source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 2cc1cb

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 2cc1cb was d76d65, checked in by Frederik Heber <heber@…>, 11 years ago

FIX: MPQCDataFragmentMap_t can be summed up in FragmentationShortRangeResults already.

  • Property mode set to 100644
File size: 26.3 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 = shortrangeresults.Result_perIndexSet_Fragment.find(index);
298 ASSERT( fragmentiter != shortrangeresults.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 std::stringstream output;
360 output << "DEBUG: graph " << iter->first
361 << " has Fragment " << iter->second.fragment
362 << ", associated energy " << iter->second.energy;
363 if (iter->second.containsGrids)
364 output << ", and sampled grid integral " << iter->second.charge_distribution.integral();
365 output << ".";
366 LOG(2, output.str());
367 }
368 }
369}
370
371// this it taken from
372// http://stackoverflow.com/questions/2291802/is-there-a-c-iterator-that-can-iterate-over-a-file-line-by-line
373namespace detail
374{
375 /** Extend the string class by a friend function.
376 *
377 */
378 class Line : public std::string
379 {
380 friend std::istream & operator>>(std::istream & is, Line & line)
381 {
382 return std::getline(is, line);
383 }
384 };
385}
386
387/** Parse the given stream line-by-line, passing each to \a dest.
388 *
389 * \param is stream to parse line-wise
390 * \param dest output iterator
391 */
392template<class OutIt>
393void read_lines(std::istream& is, OutIt dest)
394{
395 typedef std::istream_iterator<detail::Line> InIt;
396 std::copy(InIt(is), InIt(), dest);
397}
398
399
400/** Determines the largest cycle in the container and returns its size.
401 *
402 * \param cycles set of cycles
403 * \return size if largest cycle
404 */
405size_t getMaxCycleSize(const KeySetsContainer &cycles)
406{
407 // gather cycle sizes
408 std::vector<size_t> cyclesizes(cycles.KeySets.size());
409 std::transform(
410 cycles.KeySets.begin(), cycles.KeySets.end(),
411 cyclesizes.begin(),
412 boost::bind(&KeySetsContainer::IntVector::size, boost::lambda::_1)
413 );
414 // get maximum
415 std::vector<size_t>::const_iterator maximum_size =
416 std::max_element(cyclesizes.begin(), cyclesizes.end());
417 if (maximum_size != cyclesizes.end())
418 return *maximum_size;
419 else
420 return 0;
421}
422
423void calculateCycleFullContribution(
424 const std::map<JobId_t, MPQCData> &shortrangedata,
425 const KeySetsContainer &keysets,
426 const KeySetsContainer &forcekeysets,
427 const KeySetsContainer &cycles,
428 const FragmentationShortRangeResults &shortrangeresults)
429{
430 // copy the shortrangeresults such that private MaxLevel is set in
431 // FragmentationShortRangeResults
432 FragmentationShortRangeResults cycleresults(shortrangeresults);
433 // get largest size
434 const size_t maximum_size = getMaxCycleSize(cycles);
435
436 /// The idea here is that (Orthogonal)Summation will place a result
437 /// consisting of level 1,2, and 3 fragment and a level 6 ring nonetheless
438 /// in level 6. If we want to have this result already at level 3, we
439 /// have to specifically inhibit all fragments from later levels but the
440 /// cycles and then pick the result from the last level and placing it at
441 /// the desired one
442
443 // loop from level 1 to max ring size and gather contributions
444 for (size_t level = 1; level <= maximum_size; ++level) {
445 // create ValueMask for this level by stepping through each keyset and checking size
446 std::vector<bool> localValueMask(shortrangedata.size(), false);
447 size_t index=0;
448 // TODO: if only KeySetsContainer was usable as a compliant STL container, might be able to use set_difference or alike.
449 KeySetsContainer::ArrayOfIntVectors::const_iterator keysetsiter = keysets.KeySets.begin();
450 KeySetsContainer::ArrayOfIntVectors::const_iterator cyclesiter = cycles.KeySets.begin();
451 for (; (keysetsiter != keysets.KeySets.end()) && (cyclesiter != cycles.KeySets.end());) {
452 if (cyclesiter->size() > keysetsiter->size()) {
453 // add if not greater than level in size
454 if ((*keysetsiter).size() <= level)
455 localValueMask[index] = true;
456 ++keysetsiter;
457 ++index;
458 } else if (cyclesiter->size() < keysetsiter->size()) {
459 ++cyclesiter;
460 } else { // both sets have same size
461 if (*cyclesiter > *keysetsiter) {
462 // add if not greater than level in size
463 if ((*keysetsiter).size() <= level)
464 localValueMask[index] = true;
465 ++keysetsiter;
466 ++index;
467 } else if (*cyclesiter < *keysetsiter) {
468 ++cyclesiter;
469 } else {
470 // also always add all cycles
471 localValueMask[index] = true;
472 ++cyclesiter;
473 ++keysetsiter;
474 ++index;
475 }
476 }
477 }
478 // activate rest if desired by level
479 for (; keysetsiter != keysets.KeySets.end(); ++keysetsiter) {
480 if ((*keysetsiter).size() <= level)
481 localValueMask[index] = true;
482 ++index;
483 }
484 LOG(2, "DEBUG: ValueMask for cycle correction at level " << level << " is "
485 << localValueMask << ".");
486 // create FragmentationShortRangeResults
487 FragmentationShortRangeResults localresults(shortrangedata, keysets, forcekeysets, localValueMask);
488 // and perform summation
489 localresults(shortrangedata);
490 // finally, extract the corrections from last level
491 cycleresults.Result_Energy_fused[level-1] =
492 localresults.Result_Energy_fused.back();
493 cycleresults.Result_Time_fused[level-1] =
494 localresults.Result_Time_fused.back();
495 cycleresults.Result_Force_fused[level-1] =
496 localresults.Result_Force_fused.back();
497 }
498 printReceivedCycleResults(cycleresults);
499}
500
501ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
502
503 /// if file is given, parse from file into ResultsContainer
504 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
505 if (!params.resultsfile.get().empty()) {
506 boost::filesystem::path resultsfile = params.resultsfile.get();
507 if (boost::filesystem::exists(resultsfile)) {
508 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
509 std::ifstream returnstream(resultsfile.string().c_str());
510 if (returnstream.good()) {
511 boost::archive::text_iarchive ia(returnstream);
512 ia >> container;
513 }
514 } else {
515 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
516 }
517 }
518
519 /// get data and keysets from ResultsContainer
520 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
521 const KeySetsContainer &keysets = container.getKeySets();
522 const KeySetsContainer &forcekeysets = container.getForceKeySets();
523 const bool DoLongrange = container.areFullRangeResultsPresent();
524 const bool IsAngstroem = true;
525
526 if (keysets.KeySets.empty()) {
527 ELOG(2, "There are no results in the container.");
528 return Action::failure;
529 }
530
531 /// calculate normal contributions with (if present) cycles coming at their
532 /// respective bond order.
533 std::vector<bool> ValueMask(shortrangedata.size(), true);
534 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets, ValueMask);
535 shortrangeresults(shortrangedata);
536 printReceivedShortResults(shortrangeresults);
537 printReceivedShortResultsPerIndex(shortrangeresults);
538 // add summed results to container
539 container.addShortRangeSummedResults(shortrangeresults.getSummedShortRangeResults());
540
541 /// now do we need to calculate the cycle contribution
542 // check whether there are cycles in container or else in file
543 KeySetsContainer cycles = container.getCycles();
544 if (cycles.KeySets.empty()) {
545 // parse from file if cycles is empty
546 boost::filesystem::path filename(
547 params.prefix.get() + std::string(CYCLEKEYSETFILE));
548 if (boost::filesystem::exists(filename)) {
549 LOG(1, "INFO: Parsing cycles file " << filename.string() << ".");
550 // parse file line by line
551 std::ifstream File;
552 File.open(filename.string().c_str());
553 typedef std::istream_iterator<detail::Line> InIt;
554 for (InIt iter = InIt(File); iter != InIt(); ++iter) {
555 KeySetsContainer::IntVector cycle;
556 std::stringstream line(*iter);
557 while (line.good()) {
558 int id;
559 line >> id >> ws;
560 cycle.push_back(id);
561 }
562 if (!cycle.empty()) {
563 LOG(2, "DEBUG: Adding cycle " << cycle << ".");
564 cycles.insert( cycle, cycle.size());
565 }
566 }
567 File.close();
568 } else {
569 LOG(1, "INFO: Cycles file not found at " << filename.string() << ".");
570 }
571 }
572
573 // calculate energy if cycles are calculated fully at each level already
574 if (!cycles.KeySets.empty()) {
575 calculateCycleFullContribution(
576 shortrangedata,
577 keysets,
578 forcekeysets,
579 cycles,
580 shortrangeresults);
581 }
582
583 // adding obtained forces
584 if ( World::getInstance().getAllAtoms().size() != 0) {
585 const IndexedVectors::indexedvectors_t forces =
586 boost::fusion::at_key<MPQCDataFused::forces>(
587 shortrangeresults.Result_Force_fused.back()
588 ).getVectors();
589 ;
590 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
591 iter != forces.end(); ++iter) {
592 const IndexedVectors::index_t &index = iter->first;
593 const IndexedVectors::vector_t &forcevector = iter->second;
594 ASSERT( forcevector.size() == NDIM,
595 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
596 // note that mpqc calculates a gradient, hence force pointing into opposite direction
597 // we have to mind different units here: MPQC has a_o, while we may have angstroem
598 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
599 if (IsAngstroem)
600 for (size_t i=0;i<NDIM;++i)
601 ForceVector[i] *= AtomicLengthToAngstroem;
602 atom *_atom = World::getInstance().getAtom(AtomById(index));
603 if(_atom != NULL)
604 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
605 else
606 ELOG(2, "Could not find atom to id " << index << ".");
607 }
608 } else {
609 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
610 }
611
612#ifdef HAVE_VMG
613 if (DoLongrange) {
614 if ( World::getInstance().getAllAtoms().size() == 0) {
615 ELOG(1, "Please load the full molecule intostd::map<JobId_t, VMGData> longrangeData the world before starting this action.");
616 return Action::failure;
617 }
618
619 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
620 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
621
622 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
623 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
624 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
625 for (size_t i=0;i<full_sample.size();++i)
626 --iter;
627 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
628 std::vector<VMGData> fullsolutionData;
629 for (; iter != longrangeData.end(); ++iter)
630 fullsolutionData.push_back(iter->second);
631 longrangeData.erase(remove_iter, longrangeData.end());
632
633 // Final phase: sum up and print result
634 FragmentationLongRangeResults longrangeresults(
635 shortrangedata,longrangeData,keysets, forcekeysets);
636 longrangeresults(
637 shortrangedata,
638 longrangeData,
639 fullsolutionData,
640 full_sample);
641 printReceivedFullResults(longrangeresults);
642
643 // append all keysets to homology file
644 appendToHomologies(shortrangeresults, longrangeresults, params.DoStoreGrids.get());
645 } else {
646 // append all keysets to homology file with short-range info only (without grids)
647 std::map<JobId_t, VMGData> longrangeData;
648 FragmentationLongRangeResults longrangeresults(
649 shortrangedata,longrangeData,keysets, forcekeysets);
650 appendToHomologies(shortrangeresults, longrangeresults, false);
651 }
652#else
653 if (DoLongrange)
654 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
655
656 // append all keysets to homology file with short-range info only (without grids)
657 {
658 std::map<JobId_t, VMGData> longrangeData;
659 FragmentationLongRangeResults longrangeresults(
660 shortrangedata,longrangeData,keysets, forcekeysets);
661 appendToHomologies(shortrangeresults, longrangeresults, false);
662 }
663#endif
664
665 // we no longer clear the container
666// container.clear();
667
668 return Action::success;
669}
670
671ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performUndo(ActionState::ptr _state) {
672 return Action::success;
673}
674
675ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performRedo(ActionState::ptr _state){
676 return Action::success;
677}
678
679bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
680 return false;
681}
682
683bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
684 return false;
685}
686/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.