source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 83a425

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

Split off sampled_potential im VMGDataMap_t into separate fusion container.

  • this should correct the output in ..._VMGEnergy.dat
  • Property mode set to 100644
File size: 26.9 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 * 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/lambda/lambda.hpp>
45#include <boost/mpl/remove.hpp>
46
47#include <algorithm>
48#include <fstream>
49#include <iostream>
50//#include <numeric>
51#include <string>
52#include <vector>
53
54#include "CodePatterns/Assert.hpp"
55#include "CodePatterns/Log.hpp"
56
57#ifdef HAVE_JOBMARKET
58#include "JobMarket/types.hpp"
59#else
60typedef size_t JobId_t;
61#endif
62
63#include "Descriptors/AtomIdDescriptor.hpp"
64#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
65#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
66#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
67#include "Fragmentation/Summation/Containers/MPQCData.hpp"
68#include "Fragmentation/Summation/Containers/MPQCData_printKeyNames.hpp"
69#include "Fragmentation/Homology/HomologyContainer.hpp"
70#include "Fragmentation/Homology/HomologyGraph.hpp"
71#include "Fragmentation/KeySetsContainer.hpp"
72#include "Fragmentation/Summation/SetValues/Eigenvalues.hpp"
73#include "Fragmentation/Summation/SetValues/Fragment.hpp"
74#include "Fragmentation/Summation/SetValues/FragmentForces.hpp"
75#include "Fragmentation/Summation/SetValues/Histogram.hpp"
76#include "Fragmentation/Summation/SetValues/IndexedVectors.hpp"
77#include "Fragmentation/Summation/IndexSetContainer.hpp"
78#include "Fragmentation/Summation/writeIndexedTable.hpp"
79#include "Fragmentation/Summation/writeTable.hpp"
80#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
81#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
82#include "Fragmentation/Summation/Containers/VMGData.hpp"
83#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
84#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
85#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
86#endif
87#include "Helpers/defs.hpp"
88#include "World.hpp"
89
90#include "Actions/FragmentationAction/AnalyseFragmentationResultsAction.hpp"
91
92using namespace MoleCuilder;
93
94// and construct the stuff
95#include "AnalyseFragmentationResultsAction.def"
96#include "Action_impl_pre.hpp"
97/** =========== define the function ====================== */
98
99void writeToFile(const std::string &filename, const std::string contents)
100{
101 std::ofstream tablefile(filename.c_str());
102 tablefile << contents;
103 tablefile.close();
104}
105
106/** Print cycle correction from received results.
107 *
108 * @param results summed up results container
109 */
110void printReceivedCycleResults(
111 const FragmentationShortRangeResults &results)
112{
113 typedef boost::mpl::remove<
114 boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type,
115 MPQCDataFused::energy_eigenhistogram>::type
116 MPQCDataEnergyVector_noeigenvalues_t;
117 const std::string energyresult =
118 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
119 results.Result_Energy_fused, results.getMaxLevel());
120 LOG(2, "DEBUG: Energy table is \n" << energyresult);
121 std::string filename;
122 filename += FRAGMENTPREFIX + std::string("_CycleEnergy.dat");
123 writeToFile(filename, energyresult);
124}
125
126/** Print (short range) energy, forces, and timings from received results per index set.
127 *
128 * @param results summed up results container
129 */
130void printReceivedShortResultsPerIndex(
131 const FragmentationShortRangeResults &results)
132{
133 // print tables per keyset(without eigenvalues, they go extra)
134 typedef boost::mpl::remove<
135 boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type,
136 MPQCDataFused::energy_eigenhistogram>::type
137 MPQCDataEnergyVector_noeigenvalues_t;
138 const std::string energyresult =
139 writeIndexedTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
140 results.Result_perIndexSet_Energy, results.getMaxLevel());
141 LOG(2, "DEBUG: Indexed Energy table is \n" << energyresult);
142 std::string filename;
143 filename += FRAGMENTPREFIX + std::string("_IndexedEnergy.dat");
144 writeToFile(filename, energyresult);
145}
146
147/** Print (short range) energy, forces, and timings from received results.
148 *
149 * @param results summed up results container
150 */
151void printReceivedShortResults(
152 const FragmentationShortRangeResults &results)
153{
154 // print tables (without eigenvalues, they go extra)
155 {
156 typedef boost::mpl::remove<
157 boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type,
158 MPQCDataFused::energy_eigenhistogram>::type
159 MPQCDataEnergyVector_noeigenvalues_t;
160 const std::string energyresult =
161 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
162 results.Result_Energy_fused, results.getMaxLevel());
163 LOG(2, "DEBUG: Energy table is \n" << energyresult);
164 std::string filename;
165 filename += FRAGMENTPREFIX + std::string("_Energy.dat");
166 writeToFile(filename, energyresult);
167 }
168
169 {
170 typedef boost::mpl::list<
171 MPQCDataFused::energy_eigenvalues
172 > MPQCDataEigenvalues_t;
173 const std::string eigenvalueresult =
174 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
175 results.Result_Energy_fused, results.getMaxLevel());
176 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
177 std::string filename;
178 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
179 writeToFile(filename, eigenvalueresult);
180 }
181
182 {
183 typedef boost::mpl::list<
184 MPQCDataFused::energy_eigenhistogram
185 > MPQCDataEigenhistogram_t;
186 const std::string eigenhistogramresult =
187 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenhistogram_t >()(
188 results.Result_Energy_fused, results.getMaxLevel());
189 LOG(2, "DEBUG: Eigenhistogram table is \n" << eigenhistogramresult);
190 std::string filename;
191 filename += FRAGMENTPREFIX + std::string("_Eigenhistogram.dat");
192 writeToFile(filename, eigenhistogramresult);
193 }
194
195 {
196 typedef boost::mpl::list<
197 MPQCDataFused::energy_eigenvalues
198 > MPQCDataEigenvalues_t;
199 const std::string eigenvalueresult =
200 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
201 results.Result_Energy_fused, results.getMaxLevel());
202 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
203 std::string filename;
204 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
205 writeToFile(filename, eigenvalueresult);
206 }
207
208 {
209 const std::string forceresult =
210 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
211 results.Result_Force_fused, results.getMaxLevel());
212 LOG(2, "DEBUG: Force table is \n" << forceresult);
213 std::string filename;
214 filename += FRAGMENTPREFIX + std::string("_Forces.dat");
215 writeToFile(filename, forceresult);
216 }
217 // we don't want to print grid to a table
218 {
219 // print times (without flops for now)
220 typedef boost::mpl::remove<
221 boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_total_flops>::type,
222 MPQCDataFused::times_gather_flops>::type
223 MPQCDataTimeVector_noflops_t;
224 const std::string timesresult =
225 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
226 results.Result_Time_fused, results.getMaxLevel());
227 LOG(2, "DEBUG: Times table is \n" << timesresult);
228 std::string filename;
229 filename += FRAGMENTPREFIX + std::string("_Times.dat");
230 writeToFile(filename, timesresult);
231 }
232}
233
234
235#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
236/** Print long range energy from received results.
237 *
238 * @param results summed up results container
239 */
240void printReceivedFullResults(
241 const FragmentationLongRangeResults &results)
242{
243 // print tables per keyset(without grids, they go extra)
244
245 {
246 const std::string gridresult =
247 writeTable<VMGDataMap_t, VMGDataVector_t >()(
248 results.Result_LongRange_fused, results.getMaxLevel(), 1);
249 LOG(2, "DEBUG: VMG table is \n" << gridresult);
250 std::string filename;
251 filename += FRAGMENTPREFIX + std::string("_VMGEnergy.dat");
252 writeToFile(filename, gridresult);
253 }
254
255 {
256 const std::string gridresult =
257 writeTable<VMGDataLongRangeMap_t, VMGDataLongRangeVector_t >()(
258 results.Result_LongRangeIntegrated_fused, results.getMaxLevel(), 1);
259 LOG(2, "DEBUG: LongRange table is \n" << gridresult);
260 std::string filename;
261 filename += FRAGMENTPREFIX + std::string("_LongRangeEnergy.dat");
262 writeToFile(filename, gridresult);
263 }
264}
265#endif
266
267void appendToHomologies(
268 const FragmentationShortRangeResults &shortrangeresults,
269#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
270 const FragmentationLongRangeResults &longrangeresults,
271#endif
272 const bool storeGrids
273 )
274{
275 /// read homology container (if present)
276 HomologyContainer &homology_container = World::getInstance().getHomologies();
277
278 /// append all fragments to a HomologyContainer
279 HomologyContainer::container_t values;
280
281 // convert KeySetContainer to IndexSetContainer
282 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
283 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
284 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
285 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
286 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
287
288 /// go through all fragments
289 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
290 {
291 /// create new graph entry in HomologyContainer which is (key,value) type
292 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
293 HomologyGraph graph(**forceiter);
294 LOG(2, "DEBUG: Created graph " << graph << ".");
295 const IndexSet::ptr &index = *iter;
296
297 /// we fill the value structure
298 HomologyContainer::value_t value;
299 value.containsGrids = storeGrids;
300 // obtain fragment
301 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
302 = shortrangeresults.Result_perIndexSet_Fragment.find(index);
303 ASSERT( fragmentiter != shortrangeresults.Result_perIndexSet_Fragment.end(),
304 "appendToHomologyFile() - cannot find index "+toString(*index)
305 +" in FragmentResults.");
306 value.fragment = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
307
308 // obtain energy
309 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
310 = shortrangeresults.Result_perIndexSet_Energy.find(index);
311 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
312 "appendToHomologyFile() - cannot find index "+toString(*index)
313 +" in FragmentResults.");
314 value.energy = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
315
316 // only store sampled grids if desired
317 if (storeGrids) {
318#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
319 // obtain charge distribution
320 std::map<IndexSet::ptr, std::pair< MPQCDataGridMap_t, MPQCDataGridMap_t> >::const_iterator chargeiter
321 = longrangeresults.Result_perIndexSet_Grid.find(index);
322 ASSERT( chargeiter != longrangeresults.Result_perIndexSet_Grid.end(),
323 "appendToHomologyFile() - cannot find index "+toString(*index)
324 +" in FragmentResults.");
325 value.charge_distribution = boost::fusion::at_key<MPQCDataFused::sampled_grid>(chargeiter->second.second); // contributions
326
327 // obtain potential distribution
328 std::map<IndexSet::ptr, std::pair< VMGDataGridMap_t, VMGDataGridMap_t> >::const_iterator potentialiter
329 = longrangeresults.Result_perIndexSet_LongRange_Grid.find(index);
330 ASSERT( potentialiter != longrangeresults.Result_perIndexSet_LongRange_Grid.end(),
331 "appendToHomologyFile() - cannot find index "+toString(*index)
332 +" in FragmentResults.");
333 // add e+n potentials
334 value.potential_distribution =
335 boost::fusion::at_key<VMGDataFused::both_sampled_potential>(potentialiter->second.second); // contributions
336// // and re-average to zero (integral is times volume_element which we don't need here)
337// const double sum =
338// std::accumulate(
339// value.potential_distribution.sampled_grid.begin(),
340// value.potential_distribution.sampled_grid.end(),
341// 0.);
342// const double offset = sum/(double)value.potential_distribution.sampled_grid.size();
343// for (SamplingGrid::sampledvalues_t::iterator iter = value.potential_distribution.sampled_grid.begin();
344// iter != value.potential_distribution.sampled_grid.end();
345// ++iter)
346// *iter -= offset;
347#else
348 ELOG(1, "Long-range information in homology desired but long-range analysis capability not compiled in.");
349#endif
350 }
351 values.insert( std::make_pair( graph, value) );
352 }
353 homology_container.insert(values);
354
355 if (DoLog(2)) {
356 LOG(2, "DEBUG: Listing all present atomic ids ...");
357 std::stringstream output;
358 for (World::AtomIterator iter = World::getInstance().getAtomIter();
359 iter != World::getInstance().atomEnd(); ++iter)
360 output << (*iter)->getId() << " ";
361 LOG(2, "DEBUG: { " << output.str() << "} .");
362 }
363
364 // for debugging: print container
365 if (DoLog(2)) {
366 LOG(2, "DEBUG: Listing all present homologies ...");
367 for (HomologyContainer::container_t::const_iterator iter =
368 homology_container.begin(); iter != homology_container.end(); ++iter) {
369 std::stringstream output;
370 output << "DEBUG: graph " << iter->first
371 << " has Fragment " << iter->second.fragment
372 << ", associated energy " << iter->second.energy;
373 if (iter->second.containsGrids)
374#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
375 output << ", and sampled grid integral " << iter->second.charge_distribution.integral();
376#else
377 output << ", and there are sampled grids but capability not compiled in";
378#endif
379 output << ".";
380 LOG(2, output.str());
381 }
382 }
383}
384
385// this it taken from
386// http://stackoverflow.com/questions/2291802/is-there-a-c-iterator-that-can-iterate-over-a-file-line-by-line
387namespace detail
388{
389 /** Extend the string class by a friend function.
390 *
391 */
392 class Line : public std::string
393 {
394 friend std::istream & operator>>(std::istream & is, Line & line)
395 {
396 return std::getline(is, line);
397 }
398 };
399}
400
401/** Parse the given stream line-by-line, passing each to \a dest.
402 *
403 * \param is stream to parse line-wise
404 * \param dest output iterator
405 */
406template<class OutIt>
407void read_lines(std::istream& is, OutIt dest)
408{
409 typedef std::istream_iterator<detail::Line> InIt;
410 std::copy(InIt(is), InIt(), dest);
411}
412
413
414/** Determines the largest cycle in the container and returns its size.
415 *
416 * \param cycles set of cycles
417 * \return size if largest cycle
418 */
419size_t getMaxCycleSize(const KeySetsContainer &cycles)
420{
421 // gather cycle sizes
422 std::vector<size_t> cyclesizes(cycles.KeySets.size());
423 std::transform(
424 cycles.KeySets.begin(), cycles.KeySets.end(),
425 cyclesizes.begin(),
426 boost::bind(&KeySetsContainer::IntVector::size, boost::lambda::_1)
427 );
428 // get maximum
429 std::vector<size_t>::const_iterator maximum_size =
430 std::max_element(cyclesizes.begin(), cyclesizes.end());
431 if (maximum_size != cyclesizes.end())
432 return *maximum_size;
433 else
434 return 0;
435}
436
437void calculateCycleFullContribution(
438 const std::map<JobId_t, MPQCData> &shortrangedata,
439 const KeySetsContainer &keysets,
440 const KeySetsContainer &forcekeysets,
441 const KeySetsContainer &cycles,
442 const FragmentationShortRangeResults &shortrangeresults)
443{
444 // copy the shortrangeresults such that private MaxLevel is set in
445 // FragmentationShortRangeResults
446 FragmentationShortRangeResults cycleresults(shortrangeresults);
447 // get largest size
448 const size_t maximum_size = getMaxCycleSize(cycles);
449
450 /// The idea here is that (Orthogonal)Summation will place a result
451 /// consisting of level 1,2, and 3 fragment and a level 6 ring nonetheless
452 /// in level 6. If we want to have this result already at level 3, we
453 /// have to specifically inhibit all fragments from later levels but the
454 /// cycles and then pick the result from the last level and placing it at
455 /// the desired one
456
457 // loop from level 1 to max ring size and gather contributions
458 for (size_t level = 1; level <= maximum_size; ++level) {
459 // create ValueMask for this level by stepping through each keyset and checking size
460 std::vector<bool> localValueMask(shortrangedata.size(), false);
461 size_t index=0;
462 // TODO: if only KeySetsContainer was usable as a compliant STL container, might be able to use set_difference or alike.
463 KeySetsContainer::ArrayOfIntVectors::const_iterator keysetsiter = keysets.KeySets.begin();
464 KeySetsContainer::ArrayOfIntVectors::const_iterator cyclesiter = cycles.KeySets.begin();
465 for (; (keysetsiter != keysets.KeySets.end()) && (cyclesiter != cycles.KeySets.end());) {
466 if (cyclesiter->size() > keysetsiter->size()) {
467 // add if not greater than level in size
468 if ((*keysetsiter).size() <= level)
469 localValueMask[index] = true;
470 ++keysetsiter;
471 ++index;
472 } else if (cyclesiter->size() < keysetsiter->size()) {
473 ++cyclesiter;
474 } else { // both sets have same size
475 if (*cyclesiter > *keysetsiter) {
476 // add if not greater than level in size
477 if ((*keysetsiter).size() <= level)
478 localValueMask[index] = true;
479 ++keysetsiter;
480 ++index;
481 } else if (*cyclesiter < *keysetsiter) {
482 ++cyclesiter;
483 } else {
484 // also always add all cycles
485 localValueMask[index] = true;
486 ++cyclesiter;
487 ++keysetsiter;
488 ++index;
489 }
490 }
491 }
492 // activate rest if desired by level
493 for (; keysetsiter != keysets.KeySets.end(); ++keysetsiter) {
494 if ((*keysetsiter).size() <= level)
495 localValueMask[index] = true;
496 ++index;
497 }
498 LOG(2, "DEBUG: ValueMask for cycle correction at level " << level << " is "
499 << localValueMask << ".");
500 // create FragmentationShortRangeResults
501 FragmentationShortRangeResults localresults(shortrangedata, keysets, forcekeysets, localValueMask);
502 // and perform summation
503 localresults(shortrangedata);
504 // finally, extract the corrections from last level
505 cycleresults.Result_Energy_fused[level-1] =
506 localresults.Result_Energy_fused.back();
507 cycleresults.Result_Time_fused[level-1] =
508 localresults.Result_Time_fused.back();
509 cycleresults.Result_Force_fused[level-1] =
510 localresults.Result_Force_fused.back();
511 }
512 printReceivedCycleResults(cycleresults);
513}
514
515ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
516
517 /// if file is given, parse from file into ResultsContainer
518 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
519 if (!params.resultsfile.get().empty()) {
520 boost::filesystem::path resultsfile = params.resultsfile.get();
521 if (boost::filesystem::exists(resultsfile)) {
522 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
523 std::ifstream returnstream(resultsfile.string().c_str());
524 if (returnstream.good()) {
525 boost::archive::text_iarchive ia(returnstream);
526 ia >> container;
527 }
528 } else {
529 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
530 }
531 }
532
533 /// get data and keysets from ResultsContainer
534 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
535 const KeySetsContainer &keysets = container.getKeySets();
536 const KeySetsContainer &forcekeysets = container.getForceKeySets();
537 const bool DoLongrange = container.areFullRangeResultsPresent();
538 const bool IsAngstroem = true;
539
540 if (keysets.KeySets.empty()) {
541 STATUS("There are no results in the container.");
542 return Action::failure;
543 }
544
545 /// calculate normal contributions with (if present) cycles coming at their
546 /// respective bond order.
547 std::vector<bool> ValueMask(shortrangedata.size(), true);
548 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets, ValueMask);
549 shortrangeresults(shortrangedata);
550 printReceivedShortResults(shortrangeresults);
551 printReceivedShortResultsPerIndex(shortrangeresults);
552 // add summed results to container
553 container.addShortRangeSummedResults(shortrangeresults.getSummedShortRangeResults());
554
555 /// now do we need to calculate the cycle contribution
556 // check whether there are cycles in container or else in file
557 KeySetsContainer cycles = container.getCycles();
558 if (cycles.KeySets.empty()) {
559 // parse from file if cycles is empty
560 boost::filesystem::path filename(
561 params.prefix.get() + std::string(CYCLEKEYSETFILE));
562 if (boost::filesystem::exists(filename)) {
563 LOG(1, "INFO: Parsing cycles file " << filename.string() << ".");
564 // parse file line by line
565 std::ifstream File;
566 File.open(filename.string().c_str());
567 typedef std::istream_iterator<detail::Line> InIt;
568 for (InIt iter = InIt(File); iter != InIt(); ++iter) {
569 KeySetsContainer::IntVector cycle;
570 std::stringstream line(*iter);
571 while (line.good()) {
572 int id;
573 line >> id >> ws;
574 cycle.push_back(id);
575 }
576 if (!cycle.empty()) {
577 LOG(2, "DEBUG: Adding cycle " << cycle << ".");
578 cycles.insert( cycle, cycle.size());
579 }
580 }
581 File.close();
582 } else {
583 LOG(1, "INFO: Cycles file not found at " << filename.string() << ".");
584 }
585 }
586
587 // calculate energy if cycles are calculated fully at each level already
588 if (!cycles.KeySets.empty()) {
589 calculateCycleFullContribution(
590 shortrangedata,
591 keysets,
592 forcekeysets,
593 cycles,
594 shortrangeresults);
595 }
596
597 // adding obtained forces
598 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() != 0) {
599 const IndexedVectors::indexedvectors_t forces =
600 boost::fusion::at_key<MPQCDataFused::forces>(
601 shortrangeresults.Result_Force_fused.back()
602 ).getVectors();
603 ;
604 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
605 iter != forces.end(); ++iter) {
606 const IndexedVectors::index_t &index = iter->first;
607 const IndexedVectors::vector_t &forcevector = iter->second;
608 ASSERT( forcevector.size() == NDIM,
609 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
610 // note that mpqc calculates a gradient, hence force pointing into opposite direction
611 // we have to mind different units here: MPQC has a_o, while we may have angstroem
612 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
613 if (IsAngstroem)
614 for (size_t i=0;i<NDIM;++i)
615 ForceVector[i] *= AtomicLengthToAngstroem;
616 atom *_atom = World::getInstance().getAtom(AtomById(index));
617 if(_atom != NULL)
618 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
619 else
620 ELOG(2, "Could not find atom to id " << index << ".");
621 }
622 } else {
623 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
624 }
625
626#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
627 if (DoLongrange) {
628 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() == 0) {
629 STATUS("Please load the full molecule into std::map<JobId_t, VMGData> longrangeData the world before starting this action.");
630 return Action::failure;
631 }
632
633 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
634 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
635
636 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
637 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
638 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
639 std::advance(iter, -full_sample.size());
640 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
641 std::vector<VMGData> fullsolutionData;
642 for (; iter != longrangeData.end(); ++iter)
643 fullsolutionData.push_back(iter->second);
644 if (longrangeData.size() > 1) // when there's just a single fragment, it corresponds to full solution
645 longrangeData.erase(remove_iter, longrangeData.end());
646
647 // Final phase: sum up and print result
648 FragmentationLongRangeResults longrangeresults(
649 shortrangedata,longrangeData,keysets, forcekeysets);
650 longrangeresults(
651 shortrangedata,
652 longrangeData,
653 fullsolutionData,
654 full_sample);
655 printReceivedFullResults(longrangeresults);
656
657 // append all keysets to homology file
658 appendToHomologies(shortrangeresults, longrangeresults, params.DoStoreGrids.get());
659 } else {
660 // append all keysets to homology file with short-range info only (without grids)
661 std::map<JobId_t, VMGData> longrangeData;
662 FragmentationLongRangeResults longrangeresults(
663 shortrangedata,longrangeData,keysets, forcekeysets);
664 appendToHomologies(shortrangeresults, longrangeresults, false);
665 }
666#else
667 if (DoLongrange) {
668 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
669 }
670
671 // append all keysets to homology file with short-range info only (without grids)
672 appendToHomologies(shortrangeresults, false);
673#endif
674
675 // we no longer clear the container
676// container.clear();
677
678 return Action::success;
679}
680
681ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performUndo(ActionState::ptr _state) {
682 return Action::success;
683}
684
685ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performRedo(ActionState::ptr _state){
686 return Action::success;
687}
688
689bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
690 return false;
691}
692
693bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
694 return false;
695}
696/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.