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

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator 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_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since d00441 was 4c648a, checked in by Frederik Heber <heber@…>, 9 years ago

UNBREAKS: No longer downsample all grids but enforce a coarser global grid for charge and potential grids.

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