source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 92f978

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

Longrange energy is now also calculated for level 1.

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