source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 343401

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 Candidate_v1.7.0 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 343401 was 343401, checked in by Frederik Heber <heber@…>, 13 years ago

longrangeData nows needs its own MatrixNrLookup, since job ids are different.

  • Property mode set to 100644
File size: 33.1 KB
RevLine 
[edecba]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
[94d5ac6]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/>.
[edecba]21 */
22
23/*
24 * FragmentationAutomationAction.cpp
25 *
26 * Created on: May 18, 2012
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include <boost/archive/text_iarchive.hpp>
36// boost asio needs specific operator new
37#include <boost/asio.hpp>
38
39#include "CodePatterns/MemDebug.hpp"
40
[fb881a]41#include <boost/mpl/remove.hpp>
[c9f9bb]42#include <boost/lambda/lambda.hpp>
[fb881a]43
[6ca578]44#include "CodePatterns/Assert.hpp"
[edecba]45#include "CodePatterns/Info.hpp"
46#include "CodePatterns/Log.hpp"
47#include "JobMarket/Controller/FragmentController.hpp"
48#include "JobMarket/Jobs/FragmentJob.hpp"
49
50#include "Atom/atom.hpp"
[d12d621]51#include "Box.hpp"
[06865e]52#include "Element/element.hpp"
[edecba]53#include "Fragmentation/EnergyMatrix.hpp"
54#include "Fragmentation/ForceMatrix.hpp"
55#include "Fragmentation/Fragmentation.hpp"
[184943]56#include "Fragmentation/SetValues/Fragment.hpp"
[e06820]57#include "Fragmentation/SetValues/Histogram.hpp"
[e13990b]58#include "Fragmentation/SetValues/IndexedVectors.hpp"
[edecba]59#include "Fragmentation/HydrogenSaturation_enum.hpp"
[6ca578]60#include "Fragmentation/KeySet.hpp"
[edecba]61#include "Fragmentation/KeySetsContainer.hpp"
[0398bd]62#include "Fragmentation/Summation/OrthogonalSumUpPerLevel.hpp"
63#include "Fragmentation/Summation/SumUpPerLevel.hpp"
[358ddb]64#include "Fragmentation/Summation/OrthogonalFullSummator.hpp"
65#include "Fragmentation/Summation/OrthogonalSummation.hpp"
[27afbf]66#include "Fragmentation/Summation/writeTable.hpp"
[edecba]67#include "Graph/DepthFirstSearchAnalysis.hpp"
[8b58ac]68#include "Helpers/defs.hpp"
[28e894]69#include "Jobs/MPQCJob.hpp"
[4bc75d]70#include "Jobs/MPQCData.hpp"
[1f66c7]71#include "Jobs/MPQCData_printKeyNames.hpp"
[849cd8]72#include "Jobs/Grid/SamplingGrid.hpp"
[d12d621]73#include "LinearAlgebra/RealSpaceMatrix.hpp"
[69c733]74#ifdef HAVE_VMG
75#include "Jobs/VMGJob.hpp"
[358ddb]76#include "Jobs/VMGData.hpp"
77#include "Jobs/VMGDataFused.hpp"
78#include "Jobs/VMGDataMap.hpp"
79#include "Jobs/VMGData_printKeyNames.hpp"
[69c733]80#endif
[edecba]81#include "molecule.hpp"
82#include "World.hpp"
83
84#include <iostream>
85#include <string>
86#include <vector>
87
[8cae4c]88#include <boost/mpl/for_each.hpp>
89
[edecba]90#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
91
92using namespace MoleCuilder;
93
94// and construct the stuff
95#include "FragmentationAutomationAction.def"
96#include "Action_impl_pre.hpp"
97/** =========== define the function ====================== */
98
99class controller_AddOn;
100
101// needs to be defined for using the FragmentController
102controller_AddOn *getAddOn()
103{
104 return NULL;
105}
106
[d12d621]107const int LEVEL = 5;
108
[edecba]109/** Creates a MPQCCommandJob with argument \a filename.
110 *
111 * @param jobs created job is added to this vector
112 * @param command mpqc command to execute
113 * @param filename filename being argument to job
114 * @param nextid id for this job
115 */
116void parsejob(
117 std::vector<FragmentJob::ptr> &jobs,
118 const std::string &command,
119 const std::string &filename,
120 const JobId_t nextid)
121{
122 std::ifstream file;
123 file.open(filename.c_str());
124 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
125 std::string output((std::istreambuf_iterator<char>(file)),
126 std::istreambuf_iterator<char>());
[d12d621]127 double begin[NDIM] = { 0., 0., 0. };
128 const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
129 const double size = M.at(0,0);
130 ASSERT( M.determinant() == size*size*size,
131 "parsejob() - current domain matrix "+toString(M)+" is not cubic.");
132 const int level = LEVEL;
133 FragmentJob::ptr testJob( new MPQCJob(nextid, output, begin, size, level) );
[edecba]134 jobs.push_back(testJob);
135 file.close();
136 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
137}
138
139/** Helper function to get number of atoms somehow.
140 *
141 * Here, we just parse the number of lines in the adjacency file as
142 * it should correspond to the number of atoms, except when some atoms
143 * are not bonded, but then fragmentation makes no sense.
144 *
145 * @param path path to the adjacency file
146 */
147size_t getNoAtomsFromAdjacencyFile(const std::string &path)
148{
149 size_t NoAtoms = 0;
150
151 // parse in special file to get atom count (from line count)
152 std::string filename(path);
153 filename += FRAGMENTPREFIX;
154 filename += ADJACENCYFILE;
155 std::ifstream adjacency(filename.c_str());
156 if (adjacency.fail()) {
157 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
158 return false;
159 }
160 std::string buffer;
161 while (getline(adjacency, buffer))
162 NoAtoms++;
163 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
164
165 return NoAtoms;
166}
167
[2764e0]168/** Extracts MPQCData from received vector of FragmentResults.
169 *
170 * @param results results to extract MPQCData from
171 * @param fragmentData on return array filled with extracted MPQCData
172 */
[a0f8d3]173template <typename T>
174void ConvertFragmentResultTo(
[2764e0]175 const std::vector<FragmentResult::ptr> &results,
[c9f9bb]176 std::map<JobId_t, T> &fragmentData)
[2764e0]177{
178 // extract results
179 fragmentData.clear();
180
181 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
182 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
183 iter != results.end(); ++iter) {
184 //LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
[a0f8d3]185 T extractedData;
[2764e0]186 std::stringstream inputstream((*iter)->result);
187 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
188 boost::archive::text_iarchive ia(inputstream);
189 ia >> extractedData;
190 LOG(1, "INFO: extracted data is " << extractedData << ".");
[c9f9bb]191 fragmentData.insert( std::make_pair( (*iter)->getId(), extractedData) );
[2764e0]192 }
193
194 ASSERT( results.size() == fragmentData.size(),
[a0f8d3]195 "ConvertFragmentResultTo() - the number of extracted data differs from the number of results.");
[2764e0]196}
[edecba]197
[c4ee08]198/** Creates a lookup from FragmentJob::id to the true fragment number.
[edecba]199 *
[995e2f]200 * @param jobids vector with job ids
[c4ee08]201 * @param FragmentCounter total number of fragments on return
[3dd32f]202 * @return Lookup up-map
[edecba]203 */
[3dd32f]204std::map< JobId_t, size_t > createMatrixNrLookup(
[995e2f]205 const std::vector<JobId_t> &jobids,
[c4ee08]206 size_t &FragmentCounter)
[edecba]207{
208 // align fragments
[3dd32f]209 std::map< JobId_t, size_t > MatrixNrLookup;
[c4ee08]210 FragmentCounter = 0;
[995e2f]211 for (std::vector<JobId_t>::const_iterator iter = jobids.begin();
212 iter != jobids.end(); ++iter) {
[343401]213 LOG(3, "DEBUG: Inserting (" << *iter << "," << FragmentCounter << ").");
[995e2f]214#ifndef NDEBUG
215 std::pair< std::map< JobId_t, size_t >::iterator, bool> inserter =
216#endif
217 MatrixNrLookup.insert( std::make_pair(*iter, FragmentCounter++) );
218 ASSERT( inserter.second,
219 "createMatrixNrLookup() - two results have same id "
220 +toString(*iter)+".");
[edecba]221 }
222 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
[3dd32f]223 return MatrixNrLookup;
[c4ee08]224}
[edecba]225
[c4ee08]226/** Place results from FragmentResult into EnergyMatrix and ForceMatrix.
227 *
228 * @param fragmentData MPQCData resulting from the jobs
229 * @param MatrixNrLookup Lookup up-map from job id to fragment number
230 * @param FragmentCounter total number of fragments
231 * @param NoAtoms total number of atoms
232 * @param Energy energy matrix to be filled on return
233 * @param Force force matrix to be filled on return
234 * @return true - everything ok, false - else
235 */
236bool putResultsintoMatrices(
[c9f9bb]237 const std::map<JobId_t, MPQCData> &fragmentData,
[3dd32f]238 const std::map< JobId_t, size_t > &MatrixNrLookup,
[c4ee08]239 const size_t FragmentCounter,
240 const size_t NoAtoms,
241 EnergyMatrix &Energy,
242 ForceMatrix &Force)
243{
[c9f9bb]244 for (std::map<JobId_t, MPQCData>::const_iterator dataiter = fragmentData.begin();
245 dataiter != fragmentData.end(); ++dataiter) {
246 const MPQCData &extractedData = dataiter->second;
247 const JobId_t &jobid = dataiter->first;
[3dd32f]248 std::map< JobId_t, size_t >::const_iterator nriter = MatrixNrLookup.find(jobid);
249 ASSERT( nriter != MatrixNrLookup.end(),
250 "putResultsintoMatrices() - MatrixNrLookup does not contain id "
251 +toString(jobid)+".");
[edecba]252 // place results into EnergyMatrix ...
253 {
254 MatrixContainer::MatrixArray matrix;
255 matrix.resize(1);
[a9558f]256 matrix[0].resize(1, extractedData.energies.total);
[edecba]257 if (!Energy.AddMatrix(
[c9f9bb]258 std::string("MPQCJob ")+toString(jobid),
[edecba]259 matrix,
[3dd32f]260 nriter->second)) {
[edecba]261 ELOG(1, "Adding energy matrix failed.");
262 return false;
263 }
264 }
265 // ... and ForceMatrix (with two empty columns in front)
266 {
267 MatrixContainer::MatrixArray matrix;
268 const size_t rows = extractedData.forces.size();
269 matrix.resize(rows);
270 for (size_t i=0;i<rows;++i) {
271 const size_t columns = 2+extractedData.forces[i].size();
272 matrix[i].resize(columns, 0.);
273 // for (size_t j=0;j<2;++j)
274 // matrix[i][j] = 0.;
275 for (size_t j=2;j<columns;++j)
276 matrix[i][j] = extractedData.forces[i][j-2];
277 }
278 if (!Force.AddMatrix(
[c9f9bb]279 std::string("MPQCJob ")+toString(jobid),
[edecba]280 matrix,
[3dd32f]281 nriter->second)) {
[edecba]282 ELOG(1, "Adding force matrix failed.");
283 return false;
284 }
285 }
286 }
287 // add one more matrix (not required for energy)
288 MatrixContainer::MatrixArray matrix;
289 matrix.resize(1);
290 matrix[0].resize(1, 0.);
291 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
292 return false;
293 // but for energy because we need to know total number of atoms
294 matrix.resize(NoAtoms);
295 for (size_t i = 0; i< NoAtoms; ++i)
296 matrix[i].resize(2+NDIM, 0.);
297 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
298 return false;
299
[c4ee08]300 return true;
301}
302/** Print MPQCData from received results.
303 *
[c9f9bb]304 * @param fragmentData MPQCData resulting from the jobs, each associated to a job
[c4ee08]305 * @param KeySetFilename filename with keysets to associate forces correctly
306 * @param NoAtoms total number of atoms
[184943]307 * @param full_sample summed up charge density of electrons from fragments on return
308 * @param full_fragment summed up positions and charges of nuclei from fragments on return
[849cd8]309 */
310bool sumUpChargeDensity(
[c9f9bb]311 const std::map<JobId_t,MPQCData> &fragmentData,
[849cd8]312 const std::string &KeySetFilename,
[184943]313 SamplingGrid &full_sample,
314 Fragment &full_fragment)
[849cd8]315{
[c9f9bb]316 // create a vector of all job ids
317 std::vector<JobId_t> jobids;
318 std::transform(fragmentData.begin(),fragmentData.end(),
319 std::back_inserter(jobids),
320 boost::bind( &std::map<JobId_t,MPQCData>::value_type::first, boost::lambda::_1 )
321 );
322
[849cd8]323 // create lookup from job nr to fragment number
324 size_t FragmentCounter = 0;
[3dd32f]325 const std::map< JobId_t, size_t > MatrixNrLookup =
326 createMatrixNrLookup(jobids, FragmentCounter);
[849cd8]327
328 // initialise keysets
329 KeySetsContainer KeySet;
330 {
331 // else needs keysets without hydrogens
332 std::stringstream filename;
333 filename << FRAGMENTPREFIX << KEYSETFILE;
334 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
335 }
336
337 /// prepare for OrthogonalSummation
338
339 // convert KeySetContainer to IndexSetContainer
340 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
341 // create the map of all keysets
342 SubsetMap::ptr subsetmap(new SubsetMap(*container));
343
344 /// convert all MPQCData to MPQCDataMap_t
345 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
[358ddb]346 OrthogonalSumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
[c9f9bb]347 fragmentData, MatrixNrLookup, container, subsetmap));
[184943]348 std::vector<MPQCDataFragmentMap_t> Result_Fragment_fused(
[358ddb]349 OrthogonalSumUpPerLevel<MPQCDataFragmentMap_t, MPQCDataFragmentVector_t>(
[c9f9bb]350 fragmentData, MatrixNrLookup, container, subsetmap));
[849cd8]351 // obtain full grid
352 full_sample = boost::fusion::at_key<MPQCDataFused::sampled_grid>(Result_Grid_fused.back());
[184943]353 full_fragment = boost::fusion::at_key<MPQCDataFused::fragment>(Result_Fragment_fused.back());
[849cd8]354
355 return true;
356}
357
358/** Print MPQCData from received results.
359 *
[c9f9bb]360 * @param fragmentData MPQCData resulting from the jobs, associated to job id
[849cd8]361 * @param KeySetFilename filename with keysets to associate forces correctly
362 * @param NoAtoms total number of atoms
363 * @param full_sample summed up charge from fragments on return
[c4ee08]364 */
365bool printReceivedMPQCResults(
[c9f9bb]366 const std::map<JobId_t, MPQCData> &fragmentData,
[c4ee08]367 const std::string &KeySetFilename,
[849cd8]368 size_t NoAtoms,
369 SamplingGrid &full_sample)
[c4ee08]370{
[c9f9bb]371 // create a vector of all job ids
372 std::vector<JobId_t> jobids;
373 std::transform(fragmentData.begin(),fragmentData.end(),
374 std::back_inserter(jobids),
375 boost::bind( &std::map<JobId_t,MPQCData>::value_type::first, boost::lambda::_1 )
376 );
377
[c4ee08]378 // create lookup from job nr to fragment number
379 size_t FragmentCounter = 0;
[3dd32f]380 const std::map< JobId_t, size_t > MatrixNrLookup=
381 createMatrixNrLookup(jobids, FragmentCounter);
[c4ee08]382
383 // place results into maps
384 EnergyMatrix Energy;
385 ForceMatrix Force;
[c9f9bb]386 if (!putResultsintoMatrices(fragmentData, MatrixNrLookup, FragmentCounter, NoAtoms, Energy, Force))
[c4ee08]387 return false;
388
389 // initialise keysets
[6ca578]390 KeySetsContainer KeySet;
[8b58ac]391 KeySetsContainer ForceKeySet;
[edecba]392 if (!Energy.InitialiseIndices()) return false;
393
394 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
395
[8b58ac]396 {
[c4ee08]397 // else needs keysets without hydrogens
[8b58ac]398 std::stringstream filename;
399 filename << FRAGMENTPREFIX << KEYSETFILE;
400 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
401 }
[edecba]402
[8b58ac]403 {
[c4ee08]404 // forces need keysets including hydrogens
[8b58ac]405 std::stringstream filename;
406 filename << FRAGMENTPREFIX << FORCESFILE;
407 if (!ForceKeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
408 }
[6ca578]409
[a67a04]410 /// prepare for OrthogonalSummation
[fb69e9]411
412 // convert KeySetContainer to IndexSetContainer
413 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
[6ca578]414 // create the map of all keysets
415 SubsetMap::ptr subsetmap(new SubsetMap(*container));
416
[e13990b]417 /// convert all MPQCData to MPQCDataMap_t
[8cae4c]418 {
[a67a04]419 ASSERT( ForceKeySet.KeySets.size() == fragmentData.size(),
420 "FragmentationAutomationAction::performCall() - ForceKeySet's KeySets and fragmentData differ in size.");
[6ca578]421
[358ddb]422 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type MPQCDataEnergyVector_noeigenvalues_t;
[94d530f]423 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(
[358ddb]424 OrthogonalSumUpPerLevel<MPQCDataEnergyMap_t, MPQCDataEnergyVector_t>(
[c9f9bb]425 fragmentData, MatrixNrLookup, container, subsetmap));
[94d530f]426 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
[358ddb]427 OrthogonalSumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
[c9f9bb]428 fragmentData, MatrixNrLookup, container, subsetmap));
[94d530f]429 std::vector<MPQCDataTimeMap_t> Result_Time_fused(
430 SumUpPerLevel<MPQCDataTimeMap_t, MPQCDataTimeVector_t>(
[c9f9bb]431 fragmentData, MatrixNrLookup, container, subsetmap));
[94d530f]432
433 // force has extra converter
[c9f9bb]434 std::map<JobId_t, MPQCDataForceMap_t> MPQCData_Force_fused;
[c4ee08]435 convertMPQCDatatoForceMap(fragmentData, ForceKeySet, MPQCData_Force_fused);
[ff9963]436 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
437 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
[a3a382]438 subsetmap,
439 MPQCData_Force_fused,
440 container->getContainer(),
[ff9963]441 MatrixNrLookup,
442 Result_Force_fused);
[a3a382]443 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
[20b3df]444
[849cd8]445 // obtain full grid
446 full_sample = boost::fusion::at_key<MPQCDataFused::sampled_grid>(Result_Grid_fused.back());
447
[fb881a]448 // print tables (without eigenvalues, they go extra)
[27afbf]449 const size_t MaxLevel = subsetmap->getMaximumSubsetLevel();
450 const std::string energyresult =
[fb881a]451 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
[27afbf]452 Result_Energy_fused, MaxLevel);
453 LOG(0, "Energy table is \n" << energyresult);
[fb881a]454 const std::string eigenvalueresult;
455
456 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
[27afbf]457 const std::string forceresult =
458 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
459 Result_Force_fused, MaxLevel);
460 LOG(0, "Force table is \n" << forceresult);
461 // we don't want to print grid to a table
[fb881a]462 // print times (without flops for now)
463 typedef boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_flops>::type MPQCDataTimeVector_noflops_t;
[27afbf]464 const std::string timesresult =
[fb881a]465 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
[27afbf]466 Result_Time_fused, MaxLevel);
467 LOG(0, "Times table is \n" << timesresult);
[8cae4c]468 }
[56df37]469
[6ca578]470 // combine all found data
[edecba]471 if (!KeySet.ParseManyBodyTerms()) return false;
472
[c4ee08]473 EnergyMatrix EnergyFragments;
474 ForceMatrix ForceFragments;
[edecba]475 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
476 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
477
478 if(!Energy.SetLastMatrix(0., 0)) return false;
479 if(!Force.SetLastMatrix(0., 2)) return false;
480
481 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
482 // --------- sum up energy --------------------
483 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
484 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
485 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
486
487 // --------- sum up Forces --------------------
488 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
489 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
490 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
491 }
492
493 // for debugging print resulting energy and forces
494 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
495 std::stringstream output;
496 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
497 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
498 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
499 output << "\n";
500 }
501 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
502
503 return true;
504}
505
[343401]506template <typename T>
507std::vector<JobId_t> extractJobIds(const std::map<JobId_t, T> &iddata)
508{
509 // create a vector of all job ids
510 std::vector<JobId_t> jobids;
511 std::transform(iddata.begin(),iddata.end(),
512 std::back_inserter(jobids),
513 boost::bind(&std::map<JobId_t,T>::value_type::first, boost::lambda::_1 )
514 );
515 return jobids;
516}
517
[358ddb]518/** Print MPQCData from received results.
519 *
520 * @param fragmentData MPQCData resulting from the jobs
521 * @param longrangeData VMGData resulting from long-range jobs
[1f76f3]522 * @param fullsolutionData VMGData resulting from long-range of full problem
[358ddb]523 * @param KeySetFilename filename with keysets to associate forces correctly
524 * @param NoAtoms total number of atoms
525 * @param full_sample summed up charge from fragments on return
526 */
527bool printReceivedFullResults(
[c9f9bb]528 const std::map<JobId_t,MPQCData> &fragmentData,
529 const std::map<JobId_t,VMGData> &longrangeData,
[1f76f3]530 const VMGData &fullsolutionData,
[358ddb]531 const std::string &KeySetFilename,
532 size_t NoAtoms,
533 SamplingGrid &full_sample)
534{
535 // create lookup from job nr to fragment number
[343401]536 size_t MPQCFragmentCounter = 0;
537 const std::vector<JobId_t> mpqcjobids = extractJobIds<MPQCData>(fragmentData);
538 const std::map< JobId_t, size_t > MPQCMatrixNrLookup =
539 createMatrixNrLookup(mpqcjobids, MPQCFragmentCounter);
540
541 size_t VMGFragmentCounter = 0;
542 const std::vector<JobId_t> vmgjobids = extractJobIds<VMGData>(longrangeData);
543 const std::map< JobId_t, size_t > VMGMatrixNrLookup =
544 createMatrixNrLookup(vmgjobids, VMGFragmentCounter);
[358ddb]545
546 // initialise keysets
547 KeySetsContainer KeySet;
548 KeySetsContainer ForceKeySet;
549 {
550 // else needs keysets without hydrogens
551 std::stringstream filename;
552 filename << FRAGMENTPREFIX << KEYSETFILE;
[343401]553 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), MPQCFragmentCounter)) return false;
[358ddb]554 }
555
556 {
557 // forces need keysets including hydrogens
558 std::stringstream filename;
559 filename << FRAGMENTPREFIX << FORCESFILE;
[343401]560 if (!ForceKeySet.ParseKeySets(KeySetFilename, filename.str(), MPQCFragmentCounter)) return false;
[358ddb]561 }
562
563 /// prepare for OrthogonalSummation
564
565 // convert KeySetContainer to IndexSetContainer
566 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
567 // create the map of all keysets
568 SubsetMap::ptr subsetmap(new SubsetMap(*container));
569
570 /// convert all MPQCData to MPQCDataMap_t
571 {
572 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type MPQCDataEnergyVector_noeigenvalues_t;
573 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(
574 OrthogonalSumUpPerLevel<MPQCDataEnergyMap_t, MPQCDataEnergyVector_t>(
[343401]575 fragmentData, MPQCMatrixNrLookup, container, subsetmap));
[358ddb]576 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
577 OrthogonalSumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
[343401]578 fragmentData, MPQCMatrixNrLookup, container, subsetmap));
[358ddb]579 std::vector<MPQCDataTimeMap_t> Result_Time_fused(
580 SumUpPerLevel<MPQCDataTimeMap_t, MPQCDataTimeVector_t>(
[343401]581 fragmentData, MPQCMatrixNrLookup, container, subsetmap));
[06865e]582 std::vector<MPQCDataFragmentMap_t> Result_Fragment_fused(
583 OrthogonalSumUpPerLevel<MPQCDataFragmentMap_t, MPQCDataFragmentVector_t>(
[343401]584 fragmentData, MPQCMatrixNrLookup, container, subsetmap));
[358ddb]585
586 // force has extra converter
[c9f9bb]587 std::map<JobId_t, MPQCDataForceMap_t> MPQCData_Force_fused;
[358ddb]588 convertMPQCDatatoForceMap(fragmentData, ForceKeySet, MPQCData_Force_fused);
589 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
590 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
591 subsetmap,
592 MPQCData_Force_fused,
593 container->getContainer(),
[343401]594 MPQCMatrixNrLookup,
[358ddb]595 Result_Force_fused);
596 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
597
598 // obtain full grid
[c9f9bb]599 std::map<JobId_t, VMGDataMap_t> VMGData_Potential_fused;
[1f76f3]600 convertDataTo<VMGData, VMGDataMap_t>(longrangeData, VMGData_Potential_fused);
[358ddb]601 OrthogonalFullSummator<VMGDataMap_t, VMGDataFused::sampled_potential> potentialSummer(
602 subsetmap,
603 VMGData_Potential_fused,
604 container->getContainer(),
[343401]605 VMGMatrixNrLookup);
[358ddb]606 potentialSummer(subsetmap->getMaximumSubsetLevel());
[c5feef]607 OrthogonalFullSummator<VMGDataMap_t, VMGDataFused::energy_potential> epotentialSummer(
608 subsetmap,
609 VMGData_Potential_fused,
610 container->getContainer(),
[343401]611 VMGMatrixNrLookup);
[c5feef]612 epotentialSummer(subsetmap->getMaximumSubsetLevel());
[1f76f3]613 SamplingGrid full_sample = fullsolutionData.sampled_potential;
[c5feef]614 LOG(0, "Remaining long-range energy from energy_potential is " << full_sample.integral()-epotentialSummer.getFullContribution() << ".");
[06865e]615 full_sample -= potentialSummer.getFullContribution();
[358ddb]616 LOG(0, "Remaining long-range energy from potential integral is " << full_sample.integral() << ".");
617
[c5feef]618
[358ddb]619 OrthogonalFullSummator<VMGDataMap_t, VMGDataFused::energy_long> elongSummer(
620 subsetmap,
621 VMGData_Potential_fused,
622 container->getContainer(),
[343401]623 VMGMatrixNrLookup);
[358ddb]624 elongSummer(subsetmap->getMaximumSubsetLevel());
[1f76f3]625 double e_long = fullsolutionData.e_long;
[06865e]626 e_long -= elongSummer.getFullContribution();
[358ddb]627 LOG(0, "Remaining long-range energy is " << e_long << ".");
628
629 // print tables (without eigenvalues, they go extra)
630 const size_t MaxLevel = subsetmap->getMaximumSubsetLevel();
631 const std::string energyresult =
632 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
633 Result_Energy_fused, MaxLevel);
634 LOG(0, "Energy table is \n" << energyresult);
635 const std::string eigenvalueresult;
636
637 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
638 const std::string forceresult =
639 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
640 Result_Force_fused, MaxLevel);
641 LOG(0, "Force table is \n" << forceresult);
642 // we don't want to print grid to a table
643 // print times (without flops for now)
644 typedef boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_flops>::type MPQCDataTimeVector_noflops_t;
645 const std::string timesresult =
646 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
647 Result_Time_fused, MaxLevel);
648 LOG(0, "Times table is \n" << timesresult);
649 }
650
651 return true;
652}
653
[edecba]654
[c5324f]655void RunService(
656 boost::asio::io_service &io_service,
657 std::string message)
658{
659 message = std::string("io_service: ") + message;
660 io_service.reset();
661 Info info(message.c_str());
662 io_service.run();
663}
[edecba]664
[c5324f]665void requestIds(
666 FragmentController &controller,
667 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
668 const size_t numberjobs)
669{
670 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
671}
672
673bool createJobsFromFiles(
674 FragmentController &controller,
675 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
676 const std::vector< boost::filesystem::path > &jobfiles)
677{
678 std::vector<FragmentJob::ptr> jobs;
679 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
680 iter != jobfiles .end(); ++iter) {
681 const std::string &filename = (*iter).string();
682 if (boost::filesystem::exists(filename)) {
683 const JobId_t next_id = controller.getAvailableId();
684 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
685 +filename+"', and id "+toString(next_id)+".");
686 parsejob(jobs, params.executable.get().string(), filename, next_id);
687 } else {
688 ELOG(1, "Fragment job "+filename+" does not exist.");
689 return false;
[edecba]690 }
691 }
[c5324f]692 controller.addJobs(jobs);
693 controller.sendJobs(params.host.get(), params.port.get());
694 return true;
695}
696
[69c733]697#ifdef HAVE_VMG
698bool createLongRangeJobs(
699 FragmentController &controller,
700 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
[c9f9bb]701 const std::map<JobId_t, MPQCData> &fragmentData,
[184943]702 const SamplingGrid &full_sampled_grid,
703 const Fragment &full_fragment)
[69c733]704{
705 std::vector<FragmentJob::ptr> jobs;
[d12d621]706 // add one job for each fragment as the short-range correction which we need
707 // to subtract from the obtained full potential to get the long-range part only
[c9f9bb]708 for (std::map<JobId_t, MPQCData>::const_iterator iter = fragmentData.begin();
[d12d621]709 iter != fragmentData.end(); ++iter) {
[69c733]710 const JobId_t next_id = controller.getAvailableId();
[c9f9bb]711 LOG(1, "INFO: Creating VMGJob with " << iter->second.sampled_grid.sampled_grid.size()
712 << " gridpoints and " << iter->second.charges.size() << " particle charges.");
[d12d621]713 FragmentJob::ptr testJob(
[c9f9bb]714 new VMGJob(next_id, iter->second.sampled_grid, iter->second.positions, iter->second.charges) );
[69c733]715 jobs.push_back(testJob);
716 }
[d12d621]717
718 {
[06865e]719 const World::AtomComposite &atoms = World::getInstance().getAllAtoms();
720 std::vector< std::vector<double> > positions;
721 positions.reserve(atoms.size());
722 std::vector<double> charges;
723 charges.reserve(atoms.size());
724 std::vector<double> position(3, 0.);
725 for (World::AtomComposite::const_iterator iter = atoms.begin();
726 iter != atoms.end(); ++iter) {
727 const Vector &pos = (*iter)->getPosition();
728 for (size_t i=0;i<3;++i) position[i] = pos[i];
729 positions.push_back(position);
730 charges.push_back((double)((*iter)->getElement().getAtomicNumber()));
731 }
[d12d621]732 const JobId_t next_id = controller.getAvailableId();
[849cd8]733 LOG(1, "INFO: Creating full VMGJob with " << full_sampled_grid.sampled_grid.size()
[4adef7]734 << " gridpoints and " << charges.size() << " particle charges.");
[d12d621]735 FragmentJob::ptr testJob(
[cd77fc]736 new VMGJob(next_id, full_sampled_grid, positions, charges) );
[d12d621]737 jobs.push_back(testJob);
738 }
739
740 // then send jobs to controller
[69c733]741 controller.addJobs(jobs);
742 controller.sendJobs(params.host.get(), params.port.get());
743 return true;
744}
745#endif
746
[c5324f]747void WaitforResults(
748 boost::asio::io_service &io_service,
749 FragmentController &controller,
750 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
751 const size_t NoExpectedResults
752 )
753{
[edecba]754 size_t NoCalculatedResults = 0;
[c5324f]755 while (NoCalculatedResults != NoExpectedResults) {
[edecba]756 // wait a bit
757 boost::asio::deadline_timer timer(io_service);
758 timer.expires_from_now(boost::posix_time::milliseconds(500));
759 timer.wait();
760 // then request status
[bd81f9]761 controller.checkResults(params.host.get(), params.port.get());
[c5324f]762 RunService(io_service, "Checking on results");
763
[edecba]764 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
765 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
766 NoCalculatedResults = JobStatus.second;
767 }
[c5324f]768}
769
770
771Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
772 boost::asio::io_service io_service;
773 FragmentController controller(io_service);
774
775 // TODO: Have io_service run in second thread and merge with current again eventually
776
777 // Phase One: obtain ids
778 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
779 requestIds(controller, params, jobfiles.size());
780 RunService(io_service, "Requesting ids");
781
[69c733]782 // Phase Two: create and add MPQCJobs
[c5324f]783 if (!createJobsFromFiles(controller, params, jobfiles))
784 return Action::failure;
[69c733]785 RunService(io_service, "Adding MPQCJobs");
[c5324f]786
787 // Phase Three: calculate result
788 WaitforResults(io_service, controller, params, jobfiles.size());
[bd81f9]789 controller.receiveResults(params.host.get(), params.port.get());
[69c733]790 RunService(io_service, "Requesting short-range results");
[2764e0]791 std::vector<FragmentResult::ptr> MPQCresults = controller.getReceivedResults();
[c9f9bb]792 std::map<JobId_t, MPQCData> fragmentData;
[a0f8d3]793 ConvertFragmentResultTo<MPQCData>(MPQCresults, fragmentData);
[c5324f]794
[69c733]795#ifdef HAVE_VMG
796 if (params.DoLongrange.get()) {
[06865e]797 ASSERT( World::getInstance().getAllAtoms().size() != 0,
798 "FragmentationFragmentationAutomationAction::performCall() - please load the full molecule into the World before.");
799
[995e2f]800 // create a vector of all job ids
801 std::vector<JobId_t> jobids(MPQCresults.size(), JobId::IllegalJob);
802 std::transform(MPQCresults.begin(), MPQCresults.end(), jobids.begin(),
803 boost::bind(&FragmentResult::getId,
804 boost::bind(&FragmentResult::ptr::operator->, _1)));
805
[849cd8]806 // obtain combined charge density
807 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
808 SamplingGrid full_sample;
[184943]809 Fragment full_fragment;
[849cd8]810 sumUpChargeDensity(
811 fragmentData,
812 params.path.get(),
[184943]813 full_sample,
814 full_fragment);
[849cd8]815
[69c733]816 // Phase Four: obtain more ids
[2764e0]817 requestIds(controller, params, fragmentData.size()+1);
[69c733]818 RunService(io_service, "Requesting ids");
819
820 // Phase Five: create VMGJobs
[184943]821 if (!createLongRangeJobs(controller, params, fragmentData, full_sample, full_fragment))
[69c733]822 return Action::failure;
823 RunService(io_service, "Adding VMGJobs");
824
825 // Phase Six: calculate result
[2764e0]826 WaitforResults(io_service, controller, params, fragmentData.size()+1);
[69c733]827 controller.receiveResults(params.host.get(), params.port.get());
828 RunService(io_service, "Requesting long-range results");
829 std::vector<FragmentResult::ptr> VMGresults = controller.getReceivedResults();
[2764e0]830 ASSERT( MPQCresults.size()+1 == VMGresults.size(),
831 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresultd and VMGresults don't match.");
832
[c9f9bb]833 std::map<JobId_t, VMGData> longrangeData;
[358ddb]834 ConvertFragmentResultTo<VMGData>(VMGresults, longrangeData);
[c9f9bb]835 // remove full solution from map (must be highest id), has to be treated extra
836 VMGData fullsolutionData = (--longrangeData.end())->second;
837 longrangeData.erase(--longrangeData.end());
[358ddb]838
[2764e0]839 // Final phase: print result
840 {
841 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
[358ddb]842 printReceivedFullResults(
[2764e0]843 fragmentData,
[358ddb]844 longrangeData,
[1f76f3]845 fullsolutionData,
[2764e0]846 params.path.get(),
[849cd8]847 getNoAtomsFromAdjacencyFile(params.path.get()),
848 full_sample);
[2764e0]849 }
[69c733]850 }
[358ddb]851#else
852 // Final phase: print result
853 {
854 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
855 printReceivedMPQCResults(
856 fragmentData,
857 params.path.get(),
858 getNoAtomsFromAdjacencyFile(params.path.get()),
859 full_sample);
860 }
[69c733]861#endif
[edecba]862 size_t Exitflag = controller.getExitflag();
863
864 return (Exitflag == 0) ? Action::success : Action::failure;
865}
866
867Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
868 return Action::success;
869}
870
871Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
872 return Action::success;
873}
874
875bool FragmentationFragmentationAutomationAction::canUndo() {
876 return false;
877}
878
879bool FragmentationFragmentationAutomationAction::shouldUndo() {
880 return false;
881}
882/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.