source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 94db13

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

Again changes to obtain correct longrange forces, also forces are optional.

  • renamed particle_forces -> forces to make it consistent with MPQCData_Fused.
  • MPQCData_Fused and VMGData_Fused are structs and no longer namespace as the latter cannot serve as template arguments.
  • split off forces in VMGData into VMGDataForceMap_t and VMGDataForceVector_t.
  • changed ConvertMPQCDataToForceMap() into template function ConvertDataToForceMap(), working also on VMGDataForceMap_t.
  • this required changes in FragmentationShortRangeResults.
  • FragmentationLongRangeResults now also converts the longrange forces correctly.
  • AnalyseFragmentResults now prints also a ..VMGForces.dat file.
  • VMGData's forces are now optional to some degree and analysis chain can deal with it.
  • introducing forces we must still maintain working code when results without forces are calculated (e.g. as in the regression tests). Hence, a boolean im VMGData and FragmentationLongRangeResults states whether forces have been found or not and whether these should be summed up or not subsequently.
  • Property mode set to 100644
File size: 27.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/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 if (results.hasLongRangeForces()) {
256 const std::string forceresult =
257 writeTable<VMGDataForceMap_t, VMGDataForceVector_t>()(
258 results.Result_ForceLongRange_fused, results.getMaxLevel());
259 LOG(2, "DEBUG: Force table is \n" << forceresult);
260 std::string filename;
261 filename += FRAGMENTPREFIX + std::string("_VMGForces.dat");
262 writeToFile(filename, forceresult);
263 }
264
265 {
266 const std::string gridresult =
267 writeTable<VMGDataLongRangeMap_t, VMGDataLongRangeVector_t >()(
268 results.Result_LongRangeIntegrated_fused, results.getMaxLevel(), 1);
269 LOG(2, "DEBUG: LongRange table is \n" << gridresult);
270 std::string filename;
271 filename += FRAGMENTPREFIX + std::string("_LongRangeEnergy.dat");
272 writeToFile(filename, gridresult);
273 }
274}
275#endif
276
277void appendToHomologies(
278 const FragmentationShortRangeResults &shortrangeresults,
279#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
280 const FragmentationLongRangeResults &longrangeresults,
281#endif
282 const bool storeGrids
283 )
284{
285 /// read homology container (if present)
286 HomologyContainer &homology_container = World::getInstance().getHomologies();
287
288 /// append all fragments to a HomologyContainer
289 HomologyContainer::container_t values;
290
291 // convert KeySetContainer to IndexSetContainer
292 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
293 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
294 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
295 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
296 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
297
298 /// go through all fragments
299 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
300 {
301 /// create new graph entry in HomologyContainer which is (key,value) type
302 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
303 HomologyGraph graph(**forceiter);
304 LOG(2, "DEBUG: Created graph " << graph << ".");
305 const IndexSet::ptr &index = *iter;
306
307 /// we fill the value structure
308 HomologyContainer::value_t value;
309 value.containsGrids = storeGrids;
310 // obtain fragment
311 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
312 = shortrangeresults.Result_perIndexSet_Fragment.find(index);
313 ASSERT( fragmentiter != shortrangeresults.Result_perIndexSet_Fragment.end(),
314 "appendToHomologyFile() - cannot find index "+toString(*index)
315 +" in FragmentResults.");
316 value.fragment = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
317
318 // obtain energy
319 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
320 = shortrangeresults.Result_perIndexSet_Energy.find(index);
321 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
322 "appendToHomologyFile() - cannot find index "+toString(*index)
323 +" in FragmentResults.");
324 value.energy = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
325
326 // only store sampled grids if desired
327 if (storeGrids) {
328#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
329 // obtain charge distribution
330 std::map<IndexSet::ptr, std::pair< MPQCDataGridMap_t, MPQCDataGridMap_t> >::const_iterator chargeiter
331 = longrangeresults.Result_perIndexSet_Grid.find(index);
332 ASSERT( chargeiter != longrangeresults.Result_perIndexSet_Grid.end(),
333 "appendToHomologyFile() - cannot find index "+toString(*index)
334 +" in FragmentResults.");
335 value.charge_distribution = boost::fusion::at_key<MPQCDataFused::sampled_grid>(chargeiter->second.second); // contributions
336
337 // obtain potential distribution
338 std::map<IndexSet::ptr, std::pair< VMGDataGridMap_t, VMGDataGridMap_t> >::const_iterator potentialiter
339 = longrangeresults.Result_perIndexSet_LongRange_Grid.find(index);
340 ASSERT( potentialiter != longrangeresults.Result_perIndexSet_LongRange_Grid.end(),
341 "appendToHomologyFile() - cannot find index "+toString(*index)
342 +" in FragmentResults.");
343 // add e+n potentials
344 value.potential_distribution =
345 boost::fusion::at_key<VMGDataFused::both_sampled_potential>(potentialiter->second.second); // contributions
346// // and re-average to zero (integral is times volume_element which we don't need here)
347// const double sum =
348// std::accumulate(
349// value.potential_distribution.sampled_grid.begin(),
350// value.potential_distribution.sampled_grid.end(),
351// 0.);
352// const double offset = sum/(double)value.potential_distribution.sampled_grid.size();
353// for (SamplingGrid::sampledvalues_t::iterator iter = value.potential_distribution.sampled_grid.begin();
354// iter != value.potential_distribution.sampled_grid.end();
355// ++iter)
356// *iter -= offset;
357#else
358 ELOG(1, "Long-range information in homology desired but long-range analysis capability not compiled in.");
359#endif
360 }
361 values.insert( std::make_pair( graph, value) );
362 }
363 homology_container.insert(values);
364
365 if (DoLog(2)) {
366 LOG(2, "DEBUG: Listing all present atomic ids ...");
367 std::stringstream output;
368 for (World::AtomIterator iter = World::getInstance().getAtomIter();
369 iter != World::getInstance().atomEnd(); ++iter)
370 output << (*iter)->getId() << " ";
371 LOG(2, "DEBUG: { " << output.str() << "} .");
372 }
373
374 // for debugging: print container
375 if (DoLog(2)) {
376 LOG(2, "DEBUG: Listing all present homologies ...");
377 for (HomologyContainer::container_t::const_iterator iter =
378 homology_container.begin(); iter != homology_container.end(); ++iter) {
379 std::stringstream output;
380 output << "DEBUG: graph " << iter->first
381 << " has Fragment " << iter->second.fragment
382 << ", associated energy " << iter->second.energy;
383 if (iter->second.containsGrids)
384#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
385 output << ", and sampled grid integral " << iter->second.charge_distribution.integral();
386#else
387 output << ", and there are sampled grids but capability not compiled in";
388#endif
389 output << ".";
390 LOG(2, output.str());
391 }
392 }
393}
394
395// this it taken from
396// http://stackoverflow.com/questions/2291802/is-there-a-c-iterator-that-can-iterate-over-a-file-line-by-line
397namespace detail
398{
399 /** Extend the string class by a friend function.
400 *
401 */
402 class Line : public std::string
403 {
404 friend std::istream & operator>>(std::istream & is, Line & line)
405 {
406 return std::getline(is, line);
407 }
408 };
409}
410
411/** Parse the given stream line-by-line, passing each to \a dest.
412 *
413 * \param is stream to parse line-wise
414 * \param dest output iterator
415 */
416template<class OutIt>
417void read_lines(std::istream& is, OutIt dest)
418{
419 typedef std::istream_iterator<detail::Line> InIt;
420 std::copy(InIt(is), InIt(), dest);
421}
422
423
424/** Determines the largest cycle in the container and returns its size.
425 *
426 * \param cycles set of cycles
427 * \return size if largest cycle
428 */
429size_t getMaxCycleSize(const KeySetsContainer &cycles)
430{
431 // gather cycle sizes
432 std::vector<size_t> cyclesizes(cycles.KeySets.size());
433 std::transform(
434 cycles.KeySets.begin(), cycles.KeySets.end(),
435 cyclesizes.begin(),
436 boost::bind(&KeySetsContainer::IntVector::size, boost::lambda::_1)
437 );
438 // get maximum
439 std::vector<size_t>::const_iterator maximum_size =
440 std::max_element(cyclesizes.begin(), cyclesizes.end());
441 if (maximum_size != cyclesizes.end())
442 return *maximum_size;
443 else
444 return 0;
445}
446
447void calculateCycleFullContribution(
448 const std::map<JobId_t, MPQCData> &shortrangedata,
449 const KeySetsContainer &keysets,
450 const KeySetsContainer &forcekeysets,
451 const KeySetsContainer &cycles,
452 const FragmentationShortRangeResults &shortrangeresults)
453{
454 // copy the shortrangeresults such that private MaxLevel is set in
455 // FragmentationShortRangeResults
456 FragmentationShortRangeResults cycleresults(shortrangeresults);
457 // get largest size
458 const size_t maximum_size = getMaxCycleSize(cycles);
459
460 /// The idea here is that (Orthogonal)Summation will place a result
461 /// consisting of level 1,2, and 3 fragment and a level 6 ring nonetheless
462 /// in level 6. If we want to have this result already at level 3, we
463 /// have to specifically inhibit all fragments from later levels but the
464 /// cycles and then pick the result from the last level and placing it at
465 /// the desired one
466
467 // loop from level 1 to max ring size and gather contributions
468 for (size_t level = 1; level <= maximum_size; ++level) {
469 // create ValueMask for this level by stepping through each keyset and checking size
470 std::vector<bool> localValueMask(shortrangedata.size(), false);
471 size_t index=0;
472 // TODO: if only KeySetsContainer was usable as a compliant STL container, might be able to use set_difference or alike.
473 KeySetsContainer::ArrayOfIntVectors::const_iterator keysetsiter = keysets.KeySets.begin();
474 KeySetsContainer::ArrayOfIntVectors::const_iterator cyclesiter = cycles.KeySets.begin();
475 for (; (keysetsiter != keysets.KeySets.end()) && (cyclesiter != cycles.KeySets.end());) {
476 if (cyclesiter->size() > keysetsiter->size()) {
477 // add if not greater than level in size
478 if ((*keysetsiter).size() <= level)
479 localValueMask[index] = true;
480 ++keysetsiter;
481 ++index;
482 } else if (cyclesiter->size() < keysetsiter->size()) {
483 ++cyclesiter;
484 } else { // both sets have same size
485 if (*cyclesiter > *keysetsiter) {
486 // add if not greater than level in size
487 if ((*keysetsiter).size() <= level)
488 localValueMask[index] = true;
489 ++keysetsiter;
490 ++index;
491 } else if (*cyclesiter < *keysetsiter) {
492 ++cyclesiter;
493 } else {
494 // also always add all cycles
495 localValueMask[index] = true;
496 ++cyclesiter;
497 ++keysetsiter;
498 ++index;
499 }
500 }
501 }
502 // activate rest if desired by level
503 for (; keysetsiter != keysets.KeySets.end(); ++keysetsiter) {
504 if ((*keysetsiter).size() <= level)
505 localValueMask[index] = true;
506 ++index;
507 }
508 LOG(2, "DEBUG: ValueMask for cycle correction at level " << level << " is "
509 << localValueMask << ".");
510 // create FragmentationShortRangeResults
511 FragmentationShortRangeResults localresults(shortrangedata, keysets, forcekeysets, localValueMask);
512 // and perform summation
513 localresults(shortrangedata);
514 // finally, extract the corrections from last level
515 cycleresults.Result_Energy_fused[level-1] =
516 localresults.Result_Energy_fused.back();
517 cycleresults.Result_Time_fused[level-1] =
518 localresults.Result_Time_fused.back();
519 cycleresults.Result_Force_fused[level-1] =
520 localresults.Result_Force_fused.back();
521 }
522 printReceivedCycleResults(cycleresults);
523}
524
525ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
526
527 /// if file is given, parse from file into ResultsContainer
528 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
529 if (!params.resultsfile.get().empty()) {
530 boost::filesystem::path resultsfile = params.resultsfile.get();
531 if (boost::filesystem::exists(resultsfile)) {
532 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
533 std::ifstream returnstream(resultsfile.string().c_str());
534 if (returnstream.good()) {
535 boost::archive::text_iarchive ia(returnstream);
536 ia >> container;
537 }
538 } else {
539 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
540 }
541 }
542
543 /// get data and keysets from ResultsContainer
544 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
545 const KeySetsContainer &keysets = container.getKeySets();
546 const KeySetsContainer &forcekeysets = container.getForceKeySets();
547 const bool DoLongrange = container.areFullRangeResultsPresent();
548 const bool IsAngstroem = true;
549
550 if (keysets.KeySets.empty()) {
551 STATUS("There are no results in the container.");
552 return Action::failure;
553 }
554
555 /// calculate normal contributions with (if present) cycles coming at their
556 /// respective bond order.
557 std::vector<bool> ValueMask(shortrangedata.size(), true);
558 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets, ValueMask);
559 shortrangeresults(shortrangedata);
560 printReceivedShortResults(shortrangeresults);
561 printReceivedShortResultsPerIndex(shortrangeresults);
562 // add summed results to container
563 container.addShortRangeSummedResults(shortrangeresults.getSummedShortRangeResults());
564
565 /// now do we need to calculate the cycle contribution
566 // check whether there are cycles in container or else in file
567 KeySetsContainer cycles = container.getCycles();
568 if (cycles.KeySets.empty()) {
569 // parse from file if cycles is empty
570 boost::filesystem::path filename(
571 params.prefix.get() + std::string(CYCLEKEYSETFILE));
572 if (boost::filesystem::exists(filename)) {
573 LOG(1, "INFO: Parsing cycles file " << filename.string() << ".");
574 // parse file line by line
575 std::ifstream File;
576 File.open(filename.string().c_str());
577 typedef std::istream_iterator<detail::Line> InIt;
578 for (InIt iter = InIt(File); iter != InIt(); ++iter) {
579 KeySetsContainer::IntVector cycle;
580 std::stringstream line(*iter);
581 while (line.good()) {
582 int id;
583 line >> id >> ws;
584 cycle.push_back(id);
585 }
586 if (!cycle.empty()) {
587 LOG(2, "DEBUG: Adding cycle " << cycle << ".");
588 cycles.insert( cycle, cycle.size());
589 }
590 }
591 File.close();
592 } else {
593 LOG(1, "INFO: Cycles file not found at " << filename.string() << ".");
594 }
595 }
596
597 // calculate energy if cycles are calculated fully at each level already
598 if (!cycles.KeySets.empty()) {
599 calculateCycleFullContribution(
600 shortrangedata,
601 keysets,
602 forcekeysets,
603 cycles,
604 shortrangeresults);
605 }
606
607 // adding obtained forces
608 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() != 0) {
609 const IndexedVectors::indexedvectors_t forces =
610 boost::fusion::at_key<MPQCDataFused::forces>(
611 shortrangeresults.Result_Force_fused.back()
612 ).getVectors();
613 ;
614 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
615 iter != forces.end(); ++iter) {
616 const IndexedVectors::index_t &index = iter->first;
617 const IndexedVectors::vector_t &forcevector = iter->second;
618 ASSERT( forcevector.size() == NDIM,
619 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
620 // note that mpqc calculates a gradient, hence force pointing into opposite direction
621 // we have to mind different units here: MPQC has a_o, while we may have angstroem
622 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
623 if (IsAngstroem)
624 for (size_t i=0;i<NDIM;++i)
625 ForceVector[i] *= AtomicLengthToAngstroem;
626 atom *_atom = World::getInstance().getAtom(AtomById(index));
627 if(_atom != NULL)
628 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
629 else
630 ELOG(2, "Could not find atom to id " << index << ".");
631 }
632 } else {
633 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
634 }
635
636#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
637 if (DoLongrange) {
638 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() == 0) {
639 STATUS("Please load the full molecule into std::map<JobId_t, VMGData> longrangeData the world before starting this action.");
640 return Action::failure;
641 }
642
643 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
644 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
645
646 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
647 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
648 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
649 std::advance(iter, -full_sample.size());
650 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
651 std::vector<VMGData> fullsolutionData;
652 for (; iter != longrangeData.end(); ++iter)
653 fullsolutionData.push_back(iter->second);
654 if (longrangeData.size() > 1) // when there's just a single fragment, it corresponds to full solution
655 longrangeData.erase(remove_iter, longrangeData.end());
656
657 // Final phase: sum up and print result
658 FragmentationLongRangeResults longrangeresults(
659 shortrangedata,longrangeData,keysets, forcekeysets);
660 longrangeresults(
661 shortrangedata,
662 longrangeData,
663 fullsolutionData,
664 full_sample);
665 printReceivedFullResults(longrangeresults);
666
667 // append all keysets to homology file
668 appendToHomologies(shortrangeresults, longrangeresults, params.DoStoreGrids.get());
669 } else {
670 // append all keysets to homology file with short-range info only (without grids)
671 std::map<JobId_t, VMGData> longrangeData;
672 FragmentationLongRangeResults longrangeresults(
673 shortrangedata,longrangeData,keysets, forcekeysets);
674 appendToHomologies(shortrangeresults, longrangeresults, false);
675 }
676#else
677 if (DoLongrange) {
678 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
679 }
680
681 // append all keysets to homology file with short-range info only (without grids)
682 appendToHomologies(shortrangeresults, false);
683#endif
684
685 // we no longer clear the container
686// container.clear();
687
688 return Action::success;
689}
690
691ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performUndo(ActionState::ptr _state) {
692 return Action::success;
693}
694
695ActionState::ptr FragmentationAnalyseFragmentationResultsAction::performRedo(ActionState::ptr _state){
696 return Action::success;
697}
698
699bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
700 return false;
701}
702
703bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
704 return false;
705}
706/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.