source: src/Actions/FragmentationAction/AnalyseFragmentationResultsAction.cpp@ 1e1098

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

World now maintains HomologyContainer instance.

  • Property mode set to 100644
File size: 17.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 * 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
222void parseHomologiesFromFile(
223 const boost::filesystem::path &homology_file
224 )
225{
226 HomologyContainer &homology_container = World::getInstance().getHomologies();
227 if (boost::filesystem::exists(homology_file)) {
228 std::ifstream returnstream(homology_file.string().c_str());
229 if (returnstream.good()) {
230 boost::archive::text_iarchive ia(returnstream);
231 ia >> homology_container;
232 } else {
233 ELOG(2, "Failed to parse from " << homology_file.string() << ".");
234 }
235 returnstream.close();
236 } else {
237 LOG(2, "Could not open " << homology_file.string()
238 << ", creating empty container.");
239 }
240}
241
242void appendToHomologies(
243 const FragmentationShortRangeResults &shortrangeresults,
244 const FragmentationLongRangeResults &longrangeresults
245 )
246{
247 /// read homology container (if present)
248 HomologyContainer &homology_container = World::getInstance().getHomologies();
249
250 /// append all fragments to a HomologyContainer
251 HomologyContainer::container_t values;
252
253 // convert KeySetContainer to IndexSetContainer
254 IndexSetContainer::ptr ForceContainer(new IndexSetContainer(shortrangeresults.getForceKeySet()));
255 const IndexSetContainer::Container_t &Indices = shortrangeresults.getContainer();
256 const IndexSetContainer::Container_t &ForceIndices = ForceContainer->getContainer();
257 IndexSetContainer::Container_t::const_iterator iter = Indices.begin();
258 IndexSetContainer::Container_t::const_iterator forceiter = ForceIndices.begin();
259
260 /// go through all fragments
261 for (;iter != Indices.end(); ++iter, ++forceiter) // go through each IndexSet
262 {
263 /// create new graph entry in HomologyContainer which is (key,value) type
264 LOG(1, "INFO: Creating new graph with " << **forceiter << ".");
265 HomologyGraph graph(**forceiter);
266 LOG(2, "DEBUG: Created graph " << graph << ".");
267 const IndexSet::ptr &index = *iter;
268 HomologyContainer::value_t value;
269
270 // obtain fragment as key
271 std::map<IndexSet::ptr, std::pair< MPQCDataFragmentMap_t, MPQCDataFragmentMap_t> >::const_iterator fragmentiter
272 = longrangeresults.Result_perIndexSet_Fragment.find(index);
273 ASSERT( fragmentiter != longrangeresults.Result_perIndexSet_Fragment.end(),
274 "appendToHomologyFile() - cannot find index "+toString(*index)
275 +" in FragmentResults.");
276 value.first = boost::fusion::at_key<MPQCDataFused::fragment>(fragmentiter->second.first);
277
278 // obtain energy as value
279 std::map<IndexSet::ptr, std::pair< MPQCDataEnergyMap_t, MPQCDataEnergyMap_t> >::const_iterator energyiter
280 = shortrangeresults.Result_perIndexSet_Energy.find(index);
281 ASSERT( energyiter != shortrangeresults.Result_perIndexSet_Energy.end(),
282 "appendToHomologyFile() - cannot find index "+toString(*index)
283 +" in FragmentResults.");
284 // value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.first); // values
285 value.second = boost::fusion::at_key<MPQCDataFused::energy_total>(energyiter->second.second); // contributions
286 values.insert( std::make_pair( graph, value) );
287 }
288 homology_container.insert(values);
289
290 if (DoLog(2)) {
291 LOG(2, "DEBUG: Listing all present atomic ids ...");
292 std::stringstream output;
293 for (World::AtomIterator iter = World::getInstance().getAtomIter();
294 iter != World::getInstance().atomEnd(); ++iter)
295 output << (*iter)->getId() << " ";
296 LOG(2, "DEBUG: { " << output.str() << "} .");
297 }
298
299 // for debugging: print container
300 if (DoLog(2)) {
301 LOG(2, "DEBUG: Listing all present homologies ...");
302 for (HomologyContainer::container_t::const_iterator iter =
303 homology_container.begin(); iter != homology_container.end(); ++iter) {
304 LOG(2, "DEBUG: graph " << iter->first << " has Fragment "
305 << iter->second.first << " and associated energy " << iter->second.second << ".");
306 }
307 }
308}
309
310bool writeHomologiesToFile(
311 const boost::filesystem::path &homology_file
312 )
313{
314 /// store homology container again
315 HomologyContainer &homology_container = World::getInstance().getHomologies();
316 std::ofstream outputstream(homology_file.string().c_str());
317 if (outputstream.good()) { // check if opened
318 boost::archive::text_oarchive oa(outputstream);
319 oa << homology_container;
320 if (outputstream.fail()) { // check if correctly written
321 LOG(1, "Failed to write to file " << homology_file.string() << ".");
322 return false;
323 } else
324 outputstream.close();
325 } else {
326 LOG(1, "Failed to open file " << homology_file.string()
327 << " for writing.");
328 return false;
329 }
330 return true;
331}
332
333Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performCall() {
334
335 // if file is given, parse from file into resultscontainer
336 FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
337 if (!params.resultsfile.get().empty()) {
338 boost::filesystem::path resultsfile = params.resultsfile.get();
339 if (boost::filesystem::exists(resultsfile)) {
340 LOG(1, "INFO: Parsing results from " << resultsfile.string() << ".");
341 std::ifstream returnstream(resultsfile.string().c_str());
342 if (returnstream.good()) {
343 boost::archive::text_iarchive ia(returnstream);
344 ia >> container;
345 }
346 } else {
347 ELOG(1, "Given file" << resultsfile.string() << " does not exist.");
348 }
349 }
350
351 // get data and keysets from ResultsContainer
352 const std::map<JobId_t, MPQCData> &shortrangedata = container.getShortRangeResults();
353 const KeySetsContainer &keysets = container.getKeySets();
354 const KeySetsContainer &forcekeysets = container.getForceKeySets();
355 const bool DoLongrange = container.areFullRangeResultsPresent();
356 const bool IsAngstroem = true;
357
358 if (keysets.KeySets.empty()) {
359 ELOG(2, "There are no results in the container.");
360 return Action::failure;
361 }
362
363 FragmentationShortRangeResults shortrangeresults(shortrangedata, keysets, forcekeysets);
364 shortrangeresults(shortrangedata);
365 printReceivedShortResults(shortrangeresults);
366
367 // adding obtained forces
368 if ( World::getInstance().getAllAtoms().size() != 0) {
369 const IndexedVectors::indexedvectors_t forces =
370 boost::fusion::at_key<MPQCDataFused::forces>(
371 shortrangeresults.Result_Force_fused.back()
372 ).getVectors();
373 ;
374 for(IndexedVectors::indexedvectors_t::const_iterator iter = forces.begin();
375 iter != forces.end(); ++iter) {
376 const IndexedVectors::index_t &index = iter->first;
377 const IndexedVectors::vector_t &forcevector = iter->second;
378 ASSERT( forcevector.size() == NDIM,
379 "printReceivedShortResults() - obtained force vector has incorrect dimension.");
380 // note that mpqc calculates a gradient, hence force pointing into opposite direction
381 // we have to mind different units here: MPQC has a_o, while we may have angstroem
382 Vector ForceVector(-forcevector[0], -forcevector[1], -forcevector[2]);
383 if (IsAngstroem)
384 for (size_t i=0;i<NDIM;++i)
385 ForceVector[i] *= AtomicLengthToAngstroem;
386 atom *_atom = World::getInstance().getAtom(AtomById(index));
387 if(_atom != NULL)
388 _atom->setAtomicForce(_atom->getAtomicForce() + ForceVector);
389 else
390 ELOG(2, "Could not find atom to id " << index << ".");
391 }
392 } else {
393 LOG(1, "INFO: Full molecule not loaded, hence will not add forces to atoms.");
394 }
395
396#ifdef HAVE_VMG
397 if (DoLongrange) {
398 if ( World::getInstance().getAllAtoms().size() == 0) {
399 ELOG(1, "Please load the full molecule into the world before starting this action.");
400 return Action::failure;
401 }
402
403 FragmentationChargeDensity summedChargeDensity(shortrangedata,keysets);
404 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
405
406 std::map<JobId_t, VMGData> longrangeData = container.getLongRangeResults();
407 // remove full solution corresponding to full_sample from map (must be highest ids), has to be treated extra
408 std::map<JobId_t, VMGData>::iterator iter = longrangeData.end();
409 for (size_t i=0;i<full_sample.size();++i)
410 --iter;
411 std::map<JobId_t, VMGData>::iterator remove_iter = iter;
412 std::vector<VMGData> fullsolutionData;
413 for (; iter != longrangeData.end(); ++iter)
414 fullsolutionData.push_back(iter->second);
415 longrangeData.erase(remove_iter, longrangeData.end());
416
417 // Final phase: sum up and print result
418 FragmentationLongRangeResults longrangeresults(
419 shortrangedata,longrangeData,keysets, forcekeysets);
420 longrangeresults(
421 shortrangedata,
422 longrangeData,
423 fullsolutionData,
424 full_sample);
425 printReceivedFullResults(longrangeresults);
426
427 // append all keysets to homology file
428 appendToHomologies(shortrangeresults, longrangeresults);
429 if (!params.homology_file.get().empty()) {
430 const boost::filesystem::path &homology_file = params.homology_file.get();
431 if (homology_file.string() != "") {
432 LOG(1, "INFO: Parsing HomologyGraphs from file " << homology_file.string() << ".");
433 parseHomologiesFromFile(homology_file);
434 LOG(1, "INFO: Appending HomologyGraphs to file " << homology_file.string() << ".");
435 if (!writeHomologiesToFile(homology_file))
436 return Action::failure;
437 }
438 }
439 }
440#else
441 if (DoLongrange)
442 ELOG(2, "File contains long-range information but long-range analysis capability not compiled in.");
443#endif
444
445 container.clear();
446
447 return Action::success;
448}
449
450Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performUndo(Action::state_ptr _state) {
451 return Action::success;
452}
453
454Action::state_ptr FragmentationAnalyseFragmentationResultsAction::performRedo(Action::state_ptr _state){
455 return Action::success;
456}
457
458bool FragmentationAnalyseFragmentationResultsAction::canUndo() {
459 return false;
460}
461
462bool FragmentationAnalyseFragmentationResultsAction::shouldUndo() {
463 return false;
464}
465/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.