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

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

Forces obtained from fragmentation summation are now set.

  • Property mode set to 100644
File size: 17.0 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 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/mpl/remove.hpp>
45
46#include <vector>
47#include <fstream>
48#include <iostream>
49#include <string>
50#include <vector>
51
52#include "CodePatterns/Assert.hpp"
53#include "CodePatterns/Log.hpp"
54
55#ifdef HAVE_JOBMARKET
56#include "JobMarket/types.hpp"
57#else
58typedef size_t JobId_t;
59#endif
60
61#include "Descriptors/AtomIdDescriptor.hpp"
62#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
63#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
64#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
65#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
66#include "Fragmentation/Summation/Containers/MPQCData.hpp"
67#include "Fragmentation/Summation/Containers/MPQCData_printKeyNames.hpp"
68#include "Fragmentation/Homology/HomologyContainer.hpp"
69#include "Fragmentation/Homology/HomologyGraph.hpp"
70#include "Fragmentation/KeySetsContainer.hpp"
71#include "Fragmentation/Summation/SetValues/Eigenvalues.hpp"
72#include "Fragmentation/Summation/SetValues/Fragment.hpp"
73#include "Fragmentation/Summation/SetValues/Histogram.hpp"
74#include "Fragmentation/Summation/SetValues/IndexedVectors.hpp"
75#include "Fragmentation/Summation/IndexSetContainer.hpp"
76#include "Fragmentation/Summation/writeTable.hpp"
77#ifdef HAVE_VMG
78#include "Fragmentation/Summation/Containers/VMGData.hpp"
79#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
80#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
81#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
82#endif
83#include "Helpers/defs.hpp"
84#include "World.hpp"
85
86#include "Actions/FragmentationAction/AnalyseFragmentationResultsAction.hpp"
87
88using namespace MoleCuilder;
89
90// and construct the stuff
91#include "AnalyseFragmentationResultsAction.def"
92#include "Action_impl_pre.hpp"
93/** =========== define the function ====================== */
94
95void writeToFile(const std::string &filename, const std::string contents)
96{
97 std::ofstream tablefile(filename.c_str());
98 tablefile << contents;
99 tablefile.close();
100}
101
102/** Print (short range) energy, forces, and timings from received results.
103 *
104 * @param results summed up results container
105 */
106void printReceivedShortResults(
107 const FragmentationShortRangeResults &results)
108{
109 // print tables (without eigenvalues, they go extra)
110 {
111 typedef boost::mpl::remove<
112 boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type,
113 MPQCDataFused::energy_eigenhistogram>::type
114 MPQCDataEnergyVector_noeigenvalues_t;
115 const std::string energyresult =
116 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
117 results.Result_Energy_fused, results.getMaxLevel());
118 LOG(2, "DEBUG: Energy table is \n" << energyresult);
119 std::string filename;
120 filename += FRAGMENTPREFIX + std::string("_Energy.dat");
121 writeToFile(filename, energyresult);
122 }
123
124 {
125 typedef boost::mpl::list<
126 MPQCDataFused::energy_eigenvalues
127 > MPQCDataEigenvalues_t;
128 const std::string eigenvalueresult =
129 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
130 results.Result_Energy_fused, results.getMaxLevel());
131 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
132 std::string filename;
133 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
134 writeToFile(filename, eigenvalueresult);
135 }
136
137 {
138 typedef boost::mpl::list<
139 MPQCDataFused::energy_eigenhistogram
140 > MPQCDataEigenhistogram_t;
141 const std::string eigenhistogramresult =
142 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenhistogram_t >()(
143 results.Result_Energy_fused, results.getMaxLevel());
144 LOG(2, "DEBUG: Eigenhistogram table is \n" << eigenhistogramresult);
145 std::string filename;
146 filename += FRAGMENTPREFIX + std::string("_Eigenhistogram.dat");
147 writeToFile(filename, eigenhistogramresult);
148 }
149
150 {
151 typedef boost::mpl::list<
152 MPQCDataFused::energy_eigenvalues
153 > MPQCDataEigenvalues_t;
154 const std::string eigenvalueresult =
155 writeTable<MPQCDataEnergyMap_t, MPQCDataEigenvalues_t >()(
156 results.Result_Energy_fused, results.getMaxLevel());
157 LOG(2, "DEBUG: Eigenvalue table is \n" << eigenvalueresult);
158 std::string filename;
159 filename += FRAGMENTPREFIX + std::string("_Eigenvalues.dat");
160 writeToFile(filename, eigenvalueresult);
161 }
162
163 {
164 const std::string forceresult =
165 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
166 results.Result_Force_fused, results.getMaxLevel());
167 LOG(2, "DEBUG: Force table is \n" << forceresult);
168 std::string filename;
169 filename += FRAGMENTPREFIX + std::string("_Forces.dat");
170 writeToFile(filename, forceresult);
171 }
172 // we don't want to print grid to a table
173 {
174 // print times (without flops for now)
175 typedef boost::mpl::remove<
176 boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_total_flops>::type,
177 MPQCDataFused::times_gather_flops>::type
178 MPQCDataTimeVector_noflops_t;
179 const std::string timesresult =
180 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
181 results.Result_Time_fused, results.getMaxLevel());
182 LOG(2, "DEBUG: Times table is \n" << timesresult);
183 std::string filename;
184 filename += FRAGMENTPREFIX + std::string("_Times.dat");
185 writeToFile(filename, timesresult);
186 }
187}
188
189
190/** Print long range energy from received results.
191 *
192 * @param results summed up results container
193 */
194void printReceivedFullResults(
195 const FragmentationLongRangeResults &results)
196{
197 // print tables (without eigenvalues, they go extra)
198
199 if (results.Result_LongRange_fused.size() >= (results.getMaxLevel()-2))
200 {
201 const std::string gridresult =
202 writeTable<VMGDataMap_t, VMGDataVector_t >()(
203 results.Result_LongRange_fused, results.getMaxLevel(), 2);
204 LOG(2, "DEBUG: VMG table is \n" << gridresult);
205 std::string filename;
206 filename += FRAGMENTPREFIX + std::string("_VMGEnergy.dat");
207 writeToFile(filename, gridresult);
208 }
209
210 if (results.Result_LongRangeIntegrated_fused.size() >= (results.getMaxLevel()-2))
211 {
212 const std::string gridresult =
213 writeTable<VMGDataLongRangeMap_t, VMGDataLongRangeVector_t >()(
214 results.Result_LongRangeIntegrated_fused, results.getMaxLevel(), 2);
215 LOG(2, "DEBUG: LongRange table is \n" << gridresult);
216 std::string filename;
217 filename += FRAGMENTPREFIX + std::string("_LongRangeEnergy.dat");
218 writeToFile(filename, gridresult);
219 }
220}
221
222bool appendToHomologyFile(
223 const boost::filesystem::path &homology_file,
224 const FragmentationShortRangeResults &shortrangeresults,
225 const FragmentationLongRangeResults &longrangeresults
226 )
227{
228 /// read homology container (if present)
229 HomologyContainer homology_container;
230 if (boost::filesystem::exists(homology_file)) {
231 std::ifstream returnstream(homology_file.string().c_str());
232 if (returnstream.good()) {
233 boost::archive::text_iarchive ia(returnstream);
234 ia >> homology_container;
235 } else {
236 ELOG(2, "Failed to parse from " << homology_file.string() << ".");
237 }
238 returnstream.close();
239 } else {
240 LOG(2, "Could not open " << homology_file.string()
241 << ", creating empty container.");
242 }
243
244 /// append all fragments to a HomologyContainer
245 HomologyContainer::container_t values;
246
247 // convert KeySetContainer to IndexSetContainer
248 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
249 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
250 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
251 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
252 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
253
254 /// go through all fragments
255 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
256 {
257 /// create new graph entry in HomologyContainer which is (key,value) type
258 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
259 HomologyGraph graph(**forceiter);
260 LOG(2, "DEBUG: Created graph " << graph << ".");
261 const IndexSet::ptr &index = *iter;
262 HomologyContainer::value_t value;
263
264 // obtain fragment as key
265 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
266 = longrangeresults.Result_perIndexSet_Fragment.find(index);
267 ASSERT( fragmentiter != longrangeresults.Result_perIndexSet_Fragment.end(),
268 "appendToHomologyFile() - cannot find index "+toString(*index)
269 +" in FragmentResults.");
270 value.first = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
271
272 // obtain energy as value
273 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
274 = shortrangeresults.Result_perIndexSet_Energy.find(index);
275 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
276 "appendToHomologyFile() - cannot find index "+toString(*index)
277 +" in FragmentResults.");
278 // value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.first); // values
279 value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
280 values.insert( std::make_pair( graph, value) );
281 }
282 homology_container.insert(values);
283
284 if (DoLog(2)) {
285 LOG(2, "DEBUG: Listing all present atomic ids ...");
286 std::stringstream output;
287 for (World::AtomIterator iter = World::getInstance().getAtomIter();
288 iter != World::getInstance().atomEnd(); ++iter)
289 output << (*iter)->getId() << " ";
290 LOG(2, "DEBUG: { " << output.str() << "} .");
291 }
292
293 // for debugging: print container
294 if (DoLog(2)) {
295 LOG(2, "DEBUG: Listing all present homologies ...");
296 for (HomologyContainer::container_t::const_iterator iter =
297 homology_container.begin(); iter != homology_container.end(); ++iter) {
298 LOG(2, "DEBUG: graph " << iter->first << " has Fragment "
299 << iter->second.first << " and associated energy " << iter->second.second << ".");
300 }
301 }
302
303 /// store homology container again
304 std::ofstream outputstream(homology_file.string().c_str());
305 if (outputstream.good()) { // check if opened
306 boost::archive::text_oarchive oa(outputstream);
307 oa << homology_container;
308 if (outputstream.fail()) { // check if correctly written
309 LOG(1, "Failed to write to file " << homology_file.string() << ".");
310 return false;
311 } else
312 outputstream.close();
313 } else {
314 LOG(1, "Failed to open file " << homology_file.string()
315 << " for writing.");
316 return false;
317 }
318 return true;
319}
320
321Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
322
323 // if file is given, parse from file into resultscontainer
324 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
325 if (!params.resultsfile.get().empty()) {
326 boost::filesystem::path resultsfile = params.resultsfile.get();
327 if (boost::filesystem::exists(resultsfile)) {
328 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
329 std::ifstream returnstream(resultsfile.string().c_str());
330 if (returnstream.good()) {
331 boost::archive::text_iarchive ia(returnstream);
332 ia >> container;
333 }
334 } else {
335 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
336 }
337 }
338
339 // get data and keysets from ResultsContainer
340 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
341 const KeySetsContainer &keysets = container.getKeySets();
342 const KeySetsContainer &forcekeysets = container.getForceKeySets();
343 const bool DoLongrange = container.areFullRangeResultsPresent();
344 const bool IsAngstroem = true;
345
346 if (keysets.KeySets.empty()) {
347 ELOG(2, "There are no results in the container.");
348 return Action::failure;
349 }
350
351 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets);
352 shortrangeresults(shortrangedata);
353 printReceivedShortResults(shortrangeresults);
354
355 // adding obtained forces
356 if ( World::getInstance().getAllAtoms().size() != 0) {
357 const IndexedVectors::indexedvectors_t forces =
358 boost::fusion::at_key<MPQCDataFused::forces>(
359 shortrangeresults.Result_Force_fused.back()
360 ).getVectors();
361 ;
362 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
363 iter != forces.end(); ++iter) {
364 const IndexedVectors::index_t &index = iter->first;
365 const IndexedVectors::vector_t &forcevector = iter->second;
366 ASSERT( forcevector.size() == NDIM,
367 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
368 // note that mpqc calculates a gradient, hence force pointing into opposite direction
369 // we have to mind different units here: MPQC has a_o, while we may have angstroem
370 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
371 if (IsAngstroem)
372 for (size_t i=0;i<NDIM;++i)
373 ForceVector[i] *= AtomicLengthToAngstroem;
374 atom *_atom = World::getInstance().getAtom(AtomById(index));
375 if(_atom != NULL)
376 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
377 else
378 ELOG(2, "Could not find atom to id " << index << ".");
379 }
380 } else {
381 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
382 }
383
384#ifdef HAVE_VMG
385 if (DoLongrange) {
386 if ( World::getInstance().getAllAtoms().size() == 0) {
387 ELOG(1, "Please load the full molecule into the world before starting this action.");
388 return Action::failure;
389 }
390
391 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
392 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
393
394 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
395 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
396 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
397 for (size_t i=0;i<full_sample.size();++i)
398 --iter;
399 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
400 std::vector<VMGData> fullsolutionData;
401 for (; iter != longrangeData.end(); ++iter)
402 fullsolutionData.push_back(iter->second);
403 longrangeData.erase(remove_iter, longrangeData.end());
404
405 // Final phase: sum up and print result
406 FragmentationLongRangeResults longrangeresults(
407 shortrangedata,longrangeData,keysets, forcekeysets);
408 longrangeresults(
409 shortrangedata,
410 longrangeData,
411 fullsolutionData,
412 full_sample);
413 printReceivedFullResults(longrangeresults);
414
415 // append all keysets to homology file
416 if (!params.homology_file.get().empty()) {
417 const boost::filesystem::path &homology_file = params.homology_file.get();
418 if (homology_file.string() != "") {
419 LOG(1, "INFO: Appending HomologyGraphs to file " << homology_file.string() << ".");
420 if (!appendToHomologyFile(homology_file, shortrangeresults, longrangeresults))
421 return Action::failure;
422 }
423 }
424 }
425#else
426 if (DoLongrange)
427 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
428#endif
429
430 container.clear();
431
432 return Action::success;
433}
434
435Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performUndo(Action::state_ptr _state) {
436 return Action::success;
437}
438
439Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performRedo(Action::state_ptr _state){
440 return Action::success;
441}
442
443bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
444 return false;
445}
446
447bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
448 return false;
449}
450/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.