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

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 343401 was 343401, checked in by Frederik Heber <heber@…>, 12 years ago

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

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