source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 94232b

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 94232b was a58c16, checked in by Frederik Heber <heber@…>, 10 years ago

Replaced World::getAllAtoms() by const version where possible.

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