source: src/moleculelist.cpp@ dadc74

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 Candidate_v1.7.0 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 dadc74 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
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"
[d127c8]28#include "Tesselation/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"
[3bdb6d]34#include "Element/element.hpp"
[dadc74]35#include "Fragmentation/Graph.hpp"
[f0674a]36#include "Fragmentation/KeySet.hpp"
[129204]37#include "Graph/BondGraph.hpp"
[952f38]38#include "Helpers/helpers.hpp"
[583081]39#include "LinearAlgebra/RealSpaceMatrix.hpp"
[e138de]40#include "linkedcell.hpp"
41#include "molecule.hpp"
[f7c19e]42#include "Parser/MpqcParser.hpp"
43#include "Parser/FormatParserStorage.hpp"
[3bdb6d]44#include "Element/periodentafel.hpp"
[d127c8]45#include "Tesselation/tesselation.hpp"
[583081]46#include "World.hpp"
47#include "WorldTime.hpp"
[920c70]48
[e138de]49/*********************************** Functions for class MoleculeListClass *************************/
50
51/** Constructor for MoleculeListClass.
52 */
[cbc5fb]53MoleculeListClass::MoleculeListClass(World *_world) :
[cd5047]54 Observable("MoleculeListClass"),
[81a9bc]55 MaxIndex(1),
56 world(_world)
[97b825]57{};
[e138de]58
59/** Destructor for MoleculeListClass.
60 */
61MoleculeListClass::~MoleculeListClass()
62{
[bd6bfa]63 DoLog(4) && (Log() << Verbose(4) << "Clearing ListOfMolecules." << endl);
64 for(MoleculeList::iterator MolRunner = ListOfMolecules.begin(); MolRunner != ListOfMolecules.end(); ++MolRunner)
65 (*MolRunner)->signOff(this);
[e138de]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{
[2ba827]74 OBSERVE;
[e138de]75 mol->IndexNr = MaxIndex++;
76 ListOfMolecules.push_back(mol);
[520c8b]77 mol->signOn(this);
[e138de]78};
79
[bd6bfa]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
[a0064e]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
[e138de]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;
[ea7176]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()) {
[e138de]125 return -1;
126 } else {
[ea7176]127 if (mol1->getAtomCount() > mol2->getAtomCount())
[e138de]128 return +1;
129 else {
[ea7176]130 Count = mol1->getAtomCount();
[e138de]131 aList = new int[Count];
132 bList = new int[Count];
133
134 // fill the lists
135 Counter = 0;
136 aCounter = 0;
137 bCounter = 0;
[ea7176]138 molecule::const_iterator aiter = mol1->begin();
139 molecule::const_iterator biter = mol2->begin();
140 for (;(aiter != mol1->end()) && (biter != mol2->end());
[9879f6]141 ++aiter, ++biter) {
142 if ((*aiter)->GetTrueFather() == NULL)
[e138de]143 aList[Counter] = Count + (aCounter++);
144 else
[735b1c]145 aList[Counter] = (*aiter)->GetTrueFather()->getNr();
[9879f6]146 if ((*biter)->GetTrueFather() == NULL)
[e138de]147 bList[Counter] = Count + (bCounter++);
148 else
[735b1c]149 bList[Counter] = (*biter)->GetTrueFather()->getNr();
[e138de]150 Counter++;
151 }
152 // check if AtomCount was for real
153 flag = 0;
[ea7176]154 if ((aiter == mol1->end()) && (biter != mol2->end())) {
[e138de]155 flag = -1;
156 } else {
[ea7176]157 if ((aiter != mol1->end()) && (biter == mol2->end()))
[e138de]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 */
[24a5e0]189void MoleculeListClass::Enumerate(ostream *out)
[e138de]190{
[ead4e6]191 periodentafel *periode = World::getInstance().getPeriode();
192 std::map<atomicNumber_t,unsigned int> counts;
[e138de]193 double size=0;
194 Vector Origin;
195
196 // header
[835a0f]197 (*out) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
198 (*out) << "-----------------------------------------------" << endl;
[e138de]199 if (ListOfMolecules.size() == 0)
[835a0f]200 (*out) << "\tNone" << endl;
[e138de]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.;
[9879f6]206 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
[d74077]207 counts[(*iter)->getType()->getNumber()]++;
208 if ((*iter)->DistanceSquared(Origin) > size)
209 size = (*iter)->DistanceSquared(Origin);
[e138de]210 }
211 // output Index, Name, number of atoms, chemical formula
[ea7176]212 (*out) << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->getAtomCount() << "\t";
[ead4e6]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;
[e138de]218 }
219 // Center and size
[1883f9]220 Vector *Center = (*ListRunner)->DetermineCenterOfAll();
221 (*out) << "\t" << *Center << "\t" << sqrt(size) << endl;
222 delete(Center);
[e138de]223 }
224 }
225};
226
227/** Returns the molecule with the given index \a index.
228 * \param index index of the desired molecule
[1907a7]229 * \return pointer to molecule structure, NULL if not found
[e138de]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{
[a67d19]245 DoLog(1) && (Log() << Verbose(1) << "MoleculeList: ");
[e138de]246 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
[a67d19]247 DoLog(0) && (Log() << Verbose(0) << *ListRunner << "\t");
248 DoLog(0) && (Log() << Verbose(0) << endl);
[e138de]249};
250
[0d0316]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
[e138de]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.
[35b698]283 * \param &path path to file
[e138de]284 */
[35b698]285bool MoleculeListClass::AddHydrogenCorrection(std::string &path)
[e138de]286{
[5e2f80]287 const bond *Binder = NULL;
[e138de]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
[a67d19]299 DoLog(1) && (Log() << Verbose(1) << "Saving hydrogen saturation correction ... ");
[e138de]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());
[35b698]306 if (input.fail()) {
[a67d19]307 DoLog(1) && (Log() << Verbose(1) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
[e138de]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 }
[a67d19]324 DoLog(0) && (Log() << Verbose(0) << "I recognized " << a << " columns and " << b << " rows, ");
[e138de]325 input.close();
326
327 // 0b. allocate memory for constants
[920c70]328 FitConstant = new double**[3];
[e138de]329 for (int k = 0; k < 3; k++) {
[920c70]330 FitConstant[k] = new double*[a];
[e138de]331 for (int i = a; i--;) {
[920c70]332 FitConstant[k][i] = new double[b];
333 for (int j = b; j--;) {
334 FitConstant[k][i][j] = 0.;
335 }
[e138de]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());
[f7c19e]347 if (input.fail()) {
[58ed4a]348 DoeLog(0) && (eLog()<< Verbose(0) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
[e359a8]349 performCriticalExit();
[e138de]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++) {
[a67d19]370 DoLog(0) && (Log() << Verbose(0) << "Constants " << k << ":" << endl);
[e138de]371 for (int j = 0; j < b; j++) {
372 for (int i = 0; i < a; i++) {
[a67d19]373 DoLog(0) && (Log() << Verbose(0) << FitConstant[k][i][j] << "\t");
[e138de]374 }
[a67d19]375 DoLog(0) && (Log() << Verbose(0) << endl);
[e138de]376 }
[a67d19]377 DoLog(0) && (Log() << Verbose(0) << endl);
[e138de]378 }
379
380 // 0d. allocate final correction matrix
[920c70]381 correction = new double*[a];
[e138de]382 for (int i = a; i--;)
[920c70]383 correction[i] = new double[b];
[e138de]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
[9879f6]392 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
[9d83b6]393 //Log() << Verbose(1) << "(*iter): " << *(*iter) << " with first bond " << *((*iter)->getListOfBonds().begin()) << "." << endl;
[83f176]394 if (((*iter)->getType()->getAtomicNumber() == 1) && (((*iter)->father == NULL)
395 || ((*iter)->father->getType()->getAtomicNumber() != 1))) { // if it's a hydrogen
[9879f6]396 for (molecule::const_iterator runner = (*ListRunner)->begin(); runner != (*ListRunner)->end(); ++runner) {
[9d83b6]397 //Log() << Verbose(2) << "Runner: " << *(*runner) << " with first bond " << *((*iter)->getListOfBonds().begin()) << "." << endl;
[e138de]398 // 3. take every other hydrogen that is the not the first and not bound to same bonding partner
[5e2f80]399 const BondList &bondlist = (*runner)->getListOfBonds();
400 Binder = *(bondlist.begin());
[735b1c]401 if (((*runner)->getType()->getAtomicNumber() == 1) && ((*runner)->getNr() > (*iter)->getNr()) && (Binder->GetOtherAtom((*runner)) != Binder->GetOtherAtom((*iter)))) { // (hydrogens have only one bonding partner!)
[e138de]402 // 4. evaluate the morse potential for each matrix component and add up
[d74077]403 distance = (*runner)->distance(*(*iter));
[9879f6]404 //Log() << Verbose(0) << "Fragment " << (*ListRunner)->name << ": " << *(*runner) << "<= " << distance << "=>" << *(*iter) << ":" << endl;
[e138de]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;
[920c70]432 delete[] (FragmentNumber);
[e138de]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 }
[920c70]443 for (int i = a; i--;)
444 delete[](correction[i]);
445 delete[](correction);
446
[e138de]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--;) {
[920c70]461 delete[](FitConstant[k][i]);
[e138de]462 }
[920c70]463 delete[](FitConstant[k]);
[e138de]464 }
[920c70]465 delete[](FitConstant);
[a67d19]466 DoLog(0) && (Log() << Verbose(0) << "done." << endl);
[e138de]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.
[35b698]471 * \param &path path to file
[e138de]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 */
[35b698]475bool MoleculeListClass::StoreForcesFile(std::string &path, int *SortIndex)
[e138de]476{
477 bool status = true;
[35b698]478 string filename(path);
479 filename += FORCESFILE;
480 ofstream ForcesFile(filename.c_str());
[ead4e6]481 periodentafel *periode=World::getInstance().getPeriode();
[e138de]482
483 // open file for the force factors
[a67d19]484 DoLog(1) && (Log() << Verbose(1) << "Saving force factors ... ");
[35b698]485 if (!ForcesFile.fail()) {
[e138de]486 //Log() << Verbose(1) << "Final AtomicForcesList: ";
487 //output << prefix << "Forces" << endl;
488 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
[ead4e6]489 periodentafel::const_iterator elemIter;
490 for(elemIter=periode->begin();elemIter!=periode->end();++elemIter){
[389cc8]491 if ((*ListRunner)->hasElement((*elemIter).first)) { // if this element got atoms
[a7b761b]492 for(molecule::iterator atomIter = (*ListRunner)->begin(); atomIter !=(*ListRunner)->end();++atomIter){
[d74077]493 if ((*atomIter)->getType()->getNumber() == (*elemIter).first) {
[a7b761b]494 if (((*atomIter)->GetTrueFather() != NULL) && ((*atomIter)->GetTrueFather() != (*atomIter))) {// if there is a rea
[e138de]495 //Log() << Verbose(0) << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
[735b1c]496 ForcesFile << SortIndex[(*atomIter)->GetTrueFather()->getNr()] << "\t";
[e138de]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();
[a67d19]507 DoLog(1) && (Log() << Verbose(1) << "done." << endl);
[e138de]508 } else {
509 status = false;
[35b698]510 DoLog(1) && (Log() << Verbose(1) << "failed to open file " << filename << "." << endl);
[e138de]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
[35b698]519 * \param &prefix path and prefix to the fragment config files
[e138de]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 */
[35b698]523bool MoleculeListClass::OutputConfigForListOfFragments(std::string &prefix, int *SortIndex)
[e138de]524{
525 ofstream outputFragment;
[35b698]526 std::string FragmentName;
[e138de]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;
[cca9ef]535 RealSpaceMatrix cell_size = World::getInstance().getDomain().getM();
536 RealSpaceMatrix cell_size_backup = cell_size;
[3c58f8]537 int count=0;
[e138de]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
[35b698]542 path = World::getInstance().getConfig()->GetDefaultPath();
[e138de]543 if (path != NULL)
544 strcpy(PathBackup, path);
[e359a8]545 else {
[efe516]546 ELOG(0, "OutputConfigForListOfFragments: NULL default path obtained from config!");
[e359a8]547 performCriticalExit();
548 }
[e138de]549
550 // correct periodic
[3c58f8]551 if ((*ListRunner)->ScanForPeriodicCorrection()) {
552 count++;
553 }
[e138de]554
[efe516]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 }
[e138de]564
[efe516]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();
[e138de]580 }
581
582 // center on edge
583 (*ListRunner)->CenterEdge(&BoxDimension);
[4c2643]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.;
[e138de]587 (*ListRunner)->SetBoxDimension(&BoxDimension); // update Box of atoms by boundary
588 for (int k = 0; k < NDIM; k++) {
[35b698]589 BoxDimension[k] = 2.5 * (World::getInstance().getConfig()->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
[84c494]590 cell_size.at(k,k) = BoxDimension[k] * 2.;
[e138de]591 }
[84c494]592 World::getInstance().setDomain(cell_size);
[e138de]593 (*ListRunner)->Translate(&BoxDimension);
594
595 // change path in config
[35b698]596 FragmentName = PathBackup;
597 FragmentName += "/";
598 FragmentName += FRAGMENTPREFIX;
599 FragmentName += FragmentNumber;
600 FragmentName += "/";
601 World::getInstance().getConfig()->SetDefaultPath(FragmentName.c_str());
[e138de]602
[efe516]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 }
[e138de]615
616 // restore old config
[35b698]617 World::getInstance().getConfig()->SetDefaultPath(PathBackup);
[e138de]618
[efe516]619 {
620 // and save as mpqc input file
621 stringstream output;
[f7c19e]622 FragmentName = prefix + FragmentNumber + ".conf.in";
[efe516]623 output << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ... ";
[f7c19e]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());
[765f16]630 FormatParserStorage::getInstance().get(mpqc).save(&outfile, atoms);
[f7c19e]631// if ((intermediateResult = World::getInstance().getConfig()->SaveMPQC(FragmentName.c_str(), (*ListRunner))))
[efe516]632 output << " done.";
[f7c19e]633// else
634// output << " failed.";
[efe516]635 LOG(3, output.str());
636 }
[e138de]637
638 result = result && intermediateResult;
639 //outputFragment.close();
640 //outputFragment.clear();
[920c70]641 delete[](FragmentNumber);
[e138de]642 }
[efe516]643 LOG(0, "STATUS: done.");
[e138de]644
645 // printing final number
[efe516]646 LOG(2, "INFO: Final number of fragments: " << FragmentCounter << ".");
[e138de]647
[3c58f8]648 // printing final number
[efe516]649 LOG(2, "INFO: For " << count << " fragments periodic correction would have been necessary.");
[3c58f8]650
[b34306]651 // restore cell_size
[84c494]652 World::getInstance().setDomain(cell_size_backup);
[e138de]653
654 return result;
655};
656
657/** Counts the number of molecules with the molecule::ActiveFlag set.
[1907a7]658 * \return number of molecules with ActiveFlag set to true.
[e138de]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
[568be7]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++) {
[9879f6]676 AtomNo += (*MolWalker)->size();
[568be7]677 }
678 return AtomNo;
679}
680
[477bb2]681/***********
682 * Methods Moved here from the menus
683 */
[568be7]684
[477bb2]685void MoleculeListClass::createNewMolecule(periodentafel *periode) {
[2ba827]686 OBSERVE;
[477bb2]687 molecule *mol = NULL;
[23b547]688 mol = World::getInstance().createMolecule();
[477bb2]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;
[23b547]697 mol = World::getInstance().createMolecule();
[477bb2]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);
[cca9ef]705 RealSpaceMatrix domain;
[84c494]706 for(int i =0;i<NDIM;++i)
707 domain.at(i,i) = center[i];
708 World::getInstance().setDomain(domain);
[477bb2]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);
[23b547]753 World::getInstance().destroyMolecule(mol);
[477bb2]754 break;
755 }
756};
757
[77675f]758
[e138de]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)
[97b825]766MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf = NULL) :
767 Leaf(NULL),
768 previous(PreviousLeaf)
[e138de]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) {
[00b59d5]800 Leaf->removeAtomsinMolecule();
[23b547]801 World::getInstance().destroyMolecule(Leaf);
[e138de]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
[5309ba]834 * \param *AtomMask defines true/false per global Atom::Nr to mask in/out each nuclear site
[e138de]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{
[9879f6]840 atom *Father = NULL;
[e138de]841
842 if (RootStack != NULL) {
843 // find first root candidates
844 if (&(RootStack[FragmentCounter]) != NULL) {
845 RootStack[FragmentCounter].clear();
[9879f6]846 for(molecule::const_iterator iter = Leaf->begin(); iter != Leaf->end(); ++iter) {
847 Father = (*iter)->GetTrueFather();
[735b1c]848 if (AtomMask[Father->getNr()]) // apply mask
[e138de]849#ifdef ADDHYDROGEN
[83f176]850 if ((*iter)->getType()->getAtomicNumber() != 1) // skip hydrogen
[e138de]851#endif
[735b1c]852 RootStack[FragmentCounter].push_front((*iter)->getNr());
[e138de]853 }
854 if (next != NULL)
855 next->FillRootStackForSubgraphs(RootStack, AtomMask, ++FragmentCounter);
856 } else {
[a67d19]857 DoLog(1) && (Log() << Verbose(1) << "Rootstack[" << FragmentCounter << "] is NULL." << endl);
[e138de]858 return false;
859 }
860 FragmentCounter--;
861 return true;
862 } else {
[a67d19]863 DoLog(1) && (Log() << Verbose(1) << "Rootstack is NULL." << endl);
[e138de]864 return false;
865 }
866};
867
[5309ba]868/** The indices per keyset are compared to the respective father's Atom::Nr in each subgraph and thus put into \a **&FragmentList.
[e138de]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
[a67d19]883 DoLog(1) && (Log() << Verbose(1) << "Begin of AssignKeySetsToFragment." << endl);
[e138de]884 // fill ListOfLocalAtoms if NULL was given
[c6123b]885 if (!Leaf->FillListOfLocalAtoms(ListOfLocalAtoms[FragmentCounter], reference->getAtomCount())) {
[a67d19]886 DoLog(1) && (Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl);
[e138de]887 return false;
888 }
889
890 // allocate fragment list
891 if (FragmentList == NULL) {
892 KeySetCounter = Count();
[920c70]893 FragmentList = new Graph*[KeySetCounter];
894 for (int i=0;i<KeySetCounter;i++)
895 FragmentList[i] = NULL;
[e138de]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!
[735b1c]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
[e138de]906 // translate keyset to local numbers
907 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
[735b1c]908 TempSet->insert(ListOfLocalAtoms[FragmentCounter][reference->FindAtom(*sprinter)->getNr()]->getNr());
[e138de]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
[a67d19]916 DoLog(1) && (Log() << Verbose(1) << "KeySetCounter is zero, deleting FragmentList." << endl);
[e138de]917 delete (FragmentList[FragmentCounter]);
918 } else
[a67d19]919 DoLog(1) && (Log() << Verbose(1) << KeySetCounter << " keysets were assigned to subgraph " << FragmentCounter << "." << endl);
[e138de]920 FragmentCounter++;
921 if (next != NULL)
922 next->AssignKeySetsToFragment(reference, KeySetList, ListOfLocalAtoms, FragmentList, FragmentCounter, FreeList);
923 FragmentCounter--;
924 } else
[a67d19]925 DoLog(1) && (Log() << Verbose(1) << "KeySetList is NULL or empty." << endl);
[e138de]926
927 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
928 // free the index lookup list
[920c70]929 delete[](ListOfLocalAtoms[FragmentCounter]);
[e138de]930 }
[a67d19]931 DoLog(1) && (Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl);
[e138de]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{
[a67d19]944 DoLog(1) && (Log() << Verbose(1) << "Begin of TranslateIndicesToGlobalIDs." << endl);
[e138de]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++)
[735b1c]949 TempSet->insert((Leaf->FindAtom(*sprinter))->GetTrueFather()->getNr());
[e138de]950 TotalGraph.insert(GraphPair(*TempSet, pair<int, double> (TotalNumberOfKeySets++, (*runner).second.second)));
951 TempSet->clear();
952 }
953 delete (TempSet);
954 } else {
[a67d19]955 DoLog(1) && (Log() << Verbose(1) << "FragmentList is NULL." << endl);
[e138de]956 }
957 if (next != NULL)
958 next->TranslateIndicesToGlobalIDs(FragmentList, ++FragmentCounter, TotalNumberOfKeySets, TotalGraph);
959 FragmentCounter--;
[a67d19]960 DoLog(1) && (Log() << Verbose(1) << "End of TranslateIndicesToGlobalIDs." << endl);
[e138de]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.