source: src/Fragmentation/Exporters/ExportGraph_ToFiles.cpp@ df5b8c

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

Replaced MoleculeListClass in ExportGraph by vector of molecules.

  • Property mode set to 100644
File size: 8.3 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * ExportGraph_ToFiles.cpp
26 *
27 * Created on: 08.03.2012
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "CodePatterns/MemDebug.hpp"
37
38#include "ExportGraph_ToFiles.hpp"
39
40#include "CodePatterns/Info.hpp"
41#include "CodePatterns/Log.hpp"
42
43#include "Bond/bond.hpp"
44#include "Element/element.hpp"
45#include "Fragmentation/Graph.hpp"
46#include "Fragmentation/KeySet.hpp"
47#include "Graph/ListOfLocalAtoms.hpp"
48#include "molecule.hpp"
49#include "MoleculeListClass.hpp"
50#include "Parser/FormatParserStorage.hpp"
51#include "World.hpp"
52
53/** Constructor for class ExportGraph_ToFiles.
54 *
55 * @param _graph instance of Graph containing keyset of each fragment
56 * @param _treatment whether to always add already present hydrogens or not
57 * @param _saturation whether to saturate dangling bonds with hydrogen or not
58 * @param _globalsaturationpositions possibly empty map with global information
59 * where to place saturation hydrogens to fulfill consistency principle
60 */
61ExportGraph_ToFiles::ExportGraph_ToFiles(
62 const Graph &_graph,
63 const enum HydrogenTreatment _treatment,
64 const enum HydrogenSaturation _saturation,
65 const SaturatedFragment::GlobalSaturationPositions_t &_globalsaturationpositions) :
66 ExportGraph(_graph, _treatment, _saturation, _globalsaturationpositions)
67{}
68
69/** Destructor of class ExportGraph_ToFiles.
70 *
71 * We free all created molecules again and also removed their copied atoms.
72 */
73ExportGraph_ToFiles::~ExportGraph_ToFiles()
74{}
75
76/** Returns a string with \a i prefixed with 0s to match order of total number of molecules in digits.
77 * \param FragmentNumber total number of fragments to determine necessary number of digits
78 * \param digits number to create with 0 prefixed
79 * \return allocated(!) char array with number in digits, ten base.
80 */
81static char *FixedDigitNumber(const int FragmentNumber, const int digits)
82{
83 char *returnstring;
84 int number = FragmentNumber;
85 int order = 0;
86 while (number != 0) { // determine number of digits needed
87 number = (int)floor(((double)number / 10.));
88 order++;
89 //LOG(0, "Number is " << number << ", order is " << order << ".");
90 }
91 // allocate string
92 returnstring = new char[order + 2];
93 // terminate and fill string array from end backward
94 returnstring[order] = '\0';
95 number = digits;
96 for (int i=order;i--;) {
97 returnstring[i] = '0' + (char)(number % 10);
98 number = (int)floor(((double)number / 10.));
99 }
100 //LOG(0, returnstring);
101 return returnstring;
102};
103
104/** Actual implementation of the export to files function.
105 */
106void ExportGraph_ToFiles::operator()()
107{
108 LOG(1, "INFO: Writing " << TotalGraph.size() << " possible bond fragmentation configs.");
109 size_t FragmentCounter = 0;
110 char *FragmentNumber = NULL;
111 string filename(prefix);
112 filename += FORCESFILE;
113 std::ofstream ForcesFile(filename.c_str());
114 SortIndex_t SortIndex;
115
116 // ===== 9. Save fragments' configuration and keyset files et al to disk ===
117 bool write_status = true;
118 ExportGraph::SaturatedFragment_ptr CurrentFragment = getNextFragment();
119 for (; (CurrentFragment != NULL) && (CurrentFragment->getKeySet() != ExportGraph::EmptySet);
120 CurrentFragment = getNextFragment()) {
121 const KeySet &set = CurrentFragment->getKeySet();
122 LOG(2, "INFO: Writing bond fragments for set " << set << ".");
123 // store config in stream
124 {
125 // open file
126 FragmentNumber = FixedDigitNumber(TotalGraph.size(), FragmentCounter++);
127 storeFragmentForAllTypes(
128 CurrentFragment, FragmentNumber, FragmentCounter-1);
129 delete[](FragmentNumber);
130 }
131 // store force index reference file
132 write_status = write_status
133 && appendToForcesFile(CurrentFragment, ForcesFile, SortIndex);
134 // explicitly release fragment
135 CurrentFragment.reset();
136 }
137 if (CurrentFragment == NULL) {
138 ELOG(1, "Some error while obtaining the next fragment occured.");
139 return;
140 }
141 ForcesFile.close();
142
143 if (write_status)
144 LOG(1, "All configs written.");
145 else
146 LOG(1, "Some config writing failed.");
147
148 // store keysets file
149 TotalGraph.StoreKeySetFile(prefix);
150
151 // restore orbital and Stop values
152 //CalculateOrbitals(*configuration);
153}
154
155bool ExportGraph_ToFiles::storeFragmentForAllTypes(
156 SaturatedFragment_ptr &CurrentFragment,
157 char *FragmentNumber,
158 size_t FragmentCounter) const
159{
160 bool write_status = true;
161
162 // go through all desired types
163 for (std::vector<std::string>::const_iterator typeiter = typelist.begin();
164 typeiter != typelist.end(); ++typeiter) {
165 const std::string &typeName = *typeiter;
166 const ParserTypes type =
167 FormatParserStorage::getInstance().getTypeFromName(typeName);
168 // create filenname and open
169 const std::string FragmentName =
170 prefix + FragmentNumber + "." + FormatParserStorage::getInstance().getSuffixFromType(type);
171 std::ofstream outputFragment(FragmentName.c_str(), ios::out);
172
173 // write to this stream
174 {
175 std::stringstream output;
176 output << "INFO: Saving bond fragment No. " << FragmentNumber << "/"
177 << FragmentCounter << " as " << typeName << " ... ";
178 const bool intermediate_result = CurrentFragment->OutputConfig(outputFragment,type);
179 write_status &= intermediate_result;
180 if (intermediate_result)
181 output << " done.";
182 else
183 output << " failed.";
184 LOG(2, output.str());
185 }
186
187 // close file
188 outputFragment.close();
189 outputFragment.clear();
190 }
191
192 return write_status;
193}
194
195bool ExportGraph_ToFiles::appendToForcesFile(
196 SaturatedFragment_ptr &CurrentFragment,
197 std::ostream &ForcesFile,
198 const SortIndex_t &SortIndex) const
199{
200 bool status = true;
201// periodentafel *periode=World::getInstance().getPeriode();
202
203 // open file for the force factors
204 if (ForcesFile.good()) {
205 //output << prefix << "Forces" << endl;
206 const KeySet &FullMolecule = CurrentFragment->getFullMolecule();
207 const KeySet &SaturationHydrogens = CurrentFragment->getSaturationHydrogens();
208 for (KeySet::const_iterator keyiter = FullMolecule.begin();
209 keyiter != FullMolecule.end();
210 ++keyiter) {
211 if (SaturationHydrogens.find(*keyiter) == SaturationHydrogens.end()) {
212 ForcesFile << SortIndex.find(*keyiter) << "\t";
213 } else {
214 // otherwise a -1 to indicate an added saturation hydrogen
215 ForcesFile << "-1\t";
216 }
217 }
218// for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
219// periodentafel::const_iterator elemIter;
220// for(elemIter=periode->begin();elemIter!=periode->end();++elemIter){
221// if ((*ListRunner)->hasElement((*elemIter).first)) { // if this element got atoms
222// for(molecule::iterator atomIter = (*ListRunner)->begin(); atomIter !=(*ListRunner)->end();++atomIter){
223// if ((*atomIter)->getType()->getAtomicNumber() == (*elemIter).first) {
224// if (((*atomIter)->GetTrueFather() != NULL) && ((*atomIter)->GetTrueFather() != (*atomIter))) {// if there is a rea
225// const atomId_t fatherid = (*atomIter)->GetTrueFather()->getId();
226// ForcesFile << SortIndex.find(fatherid) << "\t";
227// } else
228// // otherwise a -1 to indicate an added saturation hydrogen
229// ForcesFile << "-1\t";
230// }
231// }
232// }
233// }
234// ForcesFile << endl;
235// }
236 ForcesFile << std::endl;
237 } else {
238 status = false;
239 ELOG(1, "Failure on appending to ForcesFile.");
240 }
241
242 return status;
243}
Note: See TracBrowser for help on using the repository browser.