source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 849cd8

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

Created new function sumUpChargeDensity() that just sums up the grid.

  • this is mostly just taken from printReceivedMPQCResults().
  • Property mode set to 100644
File size: 30.5 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * 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
41#include <boost/mpl/remove.hpp>
42
43#include "CodePatterns/Assert.hpp"
44#include "CodePatterns/Info.hpp"
45#include "CodePatterns/Log.hpp"
46#include "JobMarket/Controller/FragmentController.hpp"
47#include "JobMarket/Jobs/FragmentJob.hpp"
48
49#include "Atom/atom.hpp"
50#include "Box.hpp"
51#include "Fragmentation/EnergyMatrix.hpp"
52#include "Fragmentation/ForceMatrix.hpp"
53#include "Fragmentation/Fragmentation.hpp"
54#include "Fragmentation/SetValues/Histogram.hpp"
55#include "Fragmentation/SetValues/IndexedVectors.hpp"
56#include "Fragmentation/HydrogenSaturation_enum.hpp"
57#include "Fragmentation/KeySet.hpp"
58#include "Fragmentation/KeySetsContainer.hpp"
59#include "Fragmentation/Summation/AllLevelOrthogonalSummator.hpp"
60#include "Fragmentation/Summation/AllLevelSummator.hpp"
61#include "Fragmentation/Summation/writeTable.hpp"
62#include "Graph/DepthFirstSearchAnalysis.hpp"
63#include "Helpers/defs.hpp"
64#include "Jobs/MPQCJob.hpp"
65#include "Jobs/MPQCData.hpp"
66#include "Jobs/MPQCData_printKeyNames.hpp"
67#include "Jobs/Grid/SamplingGrid.hpp"
68#include "LinearAlgebra/RealSpaceMatrix.hpp"
69#ifdef HAVE_VMG
70#include "Jobs/VMGJob.hpp"
71#endif
72#include "molecule.hpp"
73#include "World.hpp"
74
75#include <iostream>
76#include <string>
77#include <vector>
78
79#include <boost/mpl/for_each.hpp>
80
81#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
82
83using namespace MoleCuilder;
84
85// and construct the stuff
86#include "FragmentationAutomationAction.def"
87#include "Action_impl_pre.hpp"
88/** =========== define the function ====================== */
89
90class controller_AddOn;
91
92// needs to be defined for using the FragmentController
93controller_AddOn *getAddOn()
94{
95 return NULL;
96}
97
98const int LEVEL = 5;
99
100/** Creates a MPQCCommandJob with argument \a filename.
101 *
102 * @param jobs created job is added to this vector
103 * @param command mpqc command to execute
104 * @param filename filename being argument to job
105 * @param nextid id for this job
106 */
107void parsejob(
108 std::vector<FragmentJob::ptr> &jobs,
109 const std::string &command,
110 const std::string &filename,
111 const JobId_t nextid)
112{
113 std::ifstream file;
114 file.open(filename.c_str());
115 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
116 std::string output((std::istreambuf_iterator<char>(file)),
117 std::istreambuf_iterator<char>());
118 double begin[NDIM] = { 0., 0., 0. };
119 const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
120 const double size = M.at(0,0);
121 ASSERT( M.determinant() == size*size*size,
122 "parsejob() - current domain matrix "+toString(M)+" is not cubic.");
123 const int level = LEVEL;
124 FragmentJob::ptr testJob( new MPQCJob(nextid, output, begin, size, level) );
125 jobs.push_back(testJob);
126 file.close();
127 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
128}
129
130/** Helper function to get number of atoms somehow.
131 *
132 * Here, we just parse the number of lines in the adjacency file as
133 * it should correspond to the number of atoms, except when some atoms
134 * are not bonded, but then fragmentation makes no sense.
135 *
136 * @param path path to the adjacency file
137 */
138size_t getNoAtomsFromAdjacencyFile(const std::string &path)
139{
140 size_t NoAtoms = 0;
141
142 // parse in special file to get atom count (from line count)
143 std::string filename(path);
144 filename += FRAGMENTPREFIX;
145 filename += ADJACENCYFILE;
146 std::ifstream adjacency(filename.c_str());
147 if (adjacency.fail()) {
148 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
149 return false;
150 }
151 std::string buffer;
152 while (getline(adjacency, buffer))
153 NoAtoms++;
154 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
155
156 return NoAtoms;
157}
158
159/** Extracts MPQCData from received vector of FragmentResults.
160 *
161 * @param results results to extract MPQCData from
162 * @param fragmentData on return array filled with extracted MPQCData
163 */
164void ConvertFragmentResultToMPQCData(
165 const std::vector<FragmentResult::ptr> &results,
166 std::vector<MPQCData> &fragmentData)
167{
168 // extract results
169 fragmentData.clear();
170 fragmentData.reserve(results.size());
171
172 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
173 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
174 iter != results.end(); ++iter) {
175 //LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
176 MPQCData extractedData;
177 std::stringstream inputstream((*iter)->result);
178 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
179 boost::archive::text_iarchive ia(inputstream);
180 ia >> extractedData;
181 LOG(1, "INFO: extracted data is " << extractedData << ".");
182 fragmentData.push_back(extractedData);
183 }
184
185 ASSERT( results.size() == fragmentData.size(),
186 "ConvertFragmentResultToMPQCData() - the number of extracted data differs from the number of results.");
187}
188
189/** Creates a lookup from FragmentJob::id to the true fragment number.
190 *
191 * @param results result with job ids
192 * @param MatrixNrLookup Lookup up-map, filled on return
193 * @param FragmentCounter total number of fragments on return
194 */
195void createMatrixNrLookup(
196 const std::vector<FragmentResult::ptr> &results,
197 std::map< JobId_t, size_t > &MatrixNrLookup,
198 size_t &FragmentCounter)
199{
200 // align fragments
201 MatrixNrLookup.clear();
202 FragmentCounter = 0;
203 {
204 // bring ids in order ...
205 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
206 IdResultMap_t IdResultMap;
207 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
208 iter != results.end(); ++iter) {
209 #ifndef NDEBUG
210 std::pair< IdResultMap_t::iterator, bool> inserter =
211 #endif
212 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
213 ASSERT( inserter.second,
214 "ExtractMPQCDataFromResults() - two results have same id "
215 +toString((*iter)->getId())+".");
216 }
217 // ... and fill lookup
218 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
219 iter != IdResultMap.end(); ++iter)
220 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
221 }
222 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
223}
224
225/** Place results from FragmentResult into EnergyMatrix and ForceMatrix.
226 *
227 * @param results results with ids to associate with fragment number
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(
237 const std::vector<FragmentResult::ptr> &results,
238 const std::vector<MPQCData> &fragmentData,
239 std::map< JobId_t, size_t > &MatrixNrLookup,
240 const size_t FragmentCounter,
241 const size_t NoAtoms,
242 EnergyMatrix &Energy,
243 ForceMatrix &Force)
244{
245 ASSERT( results.size() == fragmentData.size(),
246 "printReceivedMPQCResults() - results and fragmentData differ in size.");
247 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
248 std::vector<FragmentResult::ptr>::const_iterator resultiter = results.begin();
249 for (; dataiter != fragmentData.end(); ++dataiter, ++resultiter) {
250 const MPQCData &extractedData = *dataiter;
251 // place results into EnergyMatrix ...
252 {
253 MatrixContainer::MatrixArray matrix;
254 matrix.resize(1);
255 matrix[0].resize(1, extractedData.energies.total);
256 if (!Energy.AddMatrix(
257 std::string("MPQCJob ")+toString((*resultiter)->getId()),
258 matrix,
259 MatrixNrLookup[(*resultiter)->getId()])) {
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(
278 std::string("MPQCJob ")+toString((*resultiter)->getId()),
279 matrix,
280 MatrixNrLookup[(*resultiter)->getId()])) {
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
299 return true;
300}
301
302template <typename T>
303void convertMPQCDataTo(
304 const std::vector<MPQCData> &fragmentData,
305 std::vector<T> &MPQCData_fused)
306{
307 MPQCData_fused.clear();
308}
309
310template <>
311void convertMPQCDataTo<MPQCDataEnergyMap_t>(
312 const std::vector<MPQCData> &fragmentData,
313 std::vector<MPQCDataEnergyMap_t> &MPQCData_Energy_fused)
314{
315 // energy_t
316 MPQCData_Energy_fused.clear();
317 MPQCData_Energy_fused.reserve(fragmentData.size());
318 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
319 dataiter != fragmentData.end(); ++dataiter) {
320 const MPQCData &extractedData = *dataiter;
321 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
322 MPQCDataEnergyMap_t instance;
323 boost::fusion::at_key<MPQCDataFused::energy_total>(instance) = extractedData.energies.total;
324 boost::fusion::at_key<MPQCDataFused::energy_nuclear_repulsion>(instance) = extractedData.energies.nuclear_repulsion;
325 boost::fusion::at_key<MPQCDataFused::energy_electron_coulomb>(instance) = extractedData.energies.electron_coulomb;
326 boost::fusion::at_key<MPQCDataFused::energy_electron_exchange>(instance) = extractedData.energies.electron_exchange;
327 boost::fusion::at_key<MPQCDataFused::energy_correlation>(instance) = extractedData.energies.correlation;
328 boost::fusion::at_key<MPQCDataFused::energy_overlap>(instance) = extractedData.energies.overlap;
329 boost::fusion::at_key<MPQCDataFused::energy_kinetic>(instance) = extractedData.energies.kinetic;
330 boost::fusion::at_key<MPQCDataFused::energy_hcore>(instance) = extractedData.energies.hcore;
331 boost::fusion::at_key<MPQCDataFused::energy_eigenvalues>(instance) = extractedData.energies.eigenvalues;
332 MPQCData_Energy_fused.push_back(instance);
333 }
334}
335
336
337void convertMPQCDatatoForceMap(
338 const std::vector<MPQCData> &fragmentData,
339 const KeySetsContainer &ForceKeySet,
340 std::vector<MPQCDataForceMap_t> &MPQCData_Force_fused)
341{
342 // forces
343 ASSERT( ForceKeySet.KeySets.size() == fragmentData.size(),
344 "FragmentationAutomationAction::performCall() - indices and fragmentData differ in size.");
345 MPQCData_Force_fused.clear();
346 MPQCData_Force_fused.reserve(fragmentData.size());
347 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
348 KeySetsContainer::ArrayOfIntVectors::const_iterator arrayiter = ForceKeySet.KeySets.begin();
349 for(;dataiter != fragmentData.end(); ++dataiter, ++arrayiter) {
350 const MPQCData &extractedData = *dataiter;
351 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
352 MPQCDataForceMap_t instance;
353 // must convert int to index_t
354 IndexedVectors::indices_t indices(arrayiter->begin(), arrayiter->end());
355 boost::fusion::at_key<MPQCDataFused::forces>(instance) =
356 IndexedVectors(indices, extractedData.forces);
357 MPQCData_Force_fused.push_back(instance);
358 }
359}
360
361template <>
362void convertMPQCDataTo<MPQCDataGridMap_t>(
363 const std::vector<MPQCData> &fragmentData,
364 std::vector<MPQCDataGridMap_t> &MPQCData_Grid_fused)
365{
366 // sampled_grid
367 MPQCData_Grid_fused.clear();
368 MPQCData_Grid_fused.reserve(fragmentData.size());
369 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
370 dataiter != fragmentData.end(); ++dataiter) {
371 const MPQCData &extractedData = *dataiter;
372 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
373 MPQCDataGridMap_t instance;
374 boost::fusion::at_key<MPQCDataFused::sampled_grid>(instance) = extractedData.sampled_grid;
375 MPQCData_Grid_fused.push_back(instance);
376 }
377}
378
379template <>
380void convertMPQCDataTo<MPQCDataTimeMap_t>(
381 const std::vector<MPQCData> &fragmentData,
382 std::vector<MPQCDataTimeMap_t> &MPQCData_Time_fused)
383{
384 // times
385 MPQCData_Time_fused.clear();
386 MPQCData_Time_fused.reserve(fragmentData.size());
387 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
388 dataiter != fragmentData.end(); ++dataiter) {
389 const MPQCData &extractedData = *dataiter;
390 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
391 MPQCDataTimeMap_t instance;
392 boost::fusion::at_key<MPQCDataFused::times_walltime>(instance) = extractedData.times.walltime;
393 boost::fusion::at_key<MPQCDataFused::times_cputime>(instance) = extractedData.times.cputime;
394 boost::fusion::at_key<MPQCDataFused::times_flops>(instance) = extractedData.times.flops;
395 MPQCData_Time_fused.push_back(instance);
396 }
397}
398
399template <typename TypeMap, typename TypeVector>
400std::vector<TypeMap> SumUpPerLevel(
401 const std::vector<MPQCData> &fragmentData,
402 const std::vector<JobId_t> &jobids,
403 std::map< JobId_t, size_t > &MatrixNrLookup,
404 const IndexSetContainer::ptr &container,
405 SubsetMap::ptr &subsetmap
406 )
407{
408 // place data into boost::fusion::map instance
409 std::vector<TypeMap> MPQCData_fused;
410 convertMPQCDataTo<TypeMap>(fragmentData, MPQCData_fused);
411 // instantiate summator
412 std::vector<TypeMap> Result_fused(subsetmap->getMaximumSubsetLevel());
413 AllLevelOrthogonalSummator<TypeMap> Summer(
414 subsetmap,
415 MPQCData_fused,
416 jobids,
417 container->getContainer(),
418 MatrixNrLookup,
419 Result_fused);
420 // sum up for each type key in TypeVector
421 boost::mpl::for_each<TypeVector>(boost::ref(Summer));
422 return Result_fused;
423}
424
425/** Print MPQCData from received results.
426 *
427 * @param results results with ids to associate with fragment number
428 * @param fragmentData MPQCData resulting from the jobs
429 * @param KeySetFilename filename with keysets to associate forces correctly
430 * @param NoAtoms total number of atoms
431 * @param full_sample summed up charge from fragments on return
432 */
433bool sumUpChargeDensity(
434 const std::vector<FragmentResult::ptr> &results,
435 const std::vector<MPQCData> &fragmentData,
436 const std::string &KeySetFilename,
437 SamplingGrid &full_sample)
438{
439 // create lookup from job nr to fragment number
440 std::map< JobId_t, size_t > MatrixNrLookup;
441 size_t FragmentCounter = 0;
442 createMatrixNrLookup(results, MatrixNrLookup, FragmentCounter);
443
444 // initialise keysets
445 KeySetsContainer KeySet;
446 {
447 // else needs keysets without hydrogens
448 std::stringstream filename;
449 filename << FRAGMENTPREFIX << KEYSETFILE;
450 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
451 }
452
453 /// prepare for OrthogonalSummation
454
455 // convert KeySetContainer to IndexSetContainer
456 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
457 // create the map of all keysets
458 SubsetMap::ptr subsetmap(new SubsetMap(*container));
459
460 // create a vector of all job ids
461 std::vector<JobId_t> jobids(results.size(), JobId::IllegalJob);
462 std::transform(results.begin(), results.end(), jobids.begin(),
463 boost::bind(&FragmentResult::getId,
464 boost::bind(&FragmentResult::ptr::operator->, _1)));
465
466 /// convert all MPQCData to MPQCDataMap_t
467 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
468 SumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
469 fragmentData, jobids, MatrixNrLookup, container, subsetmap));
470 // obtain full grid
471 full_sample = boost::fusion::at_key<MPQCDataFused::sampled_grid>(Result_Grid_fused.back());
472
473 return true;
474}
475
476
477/** Print MPQCData from received results.
478 *
479 * @param results results with ids to associate with fragment number
480 * @param fragmentData MPQCData resulting from the jobs
481 * @param KeySetFilename filename with keysets to associate forces correctly
482 * @param NoAtoms total number of atoms
483 * @param full_sample summed up charge from fragments on return
484 */
485bool printReceivedMPQCResults(
486 const std::vector<FragmentResult::ptr> &results,
487 const std::vector<MPQCData> &fragmentData,
488 const std::string &KeySetFilename,
489 size_t NoAtoms,
490 SamplingGrid &full_sample)
491{
492 // create lookup from job nr to fragment number
493 std::map< JobId_t, size_t > MatrixNrLookup;
494 size_t FragmentCounter = 0;
495 createMatrixNrLookup(results, MatrixNrLookup, FragmentCounter);
496
497 // place results into maps
498 EnergyMatrix Energy;
499 ForceMatrix Force;
500 if (!putResultsintoMatrices(results, fragmentData, MatrixNrLookup, FragmentCounter, NoAtoms, Energy, Force))
501 return false;
502
503 // initialise keysets
504 KeySetsContainer KeySet;
505 KeySetsContainer ForceKeySet;
506 if (!Energy.InitialiseIndices()) return false;
507
508 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
509
510 {
511 // else needs keysets without hydrogens
512 std::stringstream filename;
513 filename << FRAGMENTPREFIX << KEYSETFILE;
514 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
515 }
516
517 {
518 // forces need keysets including hydrogens
519 std::stringstream filename;
520 filename << FRAGMENTPREFIX << FORCESFILE;
521 if (!ForceKeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
522 }
523
524 /// prepare for OrthogonalSummation
525
526 // convert KeySetContainer to IndexSetContainer
527 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
528 // create the map of all keysets
529 SubsetMap::ptr subsetmap(new SubsetMap(*container));
530
531 // create a vector of all job ids
532 std::vector<JobId_t> jobids(results.size(), JobId::IllegalJob);
533 std::transform(results.begin(), results.end(), jobids.begin(),
534 boost::bind(&FragmentResult::getId,
535 boost::bind(&FragmentResult::ptr::operator->, _1)));
536
537 /// convert all MPQCData to MPQCDataMap_t
538 {
539 ASSERT( ForceKeySet.KeySets.size() == fragmentData.size(),
540 "FragmentationAutomationAction::performCall() - ForceKeySet's KeySets and fragmentData differ in size.");
541
542 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(
543 SumUpPerLevel<MPQCDataEnergyMap_t, MPQCDataEnergyVector_t>(
544 fragmentData, jobids, MatrixNrLookup, container, subsetmap));
545 std::vector<MPQCDataGridMap_t> Result_Grid_fused(
546 SumUpPerLevel<MPQCDataGridMap_t, MPQCDataGridVector_t>(
547 fragmentData, jobids, MatrixNrLookup, container, subsetmap));
548 std::vector<MPQCDataTimeMap_t> Result_Time_fused(
549 SumUpPerLevel<MPQCDataTimeMap_t, MPQCDataTimeVector_t>(
550 fragmentData, jobids, MatrixNrLookup, container, subsetmap));
551
552 // force has extra converter
553 std::vector<MPQCDataForceMap_t> MPQCData_Force_fused;
554 convertMPQCDatatoForceMap(fragmentData, ForceKeySet, MPQCData_Force_fused);
555 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
556 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
557 subsetmap,
558 MPQCData_Force_fused,
559 jobids,
560 container->getContainer(),
561 MatrixNrLookup,
562 Result_Force_fused);
563 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
564
565 // obtain full grid
566 full_sample = boost::fusion::at_key<MPQCDataFused::sampled_grid>(Result_Grid_fused.back());
567
568 // print tables (without eigenvalues, they go extra)
569 const size_t MaxLevel = subsetmap->getMaximumSubsetLevel();
570 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type MPQCDataEnergyVector_noeigenvalues_t;
571 const std::string energyresult =
572 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
573 Result_Energy_fused, MaxLevel);
574 LOG(0, "Energy table is \n" << energyresult);
575 const std::string eigenvalueresult;
576
577 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
578 const std::string forceresult =
579 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
580 Result_Force_fused, MaxLevel);
581 LOG(0, "Force table is \n" << forceresult);
582 // we don't want to print grid to a table
583 // print times (without flops for now)
584 typedef boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_flops>::type MPQCDataTimeVector_noflops_t;
585 const std::string timesresult =
586 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
587 Result_Time_fused, MaxLevel);
588 LOG(0, "Times table is \n" << timesresult);
589 }
590
591 // combine all found data
592 if (!KeySet.ParseManyBodyTerms()) return false;
593
594 EnergyMatrix EnergyFragments;
595 ForceMatrix ForceFragments;
596 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
597 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
598
599 if(!Energy.SetLastMatrix(0., 0)) return false;
600 if(!Force.SetLastMatrix(0., 2)) return false;
601
602 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
603 // --------- sum up energy --------------------
604 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
605 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
606 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
607
608 // --------- sum up Forces --------------------
609 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
610 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
611 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
612 }
613
614 // for debugging print resulting energy and forces
615 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
616 std::stringstream output;
617 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
618 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
619 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
620 output << "\n";
621 }
622 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
623
624 return true;
625}
626
627
628void RunService(
629 boost::asio::io_service &io_service,
630 std::string message)
631{
632 message = std::string("io_service: ") + message;
633 io_service.reset();
634 Info info(message.c_str());
635 io_service.run();
636}
637
638void requestIds(
639 FragmentController &controller,
640 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
641 const size_t numberjobs)
642{
643 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
644}
645
646bool createJobsFromFiles(
647 FragmentController &controller,
648 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
649 const std::vector< boost::filesystem::path > &jobfiles)
650{
651 std::vector<FragmentJob::ptr> jobs;
652 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
653 iter != jobfiles .end(); ++iter) {
654 const std::string &filename = (*iter).string();
655 if (boost::filesystem::exists(filename)) {
656 const JobId_t next_id = controller.getAvailableId();
657 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
658 +filename+"', and id "+toString(next_id)+".");
659 parsejob(jobs, params.executable.get().string(), filename, next_id);
660 } else {
661 ELOG(1, "Fragment job "+filename+" does not exist.");
662 return false;
663 }
664 }
665 controller.addJobs(jobs);
666 controller.sendJobs(params.host.get(), params.port.get());
667 return true;
668}
669
670#ifdef HAVE_VMG
671bool createLongRangeJobs(
672 FragmentController &controller,
673 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
674 const std::vector<MPQCData> &fragmentData,
675 const SamplingGrid &full_sampled_grid)
676{
677 std::vector<FragmentJob::ptr> jobs;
678 // add one job for each fragment as the short-range correction which we need
679 // to subtract from the obtained full potential to get the long-range part only
680 for (std::vector<MPQCData>::const_iterator iter = fragmentData.begin();
681 iter != fragmentData.end(); ++iter) {
682 const JobId_t next_id = controller.getAvailableId();
683 LOG(1, "INFO: Creating VMGJob with " << iter->sampled_grid.sampled_grid.size()
684 << " gridpoints and " << iter->charges.size() << " particle charges.");
685 FragmentJob::ptr testJob(
686 new VMGJob(next_id, iter->sampled_grid, iter->positions, iter->charges) );
687 jobs.push_back(testJob);
688 }
689
690 {
691// const int level = LEVEL;
692// const int GRID = pow(2, level);
693// double begin[NDIM] = { 0., 0., 0. };
694// const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
695// const double size = M.at(0,0);
696// ASSERT( M.determinant() == size*size*size,
697// "createLongRangeJobs() - current domain matrix "+toString(M)+" is not cubic.");
698 const std::vector< std::vector<double> > positions;
699 const std::vector<double> charges;
700 const JobId_t next_id = controller.getAvailableId();
701 LOG(1, "INFO: Creating full VMGJob with " << full_sampled_grid.sampled_grid.size()
702 << " gridpoints and " << charges.size() << " particle charges.");
703 FragmentJob::ptr testJob(
704 new VMGJob(next_id, full_sampled_grid, positions, charges) );
705 jobs.push_back(testJob);
706 }
707
708 // then send jobs to controller
709 controller.addJobs(jobs);
710 controller.sendJobs(params.host.get(), params.port.get());
711 return true;
712}
713#endif
714
715void WaitforResults(
716 boost::asio::io_service &io_service,
717 FragmentController &controller,
718 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
719 const size_t NoExpectedResults
720 )
721{
722 size_t NoCalculatedResults = 0;
723 while (NoCalculatedResults != NoExpectedResults) {
724 // wait a bit
725 boost::asio::deadline_timer timer(io_service);
726 timer.expires_from_now(boost::posix_time::milliseconds(500));
727 timer.wait();
728 // then request status
729 controller.checkResults(params.host.get(), params.port.get());
730 RunService(io_service, "Checking on results");
731
732 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
733 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
734 NoCalculatedResults = JobStatus.second;
735 }
736}
737
738
739Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
740 boost::asio::io_service io_service;
741 FragmentController controller(io_service);
742
743 // TODO: Have io_service run in second thread and merge with current again eventually
744
745 // Phase One: obtain ids
746 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
747 requestIds(controller, params, jobfiles.size());
748 RunService(io_service, "Requesting ids");
749
750 // Phase Two: create and add MPQCJobs
751 if (!createJobsFromFiles(controller, params, jobfiles))
752 return Action::failure;
753 RunService(io_service, "Adding MPQCJobs");
754
755 // Phase Three: calculate result
756 WaitforResults(io_service, controller, params, jobfiles.size());
757 controller.receiveResults(params.host.get(), params.port.get());
758 RunService(io_service, "Requesting short-range results");
759 std::vector<FragmentResult::ptr> MPQCresults = controller.getReceivedResults();
760 std::vector<MPQCData> fragmentData;
761 ConvertFragmentResultToMPQCData(MPQCresults, fragmentData);
762
763#ifdef HAVE_VMG
764 if (params.DoLongrange.get()) {
765 // obtain combined charge density
766 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
767 SamplingGrid full_sample;
768 sumUpChargeDensity(
769 MPQCresults,
770 fragmentData,
771 params.path.get(),
772 full_sample);
773
774 // Phase Four: obtain more ids
775 requestIds(controller, params, fragmentData.size()+1);
776 RunService(io_service, "Requesting ids");
777
778 // Phase Five: create VMGJobs
779 if (!createLongRangeJobs(controller, params, fragmentData, full_sample))
780 return Action::failure;
781 RunService(io_service, "Adding VMGJobs");
782
783 // Phase Six: calculate result
784 WaitforResults(io_service, controller, params, fragmentData.size()+1);
785 controller.receiveResults(params.host.get(), params.port.get());
786 RunService(io_service, "Requesting long-range results");
787 std::vector<FragmentResult::ptr> VMGresults = controller.getReceivedResults();
788 ASSERT( MPQCresults.size()+1 == VMGresults.size(),
789 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresultd and VMGresults don't match.");
790
791 // Final phase: print result
792 {
793 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
794 printReceivedMPQCResults(
795 MPQCresults,
796 fragmentData,
797 params.path.get(),
798 getNoAtomsFromAdjacencyFile(params.path.get()),
799 full_sample);
800 }
801 }
802#endif
803 size_t Exitflag = controller.getExitflag();
804
805 return (Exitflag == 0) ? Action::success : Action::failure;
806}
807
808Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
809 return Action::success;
810}
811
812Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
813 return Action::success;
814}
815
816bool FragmentationFragmentationAutomationAction::canUndo() {
817 return false;
818}
819
820bool FragmentationFragmentationAutomationAction::shouldUndo() {
821 return false;
822}
823/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.