source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 3dd32f

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

MatrixNrLookup ist now used const throughout templated functors.

  • createMatrixNrLookup() returns it to allow for creating const variable directly.
  • Property mode set to 100644
File size: 32.6 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) {
213#ifndef NDEBUG
214 std::pair< std::map< JobId_t, size_t >::iterator, bool> inserter =
215#endif
216 MatrixNrLookup.insert( std::make_pair(*iter, FragmentCounter++) );
217 ASSERT( inserter.second,
218 "createMatrixNrLookup() - two results have same id "
219 +toString(*iter)+".");
[edecba]220 }
221 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
[3dd32f]222 return MatrixNrLookup;
[c4ee08]223}
[edecba]224
[c4ee08]225/** Place results from FragmentResult into EnergyMatrix and ForceMatrix.
226 *
227 * @param fragmentData MPQCData resulting from the jobs
228 * @param MatrixNrLookup Lookup up-map from job id to fragment number
229 * @param FragmentCounter total number of fragments
230 * @param NoAtoms total number of atoms
231 * @param Energy energy matrix to be filled on return
232 * @param Force force matrix to be filled on return
233 * @return true - everything ok, false - else
234 */
235bool putResultsintoMatrices(
[c9f9bb]236 const std::map<JobId_t, MPQCData> &fragmentData,
[3dd32f]237 const std::map< JobId_t, size_t > &MatrixNrLookup,
[c4ee08]238 const size_t FragmentCounter,
239 const size_t NoAtoms,
240 EnergyMatrix &Energy,
241 ForceMatrix &Force)
242{
[c9f9bb]243 for (std::map<JobId_t, MPQCData>::const_iterator dataiter = fragmentData.begin();
244 dataiter != fragmentData.end(); ++dataiter) {
245 const MPQCData &extractedData = dataiter->second;
246 const JobId_t &jobid = dataiter->first;
[3dd32f]247 std::map< JobId_t, size_t >::const_iterator nriter = MatrixNrLookup.find(jobid);
248 ASSERT( nriter != MatrixNrLookup.end(),
249 "putResultsintoMatrices() - MatrixNrLookup does not contain id "
250 +toString(jobid)+".");
[edecba]251 // place results into EnergyMatrix ...
252 {
253 MatrixContainer::MatrixArray matrix;
254 matrix.resize(1);
[a9558f]255 matrix[0].resize(1, extractedData.energies.total);
[edecba]256 if (!Energy.AddMatrix(
[c9f9bb]257 std::string("MPQCJob ")+toString(jobid),
[edecba]258 matrix,
[3dd32f]259 nriter->second)) {
[edecba]260 ELOG(1, "Adding energy matrix failed.");
261 return false;
262 }
263 }
264 // ... and ForceMatrix (with two empty columns in front)
265 {
266 MatrixContainer::MatrixArray matrix;
267 const size_t rows = extractedData.forces.size();
268 matrix.resize(rows);
269 for (size_t i=0;i<rows;++i) {
270 const size_t columns = 2+extractedData.forces[i].size();
271 matrix[i].resize(columns, 0.);
272 // for (size_t j=0;j<2;++j)
273 // matrix[i][j] = 0.;
274 for (size_t j=2;j<columns;++j)
275 matrix[i][j] = extractedData.forces[i][j-2];
276 }
277 if (!Force.AddMatrix(
[c9f9bb]278 std::string("MPQCJob ")+toString(jobid),
[edecba]279 matrix,
[3dd32f]280 nriter->second)) {
[edecba]281 ELOG(1, "Adding force matrix failed.");
282 return false;
283 }
284 }
285 }
286 // add one more matrix (not required for energy)
287 MatrixContainer::MatrixArray matrix;
288 matrix.resize(1);
289 matrix[0].resize(1, 0.);
290 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
291 return false;
292 // but for energy because we need to know total number of atoms
293 matrix.resize(NoAtoms);
294 for (size_t i = 0; i< NoAtoms; ++i)
295 matrix[i].resize(2+NDIM, 0.);
296 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
297 return false;
298
[c4ee08]299 return true;
300}
301/** Print MPQCData from received results.
302 *
[c9f9bb]303 * @param fragmentData MPQCData resulting from the jobs, each associated to a job
[c4ee08]304 * @param KeySetFilename filename with keysets to associate forces correctly
305 * @param NoAtoms total number of atoms
[184943]306 * @param full_sample summed up charge density of electrons from fragments on return
307 * @param full_fragment summed up positions and charges of nuclei from fragments on return
[849cd8]308 */
309bool sumUpChargeDensity(
[c9f9bb]310 const std::map<JobId_t,MPQCData> &fragmentData,
[849cd8]311 const std::string &KeySetFilename,
[184943]312 SamplingGrid &full_sample,
313 Fragment &full_fragment)
[849cd8]314{
[c9f9bb]315 // create a vector of all job ids
316 std::vector<JobId_t> jobids;
317 std::transform(fragmentData.begin(),fragmentData.end(),
318 std::back_inserter(jobids),
319 boost::bind( &std::map<JobId_t,MPQCData>::value_type::first, boost::lambda::_1 )
320 );
321
[849cd8]322 // create lookup from job nr to fragment number
323 size_t FragmentCounter = 0;
[3dd32f]324 const std::map< JobId_t, size_t > MatrixNrLookup =
325 createMatrixNrLookup(jobids, FragmentCounter);
[849cd8]326
327 // initialise keysets
328 KeySetsContainer KeySet;
329 {
330 // else needs keysets without hydrogens
331 std::stringstream filename;
332 filename << FRAGMENTPREFIX << KEYSETFILE;
333 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
334 }
335
336 /// prepare for OrthogonalSummation
337
338 // convert KeySetContainer to IndexSetContainer
339 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
340 // create the map of all keysets
341 SubsetMap::ptr subsetmap(new SubsetMap(*container));
342
343 /// convert all MPQCData to MPQCDataMap_t
344 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
[358ddb]345 OrthogonalSumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
[c9f9bb]346 fragmentData, MatrixNrLookup, container, subsetmap));
[184943]347 std::vector<MPQCDataFragmentMap_t> Result_Fragment_fused(
[358ddb]348 OrthogonalSumUpPerLevel<MPQCDataFragmentMap_t, MPQCDataFragmentVector_t>(
[c9f9bb]349 fragmentData, MatrixNrLookup, container, subsetmap));
[849cd8]350 // obtain full grid
351 full_sample = boost::fusion::at_key<MPQCDataFused::sampled_grid>(Result_Grid_fused.back());
[184943]352 full_fragment = boost::fusion::at_key<MPQCDataFused::fragment>(Result_Fragment_fused.back());
[849cd8]353
354 return true;
355}
356
357/** Print MPQCData from received results.
358 *
[c9f9bb]359 * @param fragmentData MPQCData resulting from the jobs, associated to job id
[849cd8]360 * @param KeySetFilename filename with keysets to associate forces correctly
361 * @param NoAtoms total number of atoms
362 * @param full_sample summed up charge from fragments on return
[c4ee08]363 */
364bool printReceivedMPQCResults(
[c9f9bb]365 const std::map<JobId_t, MPQCData> &fragmentData,
[c4ee08]366 const std::string &KeySetFilename,
[849cd8]367 size_t NoAtoms,
368 SamplingGrid &full_sample)
[c4ee08]369{
[c9f9bb]370 // create a vector of all job ids
371 std::vector<JobId_t> jobids;
372 std::transform(fragmentData.begin(),fragmentData.end(),
373 std::back_inserter(jobids),
374 boost::bind( &std::map<JobId_t,MPQCData>::value_type::first, boost::lambda::_1 )
375 );
376
[c4ee08]377 // create lookup from job nr to fragment number
378 size_t FragmentCounter = 0;
[3dd32f]379 const std::map< JobId_t, size_t > MatrixNrLookup=
380 createMatrixNrLookup(jobids, FragmentCounter);
[c4ee08]381
382 // place results into maps
383 EnergyMatrix Energy;
384 ForceMatrix Force;
[c9f9bb]385 if (!putResultsintoMatrices(fragmentData, MatrixNrLookup, FragmentCounter, NoAtoms, Energy, Force))
[c4ee08]386 return false;
387
388 // initialise keysets
[6ca578]389 KeySetsContainer KeySet;
[8b58ac]390 KeySetsContainer ForceKeySet;
[edecba]391 if (!Energy.InitialiseIndices()) return false;
392
393 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
394
[8b58ac]395 {
[c4ee08]396 // else needs keysets without hydrogens
[8b58ac]397 std::stringstream filename;
398 filename << FRAGMENTPREFIX << KEYSETFILE;
399 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
400 }
[edecba]401
[8b58ac]402 {
[c4ee08]403 // forces need keysets including hydrogens
[8b58ac]404 std::stringstream filename;
405 filename << FRAGMENTPREFIX << FORCESFILE;
406 if (!ForceKeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
407 }
[6ca578]408
[a67a04]409 /// prepare for OrthogonalSummation
[fb69e9]410
411 // convert KeySetContainer to IndexSetContainer
412 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
[6ca578]413 // create the map of all keysets
414 SubsetMap::ptr subsetmap(new SubsetMap(*container));
415
[e13990b]416 /// convert all MPQCData to MPQCDataMap_t
[8cae4c]417 {
[a67a04]418 ASSERT( ForceKeySet.KeySets.size() == fragmentData.size(),
419 "FragmentationAutomationAction::performCall() - ForceKeySet's KeySets and fragmentData differ in size.");
[6ca578]420
[358ddb]421 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type MPQCDataEnergyVector_noeigenvalues_t;
[94d530f]422 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(
[358ddb]423 OrthogonalSumUpPerLevel<MPQCDataEnergyMap_t, MPQCDataEnergyVector_t>(
[c9f9bb]424 fragmentData, MatrixNrLookup, container, subsetmap));
[94d530f]425 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
[358ddb]426 OrthogonalSumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
[c9f9bb]427 fragmentData, MatrixNrLookup, container, subsetmap));
[94d530f]428 std::vector<MPQCDataTimeMap_t> Result_Time_fused(
429 SumUpPerLevel<MPQCDataTimeMap_t, MPQCDataTimeVector_t>(
[c9f9bb]430 fragmentData, MatrixNrLookup, container, subsetmap));
[94d530f]431
432 // force has extra converter
[c9f9bb]433 std::map<JobId_t, MPQCDataForceMap_t> MPQCData_Force_fused;
[c4ee08]434 convertMPQCDatatoForceMap(fragmentData, ForceKeySet, MPQCData_Force_fused);
[ff9963]435 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
436 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
[a3a382]437 subsetmap,
438 MPQCData_Force_fused,
439 container->getContainer(),
[ff9963]440 MatrixNrLookup,
441 Result_Force_fused);
[a3a382]442 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
[20b3df]443
[849cd8]444 // obtain full grid
445 full_sample = boost::fusion::at_key<MPQCDataFused::sampled_grid>(Result_Grid_fused.back());
446
[fb881a]447 // print tables (without eigenvalues, they go extra)
[27afbf]448 const size_t MaxLevel = subsetmap->getMaximumSubsetLevel();
449 const std::string energyresult =
[fb881a]450 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
[27afbf]451 Result_Energy_fused, MaxLevel);
452 LOG(0, "Energy table is \n" << energyresult);
[fb881a]453 const std::string eigenvalueresult;
454
455 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
[27afbf]456 const std::string forceresult =
457 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
458 Result_Force_fused, MaxLevel);
459 LOG(0, "Force table is \n" << forceresult);
460 // we don't want to print grid to a table
[fb881a]461 // print times (without flops for now)
462 typedef boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_flops>::type MPQCDataTimeVector_noflops_t;
[27afbf]463 const std::string timesresult =
[fb881a]464 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
[27afbf]465 Result_Time_fused, MaxLevel);
466 LOG(0, "Times table is \n" << timesresult);
[8cae4c]467 }
[56df37]468
[6ca578]469 // combine all found data
[edecba]470 if (!KeySet.ParseManyBodyTerms()) return false;
471
[c4ee08]472 EnergyMatrix EnergyFragments;
473 ForceMatrix ForceFragments;
[edecba]474 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
475 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
476
477 if(!Energy.SetLastMatrix(0., 0)) return false;
478 if(!Force.SetLastMatrix(0., 2)) return false;
479
480 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
481 // --------- sum up energy --------------------
482 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
483 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
484 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
485
486 // --------- sum up Forces --------------------
487 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
488 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
489 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
490 }
491
492 // for debugging print resulting energy and forces
493 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
494 std::stringstream output;
495 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
496 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
497 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
498 output << "\n";
499 }
500 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
501
502 return true;
503}
504
[358ddb]505/** Print MPQCData from received results.
506 *
507 * @param fragmentData MPQCData resulting from the jobs
508 * @param longrangeData VMGData resulting from long-range jobs
[1f76f3]509 * @param fullsolutionData VMGData resulting from long-range of full problem
[358ddb]510 * @param KeySetFilename filename with keysets to associate forces correctly
511 * @param NoAtoms total number of atoms
512 * @param full_sample summed up charge from fragments on return
513 */
514bool printReceivedFullResults(
[c9f9bb]515 const std::map<JobId_t,MPQCData> &fragmentData,
516 const std::map<JobId_t,VMGData> &longrangeData,
[1f76f3]517 const VMGData &fullsolutionData,
[358ddb]518 const std::string &KeySetFilename,
519 size_t NoAtoms,
520 SamplingGrid &full_sample)
521{
[c9f9bb]522 // create a vector of all job ids
523 std::vector<JobId_t> jobids;
524 std::transform(fragmentData.begin(),fragmentData.end(),
525 std::back_inserter(jobids),
526 boost::bind( &std::map<JobId_t,MPQCData>::value_type::first, boost::lambda::_1 )
527 );
[995e2f]528
[358ddb]529 // create lookup from job nr to fragment number
530 size_t FragmentCounter = 0;
[3dd32f]531 const std::map< JobId_t, size_t > MatrixNrLookup =
532 createMatrixNrLookup(jobids, FragmentCounter);
[358ddb]533
534 // initialise keysets
535 KeySetsContainer KeySet;
536 KeySetsContainer ForceKeySet;
537 {
538 // else needs keysets without hydrogens
539 std::stringstream filename;
540 filename << FRAGMENTPREFIX << KEYSETFILE;
541 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
542 }
543
544 {
545 // forces need keysets including hydrogens
546 std::stringstream filename;
547 filename << FRAGMENTPREFIX << FORCESFILE;
548 if (!ForceKeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
549 }
550
551 /// prepare for OrthogonalSummation
552
553 // convert KeySetContainer to IndexSetContainer
554 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
555 // create the map of all keysets
556 SubsetMap::ptr subsetmap(new SubsetMap(*container));
557
558 /// convert all MPQCData to MPQCDataMap_t
559 {
560 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type MPQCDataEnergyVector_noeigenvalues_t;
561 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(
562 OrthogonalSumUpPerLevel<MPQCDataEnergyMap_t, MPQCDataEnergyVector_t>(
[c9f9bb]563 fragmentData, MatrixNrLookup, container, subsetmap));
[358ddb]564 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
565 OrthogonalSumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
[c9f9bb]566 fragmentData, MatrixNrLookup, container, subsetmap));
[358ddb]567 std::vector<MPQCDataTimeMap_t> Result_Time_fused(
568 SumUpPerLevel<MPQCDataTimeMap_t, MPQCDataTimeVector_t>(
[c9f9bb]569 fragmentData, MatrixNrLookup, container, subsetmap));
[06865e]570 std::vector<MPQCDataFragmentMap_t> Result_Fragment_fused(
571 OrthogonalSumUpPerLevel<MPQCDataFragmentMap_t, MPQCDataFragmentVector_t>(
[c9f9bb]572 fragmentData, MatrixNrLookup, container, subsetmap));
[358ddb]573
574 // force has extra converter
[c9f9bb]575 std::map<JobId_t, MPQCDataForceMap_t> MPQCData_Force_fused;
[358ddb]576 convertMPQCDatatoForceMap(fragmentData, ForceKeySet, MPQCData_Force_fused);
577 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
578 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
579 subsetmap,
580 MPQCData_Force_fused,
581 container->getContainer(),
582 MatrixNrLookup,
583 Result_Force_fused);
584 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
585
586 // obtain full grid
[c9f9bb]587 std::map<JobId_t, VMGDataMap_t> VMGData_Potential_fused;
[1f76f3]588 convertDataTo<VMGData, VMGDataMap_t>(longrangeData, VMGData_Potential_fused);
[358ddb]589 OrthogonalFullSummator<VMGDataMap_t, VMGDataFused::sampled_potential> potentialSummer(
590 subsetmap,
591 VMGData_Potential_fused,
592 container->getContainer(),
[06865e]593 MatrixNrLookup);
[358ddb]594 potentialSummer(subsetmap->getMaximumSubsetLevel());
[c5feef]595 OrthogonalFullSummator<VMGDataMap_t, VMGDataFused::energy_potential> epotentialSummer(
596 subsetmap,
597 VMGData_Potential_fused,
598 container->getContainer(),
599 MatrixNrLookup);
600 epotentialSummer(subsetmap->getMaximumSubsetLevel());
[1f76f3]601 SamplingGrid full_sample = fullsolutionData.sampled_potential;
[c5feef]602 LOG(0, "Remaining long-range energy from energy_potential is " << full_sample.integral()-epotentialSummer.getFullContribution() << ".");
[06865e]603 full_sample -= potentialSummer.getFullContribution();
[358ddb]604 LOG(0, "Remaining long-range energy from potential integral is " << full_sample.integral() << ".");
605
[c5feef]606
[358ddb]607 OrthogonalFullSummator<VMGDataMap_t, VMGDataFused::energy_long> elongSummer(
608 subsetmap,
609 VMGData_Potential_fused,
610 container->getContainer(),
[06865e]611 MatrixNrLookup);
[358ddb]612 elongSummer(subsetmap->getMaximumSubsetLevel());
[1f76f3]613 double e_long = fullsolutionData.e_long;
[06865e]614 e_long -= elongSummer.getFullContribution();
[358ddb]615 LOG(0, "Remaining long-range energy is " << e_long << ".");
616
617 // print tables (without eigenvalues, they go extra)
618 const size_t MaxLevel = subsetmap->getMaximumSubsetLevel();
619 const std::string energyresult =
620 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
621 Result_Energy_fused, MaxLevel);
622 LOG(0, "Energy table is \n" << energyresult);
623 const std::string eigenvalueresult;
624
625 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
626 const std::string forceresult =
627 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
628 Result_Force_fused, MaxLevel);
629 LOG(0, "Force table is \n" << forceresult);
630 // we don't want to print grid to a table
631 // print times (without flops for now)
632 typedef boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_flops>::type MPQCDataTimeVector_noflops_t;
633 const std::string timesresult =
634 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
635 Result_Time_fused, MaxLevel);
636 LOG(0, "Times table is \n" << timesresult);
637 }
638
639 return true;
640}
641
[edecba]642
[c5324f]643void RunService(
644 boost::asio::io_service &io_service,
645 std::string message)
646{
647 message = std::string("io_service: ") + message;
648 io_service.reset();
649 Info info(message.c_str());
650 io_service.run();
651}
[edecba]652
[c5324f]653void requestIds(
654 FragmentController &controller,
655 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
656 const size_t numberjobs)
657{
658 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
659}
660
661bool createJobsFromFiles(
662 FragmentController &controller,
663 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
664 const std::vector< boost::filesystem::path > &jobfiles)
665{
666 std::vector<FragmentJob::ptr> jobs;
667 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
668 iter != jobfiles .end(); ++iter) {
669 const std::string &filename = (*iter).string();
670 if (boost::filesystem::exists(filename)) {
671 const JobId_t next_id = controller.getAvailableId();
672 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
673 +filename+"', and id "+toString(next_id)+".");
674 parsejob(jobs, params.executable.get().string(), filename, next_id);
675 } else {
676 ELOG(1, "Fragment job "+filename+" does not exist.");
677 return false;
[edecba]678 }
679 }
[c5324f]680 controller.addJobs(jobs);
681 controller.sendJobs(params.host.get(), params.port.get());
682 return true;
683}
684
[69c733]685#ifdef HAVE_VMG
686bool createLongRangeJobs(
687 FragmentController &controller,
688 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
[c9f9bb]689 const std::map<JobId_t, MPQCData> &fragmentData,
[184943]690 const SamplingGrid &full_sampled_grid,
691 const Fragment &full_fragment)
[69c733]692{
693 std::vector<FragmentJob::ptr> jobs;
[d12d621]694 // add one job for each fragment as the short-range correction which we need
695 // to subtract from the obtained full potential to get the long-range part only
[c9f9bb]696 for (std::map<JobId_t, MPQCData>::const_iterator iter = fragmentData.begin();
[d12d621]697 iter != fragmentData.end(); ++iter) {
[69c733]698 const JobId_t next_id = controller.getAvailableId();
[c9f9bb]699 LOG(1, "INFO: Creating VMGJob with " << iter->second.sampled_grid.sampled_grid.size()
700 << " gridpoints and " << iter->second.charges.size() << " particle charges.");
[d12d621]701 FragmentJob::ptr testJob(
[c9f9bb]702 new VMGJob(next_id, iter->second.sampled_grid, iter->second.positions, iter->second.charges) );
[69c733]703 jobs.push_back(testJob);
704 }
[d12d621]705
706 {
[06865e]707 const World::AtomComposite &atoms = World::getInstance().getAllAtoms();
708 std::vector< std::vector<double> > positions;
709 positions.reserve(atoms.size());
710 std::vector<double> charges;
711 charges.reserve(atoms.size());
712 std::vector<double> position(3, 0.);
713 for (World::AtomComposite::const_iterator iter = atoms.begin();
714 iter != atoms.end(); ++iter) {
715 const Vector &pos = (*iter)->getPosition();
716 for (size_t i=0;i<3;++i) position[i] = pos[i];
717 positions.push_back(position);
718 charges.push_back((double)((*iter)->getElement().getAtomicNumber()));
719 }
[d12d621]720 const JobId_t next_id = controller.getAvailableId();
[849cd8]721 LOG(1, "INFO: Creating full VMGJob with " << full_sampled_grid.sampled_grid.size()
[4adef7]722 << " gridpoints and " << charges.size() << " particle charges.");
[d12d621]723 FragmentJob::ptr testJob(
[cd77fc]724 new VMGJob(next_id, full_sampled_grid, positions, charges) );
[d12d621]725 jobs.push_back(testJob);
726 }
727
728 // then send jobs to controller
[69c733]729 controller.addJobs(jobs);
730 controller.sendJobs(params.host.get(), params.port.get());
731 return true;
732}
733#endif
734
[c5324f]735void WaitforResults(
736 boost::asio::io_service &io_service,
737 FragmentController &controller,
738 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
739 const size_t NoExpectedResults
740 )
741{
[edecba]742 size_t NoCalculatedResults = 0;
[c5324f]743 while (NoCalculatedResults != NoExpectedResults) {
[edecba]744 // wait a bit
745 boost::asio::deadline_timer timer(io_service);
746 timer.expires_from_now(boost::posix_time::milliseconds(500));
747 timer.wait();
748 // then request status
[bd81f9]749 controller.checkResults(params.host.get(), params.port.get());
[c5324f]750 RunService(io_service, "Checking on results");
751
[edecba]752 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
753 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
754 NoCalculatedResults = JobStatus.second;
755 }
[c5324f]756}
757
758
759Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
760 boost::asio::io_service io_service;
761 FragmentController controller(io_service);
762
763 // TODO: Have io_service run in second thread and merge with current again eventually
764
765 // Phase One: obtain ids
766 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
767 requestIds(controller, params, jobfiles.size());
768 RunService(io_service, "Requesting ids");
769
[69c733]770 // Phase Two: create and add MPQCJobs
[c5324f]771 if (!createJobsFromFiles(controller, params, jobfiles))
772 return Action::failure;
[69c733]773 RunService(io_service, "Adding MPQCJobs");
[c5324f]774
775 // Phase Three: calculate result
776 WaitforResults(io_service, controller, params, jobfiles.size());
[bd81f9]777 controller.receiveResults(params.host.get(), params.port.get());
[69c733]778 RunService(io_service, "Requesting short-range results");
[2764e0]779 std::vector<FragmentResult::ptr> MPQCresults = controller.getReceivedResults();
[c9f9bb]780 std::map<JobId_t, MPQCData> fragmentData;
[a0f8d3]781 ConvertFragmentResultTo<MPQCData>(MPQCresults, fragmentData);
[c5324f]782
[69c733]783#ifdef HAVE_VMG
784 if (params.DoLongrange.get()) {
[06865e]785 ASSERT( World::getInstance().getAllAtoms().size() != 0,
786 "FragmentationFragmentationAutomationAction::performCall() - please load the full molecule into the World before.");
787
[995e2f]788 // create a vector of all job ids
789 std::vector<JobId_t> jobids(MPQCresults.size(), JobId::IllegalJob);
790 std::transform(MPQCresults.begin(), MPQCresults.end(), jobids.begin(),
791 boost::bind(&FragmentResult::getId,
792 boost::bind(&FragmentResult::ptr::operator->, _1)));
793
[849cd8]794 // obtain combined charge density
795 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
796 SamplingGrid full_sample;
[184943]797 Fragment full_fragment;
[849cd8]798 sumUpChargeDensity(
799 fragmentData,
800 params.path.get(),
[184943]801 full_sample,
802 full_fragment);
[849cd8]803
[69c733]804 // Phase Four: obtain more ids
[2764e0]805 requestIds(controller, params, fragmentData.size()+1);
[69c733]806 RunService(io_service, "Requesting ids");
807
808 // Phase Five: create VMGJobs
[184943]809 if (!createLongRangeJobs(controller, params, fragmentData, full_sample, full_fragment))
[69c733]810 return Action::failure;
811 RunService(io_service, "Adding VMGJobs");
812
813 // Phase Six: calculate result
[2764e0]814 WaitforResults(io_service, controller, params, fragmentData.size()+1);
[69c733]815 controller.receiveResults(params.host.get(), params.port.get());
816 RunService(io_service, "Requesting long-range results");
817 std::vector<FragmentResult::ptr> VMGresults = controller.getReceivedResults();
[2764e0]818 ASSERT( MPQCresults.size()+1 == VMGresults.size(),
819 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresultd and VMGresults don't match.");
820
[c9f9bb]821 std::map<JobId_t, VMGData> longrangeData;
[358ddb]822 ConvertFragmentResultTo<VMGData>(VMGresults, longrangeData);
[c9f9bb]823 // remove full solution from map (must be highest id), has to be treated extra
824 VMGData fullsolutionData = (--longrangeData.end())->second;
825 longrangeData.erase(--longrangeData.end());
[358ddb]826
[2764e0]827 // Final phase: print result
828 {
829 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
[358ddb]830 printReceivedFullResults(
[2764e0]831 fragmentData,
[358ddb]832 longrangeData,
[1f76f3]833 fullsolutionData,
[2764e0]834 params.path.get(),
[849cd8]835 getNoAtomsFromAdjacencyFile(params.path.get()),
836 full_sample);
[2764e0]837 }
[69c733]838 }
[358ddb]839#else
840 // Final phase: print result
841 {
842 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
843 printReceivedMPQCResults(
844 fragmentData,
845 params.path.get(),
846 getNoAtomsFromAdjacencyFile(params.path.get()),
847 full_sample);
848 }
[69c733]849#endif
[edecba]850 size_t Exitflag = controller.getExitflag();
851
852 return (Exitflag == 0) ? Action::success : Action::failure;
853}
854
855Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
856 return Action::success;
857}
858
859Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
860 return Action::success;
861}
862
863bool FragmentationFragmentationAutomationAction::canUndo() {
864 return false;
865}
866
867bool FragmentationFragmentationAutomationAction::shouldUndo() {
868 return false;
869}
870/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.