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

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

Split long-range calculations into two parts to overcome E-N-potential problems.

The general problem is that smeared-out nuclei charges cannot interact with
electron charge densities as they always overlap, hence we always make a large
error. The idea then is - as the potential energy is symmetric both
densities - to flip from N-E to E-N, i.\,e. to take the electron potential and
evaluate at nuclei positions instead of smeared-out nuclei charges with
eletronic charge distribution. However, then we need to make two calculations
for the four contributions: E-E, E-N and N-N, N-E (=E-N).

  • new enums SampleParticles_t eventually tells InterfaceVMGJob whether to sample the nuclei charges onto the grid or not.
  • TreatGrid_t tells InterfaceVMGJob whether to actually add the electronic charge onto the grid (this was added but is actually not required anymore).
  • FragmentationAutomationAction::performCall() now creates twice as many long-range jobs. This requires two variables in VMGData for storing integrated long-range energy: electron_long, nuclei_long, as both calculations are combined into a single VMGData instance per fragment.
  • Summation of long-range contributions is split into three instead of formerly two parts: electron (E-E), nuclei (N-N), and mixed (E-N). This allows to easierly check their cancellation. This needs new member in fusion map and name in printKeyNames.
  • naturally, the enums have to be passed a long way: VMGFragmentController, VMGJob, VMGData.
  • VMGData now has serialization version 1 due to new entry.
  • we enhanced documentation in FragmentationLongRangeResults::operator()() of how and what is summed per level.
  • FIX: InterfaceVMGJob::ImportRightHandSide() subtracted grid instead of adding it. Now, we set correct sign of electron charge distribution in MPQC.
  • TESTFIX: Regression test AnalyseFragmentResults now has short- and long-range part. Long-range part is only diff'ed when the compiled code has the capabilities.
  • Property mode set to 100644
