source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 55e1bc

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

FragmentationResultContainer is serializable.

  • Property mode set to 100644
File size: 14.1 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * AnalyseFragmentationResultsAction.cpp
25 *
26 * Created on: Mar 8, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35// include headers that implement a archive in simple text format
36// and before MemDebug due to placement new
37#include <boost/archive/text_oarchive.hpp>
38#include <boost/archive/text_iarchive.hpp>
39
40#include "CodePatterns/MemDebug.hpp"
41
42#include <boost/mpl/remove.hpp>
43
44#include <vector>
45#include <fstream>
46#include <iostream>
47#include <string>
48#include <vector>
49
50#include "CodePatterns/Assert.hpp"
51#include "CodePatterns/Log.hpp"
52
53#ifdef HAVE_JOBMARKET
54#include "JobMarket/types.hpp"
55#else
56typedef size_t JobId_t;
57#endif
58
59#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
60#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
61#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
62#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
63#include "Fragmentation/Summation/Containers/MPQCData.hpp"
64#include "Fragmentation/Summation/Containers/MPQCData_printKeyNames.hpp"
65#include "Fragmentation/Homology/HomologyContainer.hpp"
66#include "Fragmentation/Homology/HomologyGraph.hpp"
67#include "Fragmentation/KeySetsContainer.hpp"
68#include "Fragmentation/Summation/SetValues/Fragment.hpp"
69#include "Fragmentation/Summation/SetValues/Histogram.hpp"
70#include "Fragmentation/Summation/SetValues/IndexedVectors.hpp"
71#include "Fragmentation/Summation/IndexSetContainer.hpp"
72#include "Fragmentation/Summation/writeTable.hpp"
73#ifdef HAVE_VMG
74#include "Fragmentation/Summation/Containers/VMGData.hpp"
75#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
76#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
77#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
78#endif
79#include "World.hpp"
80
81#include "Actions/FragmentationAction/AnalyseFragmentationResultsAction.hpp"
82
83using namespace MoleCuilder;
84
85// and construct the stuff
86#include "AnalyseFragmentationResultsAction.def"
87#include "Action_impl_pre.hpp"
88/** =========== define the function ====================== */
89
90void writeToFile(const std::string &filename, const std::string contents)
91{
92 std::ofstream tablefile(filename.c_str());
93 tablefile << contents;
94 tablefile.close();
95}
96
97/** Print (short range) energy, forces, and timings from received results.
98 *
99 * @param results summed up results container
100 */
101void printReceivedShortResults(
102 const FragmentationShortRangeResults &results)
103{
104 // print tables (without eigenvalues, they go extra)
105 {
106 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type
107 MPQCDataEnergyVector_noeigenvalues_t;
108 const std::string energyresult =
109 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
110 results.Result_Energy_fused, results.getMaxLevel());
111 LOG(0, "Energy table is \n" << energyresult);
112 std::string filename;
113 filename += FRAGMENTPREFIX + std::string("_Energy.dat");
114 writeToFile(filename, energyresult);
115 }
116
117 {
118 typedef boost::mpl::list<
119 MPQCDataFused::energy_eigenvalues
120 > MPQCDataEigenvalues_t;
121 const std::string eigenvalueresult =
122 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
123 results.Result_Energy_fused, results.getMaxLevel());
124 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
125 std::string filename;
126 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
127 writeToFile(filename, eigenvalueresult);
128 }
129
130 {
131 const std::string forceresult =
132 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
133 results.Result_Force_fused, results.getMaxLevel());
134 LOG(0, "Force table is \n" << forceresult);
135 std::string filename;
136 filename += FRAGMENTPREFIX + std::string("_Forces.dat");
137 writeToFile(filename, forceresult);
138 }
139 // we don't want to print grid to a table
140 {
141 // print times (without flops for now)
142 typedef boost::mpl::remove<
143 boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_total_flops>::type,
144 MPQCDataFused::times_gather_flops>::type
145 MPQCDataTimeVector_noflops_t;
146 const std::string timesresult =
147 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
148 results.Result_Time_fused, results.getMaxLevel());
149 LOG(0, "Times table is \n" << timesresult);
150 std::string filename;
151 filename += FRAGMENTPREFIX + std::string("_Times.dat");
152 writeToFile(filename, timesresult);
153 }
154}
155
156
157/** Print long range energy from received results.
158 *
159 * @param results summed up results container
160 */
161void printReceivedFullResults(
162 const FragmentationLongRangeResults &results)
163{
164 // print tables (without eigenvalues, they go extra)
165
166 if (results.Result_LongRange_fused.size() >= (results.getMaxLevel()-2))
167 {
168 const std::string gridresult =
169 writeTable<VMGDataMap_t, VMGDataVector_t >()(
170 results.Result_LongRange_fused, results.getMaxLevel(), 2);
171 LOG(0, "VMG table is \n" << gridresult);
172 std::string filename;
173 filename += FRAGMENTPREFIX + std::string("_VMGEnergy.dat");
174 writeToFile(filename, gridresult);
175 }
176
177 if (results.Result_LongRangeIntegrated_fused.size() >= (results.getMaxLevel()-2))
178 {
179 const std::string gridresult =
180 writeTable<VMGDataLongRangeMap_t, VMGDataLongRangeVector_t >()(
181 results.Result_LongRangeIntegrated_fused, results.getMaxLevel(), 2);
182 LOG(0, "LongRange table is \n" << gridresult);
183 std::string filename;
184 filename += FRAGMENTPREFIX + std::string("_LongRangeEnergy.dat");
185 writeToFile(filename, gridresult);
186 }
187}
188
189bool appendToHomologyFile(
190 const boost::filesystem::path &homology_file,
191 const FragmentationShortRangeResults &shortrangeresults,
192 const FragmentationLongRangeResults &longrangeresults
193 )
194{
195 /// read homology container (if present)
196 HomologyContainer homology_container;
197 if (boost::filesystem::exists(homology_file)) {
198 std::ifstream returnstream(homology_file.string().c_str());
199 if (returnstream.good()) {
200 boost::archive::text_iarchive ia(returnstream);
201 ia >> homology_container;
202 } else {
203 ELOG(2, "Failed to parse from " << homology_file.string() << ".");
204 }
205 returnstream.close();
206 } else {
207 LOG(2, "Could not open " << homology_file.string()
208 << ", creating empty container.");
209 }
210
211 /// append all fragments to a HomologyContainer
212 HomologyContainer::container_t values;
213
214 // convert KeySetContainer to IndexSetContainer
215 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
216 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
217 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
218 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
219 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
220 /// go through all fragments
221 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
222 {
223 /// create new graph entry in HomologyContainer which is (key,value) type
224 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
225 HomologyGraph graph(**forceiter);
226 LOG(2, "DEBUG: Created graph " << graph << ".");
227 const IndexSet::ptr &index = *iter;
228 HomologyContainer::value_t value;
229
230 // obtain fragment as key
231 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
232 = longrangeresults.Result_perIndexSet_Fragment.find(index);
233 ASSERT( fragmentiter != longrangeresults.Result_perIndexSet_Fragment.end(),
234 "appendToHomologyFile() - cannot find index "+toString(*index)
235 +" in FragmentResults.");
236 value.first = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
237
238 // obtain energy as value
239 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
240 = shortrangeresults.Result_perIndexSet_Energy.find(index);
241 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
242 "appendToHomologyFile() - cannot find index "+toString(*index)
243 +" in FragmentResults.");
244 // value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.first); // values
245 value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
246 values.insert( std::make_pair( graph, value) );
247 }
248 homology_container.insert(values);
249
250 LOG(1, "INFO: Listing all present atomic ids ...");
251 std::stringstream output;
252 for (World::AtomIterator iter = World::getInstance().getAtomIter();
253 iter != World::getInstance().atomEnd(); ++iter)
254 output << (*iter)->getId() << " ";
255 LOG(1, "INFO: { " << output.str() << "} .");
256
257 // for debugging: print container
258 LOG(1, "INFO: Listing all present homologies ...");
259 for (HomologyContainer::container_t::const_iterator iter =
260 homology_container.begin(); iter != homology_container.end(); ++iter) {
261 LOG(1, "INFO: graph " << iter->first << " has Fragment "
262 << iter->second.first << " and associated energy " << iter->second.second << ".");
263 }
264
265 /// store homology container again
266 std::ofstream outputstream(homology_file.string().c_str());
267 if (outputstream.good()) { // check if opened
268 boost::archive::text_oarchive oa(outputstream);
269 oa << homology_container;
270 if (outputstream.fail()) { // check if correctly written
271 LOG(1, "Failed to write to file " << homology_file.string() << ".");
272 return false;
273 } else
274 outputstream.close();
275 } else {
276 LOG(1, "Failed to open file " << homology_file.string()
277 << " for writing.");
278 return false;
279 }
280 return true;
281}
282
283Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
284
285 // if file is given, parse from file into resultscontainer
286 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
287 if (!params.resultsfile.get().empty()) {
288 boost::filesystem::path resultsfile = params.resultsfile.get();
289 if (boost::filesystem::exists(resultsfile)) {
290 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
291 std::ifstream returnstream(resultsfile.string().c_str());
292 if (returnstream.good()) {
293 boost::archive::text_iarchive ia(returnstream);
294 ia >> container;
295 }
296 } else {
297 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
298 }
299 }
300
301 // get data and keysets from ResultsContainer
302 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
303 const KeySetsContainer &keysets = container.getKeySets();
304 const KeySetsContainer &forcekeysets = container.getForceKeySets();
305 const bool DoLongrange = container.areFullRangeResultsPresent();
306
307 if (keysets.KeySets.empty()) {
308 ELOG(2, "There are no results in the container.");
309 return Action::failure;
310 }
311
312 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets);
313 shortrangeresults(shortrangedata);
314 printReceivedShortResults(shortrangeresults);
315
316#ifdef HAVE_VMG
317 if (DoLongrange) {
318 if ( World::getInstance().getAllAtoms().size() == 0) {
319 ELOG(1, "Please load the full molecule into the world before starting this action.");
320 return Action::failure;
321 }
322
323 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
324 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
325
326 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
327 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
328 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
329 for (size_t i=0;i<full_sample.size();++i)
330 --iter;
331 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
332 std::vector<VMGData> fullsolutionData;
333 for (; iter != longrangeData.end(); ++iter)
334 fullsolutionData.push_back(iter->second);
335 longrangeData.erase(remove_iter, longrangeData.end());
336
337 // Final phase: sum up and print result
338 FragmentationLongRangeResults longrangeresults(
339 shortrangedata,longrangeData,keysets, forcekeysets);
340 longrangeresults(
341 shortrangedata,
342 longrangeData,
343 fullsolutionData,
344 full_sample);
345 printReceivedFullResults(longrangeresults);
346
347 // append all keysets to homology file
348 if (!params.homology_file.get().empty()) {
349 const boost::filesystem::path &homology_file = params.homology_file.get();
350 if (homology_file.string() != "") {
351 LOG(1, "INFO: Appending HomologyGraphs to file " << homology_file.string() << ".");
352 if (!appendToHomologyFile(homology_file, shortrangeresults, longrangeresults))
353 return Action::failure;
354 }
355 }
356 }
357#endif
358
359 container.clear();
360
361 return Action::success;
362}
363
364Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performUndo(Action::state_ptr _state) {
365 return Action::success;
366}
367
368Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performRedo(Action::state_ptr _state){
369 return Action::success;
370}
371
372bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
373 return false;
374}
375
376bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
377 return false;
378}
379/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.