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

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

Generalized template functions Convert(MPQC)DataTo and ConvertFragmentDataTo().

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