source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ cbbb6a

Candidate_v1.7.0 stable
Last change on this file since cbbb6a was cbbb6a, checked in by Frederik Heber <frederik.heber@…>, 5 years ago

FIX: AnalyseFragmentationResultsAction ignored prefix mostly.

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