File size: 15.5 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * AnalyseFragmentationResultsAction.cpp
25 *
26 * Created on: Mar 8, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35// include headers that implement a archive in simple text format
36// and before MemDebug due to placement new
37#include <boost/archive/text_oarchive.hpp>
38#include <boost/archive/text_iarchive.hpp>
39
40#include "CodePatterns/MemDebug.hpp"
41
42#include <boost/mpl/remove.hpp>
43
44#include <vector>
45#include <fstream>
46#include <iostream>
47#include <string>
48#include <vector>
49
50#include "CodePatterns/Assert.hpp"
51#include "CodePatterns/Log.hpp"
52
53#ifdef HAVE_JOBMARKET
54#include "JobMarket/types.hpp"
55#else
56typedef size_t JobId_t;
57#endif
58
59#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
60#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
61#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
62#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
63#include "Fragmentation/Summation/Containers/MPQCData.hpp"
64#include "Fragmentation/Summation/Containers/MPQCData_printKeyNames.hpp"
65#include "Fragmentation/Homology/HomologyContainer.hpp"
66#include "Fragmentation/Homology/HomologyGraph.hpp"
67#include "Fragmentation/KeySetsContainer.hpp"
68#include "Fragmentation/Summation/SetValues/Eigenvalues.hpp"
69#include "Fragmentation/Summation/SetValues/Fragment.hpp"
70#include "Fragmentation/Summation/SetValues/Histogram.hpp"
71#include "Fragmentation/Summation/SetValues/IndexedVectors.hpp"
72#include "Fragmentation/Summation/IndexSetContainer.hpp"
73#include "Fragmentation/Summation/writeTable.hpp"
74#ifdef HAVE_VMG
75#include "Fragmentation/Summation/Containers/VMGData.hpp"
76#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
77#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
78#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
79#endif
80#include "World.hpp"
81
82#include "Actions/FragmentationAction/AnalyseFragmentationResultsAction.hpp"
83
84using namespace MoleCuilder;
85
86// and construct the stuff
87#include "AnalyseFragmentationResultsAction.def"
88#include "Action_impl_pre.hpp"
89/** =========== define the function ====================== */
90
91void writeToFile(const std::string &filename, const std::string contents)
92{
93 std::ofstream tablefile(filename.c_str());
94 tablefile << contents;
95 tablefile.close();
96}
97
98/** Print (short range) energy, forces, and timings from received results.
99 *
100 * @param results summed up results container
101 */
102void printReceivedShortResults(
103 const FragmentationShortRangeResults &results)
104{
105 // print tables (without eigenvalues, they go extra)
106 {
107 typedef boost::mpl::remove<
108 boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type,
109 MPQCDataFused::energy_eigenhistogram>::type
110 MPQCDataEnergyVector_noeigenvalues_t;
111 const std::string energyresult =
112 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
113 results.Result_Energy_fused, results.getMaxLevel());
114 LOG(2, "DEBUG: Energy table is \n" << energyresult);
115 std::string filename;
116 filename += FRAGMENTPREFIX + std::string("_Energy.dat");
117 writeToFile(filename, energyresult);
118 }
119
120 {
121 typedef boost::mpl::list<
122 MPQCDataFused::energy_eigenvalues
123 > MPQCDataEigenvalues_t;
124 const std::string eigenvalueresult =
125 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
126 results.Result_Energy_fused, results.getMaxLevel());
127 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
128 std::string filename;
129 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
130 writeToFile(filename, eigenvalueresult);
131 }
132
133 {
134 typedef boost::mpl::list<
135 MPQCDataFused::energy_eigenhistogram
136 > MPQCDataEigenhistogram_t;
137 const std::string eigenhistogramresult =
138 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenhistogram_t >()(
139 results.Result_Energy_fused, results.getMaxLevel());
140 LOG(2, "DEBUG: Eigenhistogram table is \n" << eigenhistogramresult);
141 std::string filename;
142 filename += FRAGMENTPREFIX + std::string("_Eigenhistogram.dat");
143 writeToFile(filename, eigenhistogramresult);
144 }
145
146 {
147 typedef boost::mpl::list<
148 MPQCDataFused::energy_eigenvalues
149 > MPQCDataEigenvalues_t;
150 const std::string eigenvalueresult =
151 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
152 results.Result_Energy_fused, results.getMaxLevel());
153 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
154 std::string filename;
155 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
156 writeToFile(filename, eigenvalueresult);
157 }
158
159 {
160 const std::string forceresult =
161 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
162 results.Result_Force_fused, results.getMaxLevel());
163 LOG(2, "DEBUG: Force table is \n" << forceresult);
164 std::string filename;
165 filename += FRAGMENTPREFIX + std::string("_Forces.dat");
166 writeToFile(filename, forceresult);
167 }
168 // we don't want to print grid to a table
169 {
170 // print times (without flops for now)
171 typedef boost::mpl::remove<
172 boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_total_flops>::type,
173 MPQCDataFused::times_gather_flops>::type
174 MPQCDataTimeVector_noflops_t;
175 const std::string timesresult =
176 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
177 results.Result_Time_fused, results.getMaxLevel());
178 LOG(2, "DEBUG: Times table is \n" << timesresult);
179 std::string filename;
180 filename += FRAGMENTPREFIX + std::string("_Times.dat");
181 writeToFile(filename, timesresult);
182 }
183}
184
185
186/** Print long range energy from received results.
187 *
188 * @param results summed up results container
189 */
190void printReceivedFullResults(
191 const FragmentationLongRangeResults &results)
192{
193 // print tables (without eigenvalues, they go extra)
194
195 if (results.Result_LongRange_fused.size() >= (results.getMaxLevel()-2))
196 {
197 const std::string gridresult =
198 writeTable<VMGDataMap_t, VMGDataVector_t >()(
199 results.Result_LongRange_fused, results.getMaxLevel(), 2);
200 LOG(2, "DEBUG: VMG table is \n" << gridresult);
201 std::string filename;
202 filename += FRAGMENTPREFIX + std::string("_VMGEnergy.dat");
203 writeToFile(filename, gridresult);
204 }
205
206 if (results.Result_LongRangeIntegrated_fused.size() >= (results.getMaxLevel()-2))
207 {
208 const std::string gridresult =
209 writeTable<VMGDataLongRangeMap_t, VMGDataLongRangeVector_t >()(
210 results.Result_LongRangeIntegrated_fused, results.getMaxLevel(), 2);
211 LOG(2, "DEBUG: LongRange table is \n" << gridresult);
212 std::string filename;
213 filename += FRAGMENTPREFIX + std::string("_LongRangeEnergy.dat");
214 writeToFile(filename, gridresult);
215 }
216}
217
218bool appendToHomologyFile(
219 const boost::filesystem::path &homology_file,
220 const FragmentationShortRangeResults &shortrangeresults,
221 const FragmentationLongRangeResults &longrangeresults
222 )
223{
224 /// read homology container (if present)
225 HomologyContainer homology_container;
226 if (boost::filesystem::exists(homology_file)) {
227 std::ifstream returnstream(homology_file.string().c_str());
228 if (returnstream.good()) {
229 boost::archive::text_iarchive ia(returnstream);
230 ia >> homology_container;
231 } else {
232 ELOG(2, "Failed to parse from " << homology_file.string() << ".");
233 }
234 returnstream.close();
235 } else {
236 LOG(2, "Could not open " << homology_file.string()
237 << ", creating empty container.");
238 }
239
240 /// append all fragments to a HomologyContainer
241 HomologyContainer::container_t values;
242
243 // convert KeySetContainer to IndexSetContainer
244 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
245 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
246 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
247 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
248 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
249 /// go through all fragments
250 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
251 {
252 /// create new graph entry in HomologyContainer which is (key,value) type
253 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
254 HomologyGraph graph(**forceiter);
255 LOG(2, "DEBUG: Created graph " << graph << ".");
256 const IndexSet::ptr &index = *iter;
257 HomologyContainer::value_t value;
258
259 // obtain fragment as key
260 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
261 = longrangeresults.Result_perIndexSet_Fragment.find(index);
262 ASSERT( fragmentiter != longrangeresults.Result_perIndexSet_Fragment.end(),
263 "appendToHomologyFile() - cannot find index "+toString(*index)
264 +" in FragmentResults.");
265 value.first = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
266
267 // obtain energy as value
268 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
269 = shortrangeresults.Result_perIndexSet_Energy.find(index);
270 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
271 "appendToHomologyFile() - cannot find index "+toString(*index)
272 +" in FragmentResults.");
273 // value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.first); // values
274 value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
275 values.insert( std::make_pair( graph, value) );
276 }
277 homology_container.insert(values);
278
279 if (DoLog(2)) {
280 LOG(2, "DEBUG: Listing all present atomic ids ...");
281 std::stringstream output;
282 for (World::AtomIterator iter = World::getInstance().getAtomIter();
283 iter != World::getInstance().atomEnd(); ++iter)
284 output << (*iter)->getId() << " ";
285 LOG(2, "DEBUG: { " << output.str() << "} .");
286 }
287
288 // for debugging: print container
289 if (DoLog(2)) {
290 LOG(2, "DEBUG: Listing all present homologies ...");
291 for (HomologyContainer::container_t::const_iterator iter =
292 homology_container.begin(); iter != homology_container.end(); ++iter) {
293 LOG(2, "DEBUG: graph " << iter->first << " has Fragment "
294 << iter->second.first << " and associated energy " << iter->second.second << ".");
295 }
296 }
297
298 /// store homology container again
299 std::ofstream outputstream(homology_file.string().c_str());
300 if (outputstream.good()) { // check if opened
301 boost::archive::text_oarchive oa(outputstream);
302 oa << homology_container;
303 if (outputstream.fail()) { // check if correctly written
304 LOG(1, "Failed to write to file " << homology_file.string() << ".");
305 return false;
306 } else
307 outputstream.close();
308 } else {
309 LOG(1, "Failed to open file " << homology_file.string()
310 << " for writing.");
311 return false;
312 }
313 return true;
314}
315
316Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
317
318 // if file is given, parse from file into resultscontainer
319 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
320 if (!params.resultsfile.get().empty()) {
321 boost::filesystem::path resultsfile = params.resultsfile.get();
322 if (boost::filesystem::exists(resultsfile)) {
323 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
324 std::ifstream returnstream(resultsfile.string().c_str());
325 if (returnstream.good()) {
326 boost::archive::text_iarchive ia(returnstream);
327 ia >> container;
328 }
329 } else {
330 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
331 }
332 }
333
334 // get data and keysets from ResultsContainer
335 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
336 const KeySetsContainer &keysets = container.getKeySets();
337 const KeySetsContainer &forcekeysets = container.getForceKeySets();
338 const bool DoLongrange = container.areFullRangeResultsPresent();
339
340 if (keysets.KeySets.empty()) {
341 ELOG(2, "There are no results in the container.");
342 return Action::failure;
343 }
344
345 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets);
346 shortrangeresults(shortrangedata);
347 printReceivedShortResults(shortrangeresults);
348
349#ifdef HAVE_VMG
350 if (DoLongrange) {
351 if ( World::getInstance().getAllAtoms().size() == 0) {
352 ELOG(1, "Please load the full molecule into the world before starting this action.");
353 return Action::failure;
354 }
355
356 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
357 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
358
359 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
360 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
361 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
362 for (size_t i=0;i<full_sample.size();++i)
363 --iter;
364 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
365 std::vector<VMGData> fullsolutionData;
366 for (; iter != longrangeData.end(); ++iter)
367 fullsolutionData.push_back(iter->second);
368 longrangeData.erase(remove_iter, longrangeData.end());
369
370 // Final phase: sum up and print result
371 FragmentationLongRangeResults longrangeresults(
372 shortrangedata,longrangeData,keysets, forcekeysets);
373 longrangeresults(
374 shortrangedata,
375 longrangeData,
376 fullsolutionData,
377 full_sample);
378 printReceivedFullResults(longrangeresults);
379
380 // append all keysets to homology file
381 if (!params.homology_file.get().empty()) {
382 const boost::filesystem::path &homology_file = params.homology_file.get();
383 if (homology_file.string() != "") {
384 LOG(1, "INFO: Appending HomologyGraphs to file " << homology_file.string() << ".");
385 if (!appendToHomologyFile(homology_file, shortrangeresults, longrangeresults))
386 return Action::failure;
387 }
388 }
389 }
390#else
391 if (DoLongrange)
392 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
393#endif
394
395 container.clear();
396
397 return Action::success;
398}
399
400Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performUndo(Action::state_ptr _state) {
401 return Action::success;
402}
403
404Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performRedo(Action::state_ptr _state){
405 return Action::success;
406}
407
408bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
409 return false;
410}
411
412bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
413 return false;
414}
415/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.