source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 6367dd

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 6367dd was b5b01e, checked in by Frederik Heber <heber@…>, 11 years ago

ActionState extracted into own header file, rename Action::state_ptr -> ActionState::ptr.

  • Property mode set to 100644
File size: 17.5 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 <fstream>
47#include <iostream>
48//#include <numeric>
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 const bool storeGrids
226 )
227{
228 /// read homology container (if present)
229 HomologyContainer &homology_container = World::getInstance().getHomologies();
230
231 /// append all fragments to a HomologyContainer
232 HomologyContainer::container_t values;
233
234 // convert KeySetContainer to IndexSetContainer
235 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
236 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
237 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
238 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
239 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
240
241 /// go through all fragments
242 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
243 {
244 /// create new graph entry in HomologyContainer which is (key,value) type
245 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
246 HomologyGraph graph(**forceiter);
247 LOG(2, "DEBUG: Created graph " << graph << ".");
248 const IndexSet::ptr &index = *iter;
249
250 /// we fill the value structure
251 HomologyContainer::value_t value;
252 value.containsGrids = storeGrids;
253 // obtain fragment
254 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
255 = longrangeresults.Result_perIndexSet_Fragment.find(index);
256 ASSERT( fragmentiter != longrangeresults.Result_perIndexSet_Fragment.end(),
257 "appendToHomologyFile() - cannot find index "+toString(*index)
258 +" in FragmentResults.");
259 value.fragment = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
260
261 // obtain energy
262 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
263 = shortrangeresults.Result_perIndexSet_Energy.find(index);
264 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
265 "appendToHomologyFile() - cannot find index "+toString(*index)
266 +" in FragmentResults.");
267 value.energy = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
268
269 // only store sampled grids if desired
270 if (storeGrids) {
271 // obtain charge distribution
272 std::map<IndexSet::ptr, std::pair< MPQCDataGridMap_t, MPQCDataGridMap_t> >::const_iterator chargeiter
273 = longrangeresults.Result_perIndexSet_Grid.find(index);
274 ASSERT( chargeiter != longrangeresults.Result_perIndexSet_Grid.end(),
275 "appendToHomologyFile() - cannot find index "+toString(*index)
276 +" in FragmentResults.");
277 value.charge_distribution = boost::fusion::at_key<MPQCDataFused::sampled_grid>(chargeiter->second.second); // contributions
278
279 // obtain potential distribution
280 std::map<IndexSet::ptr, std::pair< VMGDataMap_t, VMGDataMap_t> >::const_iterator potentialiter
281 = longrangeresults.Result_perIndexSet_LongRange.find(index);
282 ASSERT( potentialiter != longrangeresults.Result_perIndexSet_LongRange.end(),
283 "appendToHomologyFile() - cannot find index "+toString(*index)
284 +" in FragmentResults.");
285 // add e+n potentials
286 value.potential_distribution = boost::fusion::at_key<VMGDataFused::both_sampled_potential>(potentialiter->second.second); // contributions
287// // and re-average to zero (integral is times volume_element which we don't need here)
288// const double sum =
289// std::accumulate(
290// value.potential_distribution.sampled_grid.begin(),
291// value.potential_distribution.sampled_grid.end(),
292// 0.);
293// const double offset = sum/(double)value.potential_distribution.sampled_grid.size();
294// for (SamplingGrid::sampledvalues_t::iterator iter = value.potential_distribution.sampled_grid.begin();
295// iter != value.potential_distribution.sampled_grid.end();
296// ++iter)
297// *iter -= offset;
298 }
299 values.insert( std::make_pair( graph, value) );
300 }
301 homology_container.insert(values);
302
303 if (DoLog(2)) {
304 LOG(2, "DEBUG: Listing all present atomic ids ...");
305 std::stringstream output;
306 for (World::AtomIterator iter = World::getInstance().getAtomIter();
307 iter != World::getInstance().atomEnd(); ++iter)
308 output << (*iter)->getId() << " ";
309 LOG(2, "DEBUG: { " << output.str() << "} .");
310 }
311
312 // for debugging: print container
313 if (DoLog(2)) {
314 LOG(2, "DEBUG: Listing all present homologies ...");
315 for (HomologyContainer::container_t::const_iterator iter =
316 homology_container.begin(); iter != homology_container.end(); ++iter) {
317 LOG(2, "DEBUG: graph " << iter->first
318 << " has Fragment " << iter->second.fragment
319 << ", associated energy " << iter->second.energy
320 << ", and sampled grid integral " << iter->second.charge_distribution.integral()
321 << ".");
322 }
323 }
324}
325
326ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
327
328 // if file is given, parse from file into resultscontainer
329 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
330 if (!params.resultsfile.get().empty()) {
331 boost::filesystem::path resultsfile = params.resultsfile.get();
332 if (boost::filesystem::exists(resultsfile)) {
333 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
334 std::ifstream returnstream(resultsfile.string().c_str());
335 if (returnstream.good()) {
336 boost::archive::text_iarchive ia(returnstream);
337 ia >> container;
338 }
339 } else {
340 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
341 }
342 }
343
344 // get data and keysets from ResultsContainer
345 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
346 const KeySetsContainer &keysets = container.getKeySets();
347 const KeySetsContainer &forcekeysets = container.getForceKeySets();
348 const bool DoLongrange = container.areFullRangeResultsPresent();
349 const bool IsAngstroem = true;
350
351 if (keysets.KeySets.empty()) {
352 ELOG(2, "There are no results in the container.");
353 return Action::failure;
354 }
355
356 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets);
357 shortrangeresults(shortrangedata);
358 printReceivedShortResults(shortrangeresults);
359
360 // adding obtained forces
361 if ( World::getInstance().getAllAtoms().size() != 0) {
362 const IndexedVectors::indexedvectors_t forces =
363 boost::fusion::at_key<MPQCDataFused::forces>(
364 shortrangeresults.Result_Force_fused.back()
365 ).getVectors();
366 ;
367 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
368 iter != forces.end(); ++iter) {
369 const IndexedVectors::index_t &index = iter->first;
370 const IndexedVectors::vector_t &forcevector = iter->second;
371 ASSERT( forcevector.size() == NDIM,
372 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
373 // note that mpqc calculates a gradient, hence force pointing into opposite direction
374 // we have to mind different units here: MPQC has a_o, while we may have angstroem
375 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
376 if (IsAngstroem)
377 for (size_t i=0;i<NDIM;++i)
378 ForceVector[i] *= AtomicLengthToAngstroem;
379 atom *_atom = World::getInstance().getAtom(AtomById(index));
380 if(_atom != NULL)
381 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
382 else
383 ELOG(2, "Could not find atom to id " << index << ".");
384 }
385 } else {
386 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
387 }
388
389#ifdef HAVE_VMG
390 if (DoLongrange) {
391 if ( World::getInstance().getAllAtoms().size() == 0) {
392 ELOG(1, "Please load the full molecule into the world before starting this action.");
393 return Action::failure;
394 }
395
396 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
397 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
398
399 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
400 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
401 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
402 for (size_t i=0;i<full_sample.size();++i)
403 --iter;
404 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
405 std::vector<VMGData> fullsolutionData;
406 for (; iter != longrangeData.end(); ++iter)
407 fullsolutionData.push_back(iter->second);
408 longrangeData.erase(remove_iter, longrangeData.end());
409
410 // Final phase: sum up and print result
411 FragmentationLongRangeResults longrangeresults(
412 shortrangedata,longrangeData,keysets, forcekeysets);
413 longrangeresults(
414 shortrangedata,
415 longrangeData,
416 fullsolutionData,
417 full_sample);
418 printReceivedFullResults(longrangeresults);
419
420 // append all keysets to homology file
421 appendToHomologies(shortrangeresults, longrangeresults, params.DoStoreGrids.get());
422 }
423#else
424 if (DoLongrange)
425 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
426#endif
427
428 container.clear();
429
430 return Action::success;
431}
432
433ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performUndo(ActionState::ptr _state) {
434 return Action::success;
435}
436
437ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performRedo(ActionState::ptr _state){
438 return Action::success;
439}
440
441bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
442 return false;
443}
444
445bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
446 return false;
447}
448/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.