source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ d449a9

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

Split off parsing and saving of homologies into new Actions.

  • Property mode set to 100644
File size: 15.7 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 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 * AnalyseFragmentationResultsAction.cpp
26 *
27 * Created on: Mar 8, 2013
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36// include headers that implement a archive in simple text format
37// and before MemDebug due to placement new
38#include <boost/archive/text_oarchive.hpp>
39#include <boost/archive/text_iarchive.hpp>
40
41#include "CodePatterns/MemDebug.hpp"
42
43#include <boost/foreach.hpp>
44#include <boost/mpl/remove.hpp>
45
46#include <vector>
47#include <fstream>
48#include <iostream>
49#include <string>
50#include <vector>
51
52#include "CodePatterns/Assert.hpp"
53#include "CodePatterns/Log.hpp"
54
55#ifdef HAVE_JOBMARKET
56#include "JobMarket/types.hpp"
57#else
58typedef size_t JobId_t;
59#endif
60
61#include "Descriptors/AtomIdDescriptor.hpp"
62#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
63#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
64#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
65#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
66#include "Fragmentation/Summation/Containers/MPQCData.hpp"
67#include "Fragmentation/Summation/Containers/MPQCData_printKeyNames.hpp"
68#include "Fragmentation/Homology/HomologyContainer.hpp"
69#include "Fragmentation/Homology/HomologyGraph.hpp"
70#include "Fragmentation/KeySetsContainer.hpp"
71#include "Fragmentation/Summation/SetValues/Eigenvalues.hpp"
72#include "Fragmentation/Summation/SetValues/Fragment.hpp"
73#include "Fragmentation/Summation/SetValues/Histogram.hpp"
74#include "Fragmentation/Summation/SetValues/IndexedVectors.hpp"
75#include "Fragmentation/Summation/IndexSetContainer.hpp"
76#include "Fragmentation/Summation/writeTable.hpp"
77#ifdef HAVE_VMG
78#include "Fragmentation/Summation/Containers/VMGData.hpp"
79#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
80#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
81#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
82#endif
83#include "Helpers/defs.hpp"
84#include "World.hpp"
85
86#include "Actions/FragmentationAction/AnalyseFragmentationResultsAction.hpp"
87
88using namespace MoleCuilder;
89
90// and construct the stuff
91#include "AnalyseFragmentationResultsAction.def"
92#include "Action_impl_pre.hpp"
93/** =========== define the function ====================== */
94
95void writeToFile(const std::string &filename, const std::string contents)
96{
97 std::ofstream tablefile(filename.c_str());
98 tablefile << contents;
99 tablefile.close();
100}
101
102/** Print (short range) energy, forces, and timings from received results.
103 *
104 * @param results summed up results container
105 */
106void printReceivedShortResults(
107 const FragmentationShortRangeResults &results)
108{
109 // print tables (without eigenvalues, they go extra)
110 {
111 typedef boost::mpl::remove<
112 boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type,
113 MPQCDataFused::energy_eigenhistogram>::type
114 MPQCDataEnergyVector_noeigenvalues_t;
115 const std::string energyresult =
116 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
117 results.Result_Energy_fused, results.getMaxLevel());
118 LOG(2, "DEBUG: Energy table is \n" << energyresult);
119 std::string filename;
120 filename += FRAGMENTPREFIX + std::string("_Energy.dat");
121 writeToFile(filename, energyresult);
122 }
123
124 {
125 typedef boost::mpl::list<
126 MPQCDataFused::energy_eigenvalues
127 > MPQCDataEigenvalues_t;
128 const std::string eigenvalueresult =
129 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
130 results.Result_Energy_fused, results.getMaxLevel());
131 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
132 std::string filename;
133 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
134 writeToFile(filename, eigenvalueresult);
135 }
136
137 {
138 typedef boost::mpl::list<
139 MPQCDataFused::energy_eigenhistogram
140 > MPQCDataEigenhistogram_t;
141 const std::string eigenhistogramresult =
142 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenhistogram_t >()(
143 results.Result_Energy_fused, results.getMaxLevel());
144 LOG(2, "DEBUG: Eigenhistogram table is \n" << eigenhistogramresult);
145 std::string filename;
146 filename += FRAGMENTPREFIX + std::string("_Eigenhistogram.dat");
147 writeToFile(filename, eigenhistogramresult);
148 }
149
150 {
151 typedef boost::mpl::list<
152 MPQCDataFused::energy_eigenvalues
153 > MPQCDataEigenvalues_t;
154 const std::string eigenvalueresult =
155 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
156 results.Result_Energy_fused, results.getMaxLevel());
157 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
158 std::string filename;
159 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
160 writeToFile(filename, eigenvalueresult);
161 }
162
163 {
164 const std::string forceresult =
165 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
166 results.Result_Force_fused, results.getMaxLevel());
167 LOG(2, "DEBUG: Force table is \n" << forceresult);
168 std::string filename;
169 filename += FRAGMENTPREFIX + std::string("_Forces.dat");
170 writeToFile(filename, forceresult);
171 }
172 // we don't want to print grid to a table
173 {
174 // print times (without flops for now)
175 typedef boost::mpl::remove<
176 boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_total_flops>::type,
177 MPQCDataFused::times_gather_flops>::type
178 MPQCDataTimeVector_noflops_t;
179 const std::string timesresult =
180 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
181 results.Result_Time_fused, results.getMaxLevel());
182 LOG(2, "DEBUG: Times table is \n" << timesresult);
183 std::string filename;
184 filename += FRAGMENTPREFIX + std::string("_Times.dat");
185 writeToFile(filename, timesresult);
186 }
187}
188
189
190/** Print long range energy from received results.
191 *
192 * @param results summed up results container
193 */
194void printReceivedFullResults(
195 const FragmentationLongRangeResults &results)
196{
197 // print tables (without eigenvalues, they go extra)
198
199 if (results.Result_LongRange_fused.size() >= (results.getMaxLevel()-2))
200 {
201 const std::string gridresult =
202 writeTable<VMGDataMap_t, VMGDataVector_t >()(
203 results.Result_LongRange_fused, results.getMaxLevel(), 2);
204 LOG(2, "DEBUG: VMG table is \n" << gridresult);
205 std::string filename;
206 filename += FRAGMENTPREFIX + std::string("_VMGEnergy.dat");
207 writeToFile(filename, gridresult);
208 }
209
210 if (results.Result_LongRangeIntegrated_fused.size() >= (results.getMaxLevel()-2))
211 {
212 const std::string gridresult =
213 writeTable<VMGDataLongRangeMap_t, VMGDataLongRangeVector_t >()(
214 results.Result_LongRangeIntegrated_fused, results.getMaxLevel(), 2);
215 LOG(2, "DEBUG: LongRange table is \n" << gridresult);
216 std::string filename;
217 filename += FRAGMENTPREFIX + std::string("_LongRangeEnergy.dat");
218 writeToFile(filename, gridresult);
219 }
220}
221
222void appendToHomologies(
223 const FragmentationShortRangeResults &shortrangeresults,
224 const FragmentationLongRangeResults &longrangeresults
225 )
226{
227 /// read homology container (if present)
228 HomologyContainer &homology_container = World::getInstance().getHomologies();
229
230 /// append all fragments to a HomologyContainer
231 HomologyContainer::container_t values;
232
233 // convert KeySetContainer to IndexSetContainer
234 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
235 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
236 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
237 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
238 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
239
240 /// go through all fragments
241 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
242 {
243 /// create new graph entry in HomologyContainer which is (key,value) type
244 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
245 HomologyGraph graph(**forceiter);
246 LOG(2, "DEBUG: Created graph " << graph << ".");
247 const IndexSet::ptr &index = *iter;
248 HomologyContainer::value_t value;
249
250 // obtain fragment as key
251 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
252 = longrangeresults.Result_perIndexSet_Fragment.find(index);
253 ASSERT( fragmentiter != longrangeresults.Result_perIndexSet_Fragment.end(),
254 "appendToHomologyFile() - cannot find index "+toString(*index)
255 +" in FragmentResults.");
256 value.first = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
257
258 // obtain energy as value
259 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
260 = shortrangeresults.Result_perIndexSet_Energy.find(index);
261 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
262 "appendToHomologyFile() - cannot find index "+toString(*index)
263 +" in FragmentResults.");
264 // value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.first); // values
265 value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
266 values.insert( std::make_pair( graph, value) );
267 }
268 homology_container.insert(values);
269
270 if (DoLog(2)) {
271 LOG(2, "DEBUG: Listing all present atomic ids ...");
272 std::stringstream output;
273 for (World::AtomIterator iter = World::getInstance().getAtomIter();
274 iter != World::getInstance().atomEnd(); ++iter)
275 output << (*iter)->getId() << " ";
276 LOG(2, "DEBUG: { " << output.str() << "} .");
277 }
278
279 // for debugging: print container
280 if (DoLog(2)) {
281 LOG(2, "DEBUG: Listing all present homologies ...");
282 for (HomologyContainer::container_t::const_iterator iter =
283 homology_container.begin(); iter != homology_container.end(); ++iter) {
284 LOG(2, "DEBUG: graph " << iter->first << " has Fragment "
285 << iter->second.first << " and associated energy " << iter->second.second << ".");
286 }
287 }
288}
289
290Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
291
292 // if file is given, parse from file into resultscontainer
293 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
294 if (!params.resultsfile.get().empty()) {
295 boost::filesystem::path resultsfile = params.resultsfile.get();
296 if (boost::filesystem::exists(resultsfile)) {
297 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
298 std::ifstream returnstream(resultsfile.string().c_str());
299 if (returnstream.good()) {
300 boost::archive::text_iarchive ia(returnstream);
301 ia >> container;
302 }
303 } else {
304 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
305 }
306 }
307
308 // get data and keysets from ResultsContainer
309 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
310 const KeySetsContainer &keysets = container.getKeySets();
311 const KeySetsContainer &forcekeysets = container.getForceKeySets();
312 const bool DoLongrange = container.areFullRangeResultsPresent();
313 const bool IsAngstroem = true;
314
315 if (keysets.KeySets.empty()) {
316 ELOG(2, "There are no results in the container.");
317 return Action::failure;
318 }
319
320 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets);
321 shortrangeresults(shortrangedata);
322 printReceivedShortResults(shortrangeresults);
323
324 // adding obtained forces
325 if ( World::getInstance().getAllAtoms().size() != 0) {
326 const IndexedVectors::indexedvectors_t forces =
327 boost::fusion::at_key<MPQCDataFused::forces>(
328 shortrangeresults.Result_Force_fused.back()
329 ).getVectors();
330 ;
331 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
332 iter != forces.end(); ++iter) {
333 const IndexedVectors::index_t &index = iter->first;
334 const IndexedVectors::vector_t &forcevector = iter->second;
335 ASSERT( forcevector.size() == NDIM,
336 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
337 // note that mpqc calculates a gradient, hence force pointing into opposite direction
338 // we have to mind different units here: MPQC has a_o, while we may have angstroem
339 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
340 if (IsAngstroem)
341 for (size_t i=0;i<NDIM;++i)
342 ForceVector[i] *= AtomicLengthToAngstroem;
343 atom *_atom = World::getInstance().getAtom(AtomById(index));
344 if(_atom != NULL)
345 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
346 else
347 ELOG(2, "Could not find atom to id " << index << ".");
348 }
349 } else {
350 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
351 }
352
353#ifdef HAVE_VMG
354 if (DoLongrange) {
355 if ( World::getInstance().getAllAtoms().size() == 0) {
356 ELOG(1, "Please load the full molecule into the world before starting this action.");
357 return Action::failure;
358 }
359
360 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
361 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
362
363 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
364 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
365 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
366 for (size_t i=0;i<full_sample.size();++i)
367 --iter;
368 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
369 std::vector<VMGData> fullsolutionData;
370 for (; iter != longrangeData.end(); ++iter)
371 fullsolutionData.push_back(iter->second);
372 longrangeData.erase(remove_iter, longrangeData.end());
373
374 // Final phase: sum up and print result
375 FragmentationLongRangeResults longrangeresults(
376 shortrangedata,longrangeData,keysets, forcekeysets);
377 longrangeresults(
378 shortrangedata,
379 longrangeData,
380 fullsolutionData,
381 full_sample);
382 printReceivedFullResults(longrangeresults);
383
384 // append all keysets to homology file
385 appendToHomologies(shortrangeresults, longrangeresults);
386 }
387#else
388 if (DoLongrange)
389 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
390#endif
391
392 container.clear();
393
394 return Action::success;
395}
396
397Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performUndo(Action::state_ptr _state) {
398 return Action::success;
399}
400
401Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performRedo(Action::state_ptr _state){
402 return Action::success;
403}
404
405bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
406 return false;
407}
408
409bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
410 return false;
411}
412/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.