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

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures 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_ChronosMutex 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 TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since d03800 was ea63cb, checked in by Frederik Heber <heber@…>, 9 years ago

Edges per Fragment passed on to FragmentationShortRangeResults.

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