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

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

Combining FragmentResult's id and ...Data in FragmentationAutomationAction's helpers.

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