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

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

MatrixNrLookup ist now used const throughout templated functors.

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