source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 0398bd

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

Moved ConvertDataTo and ..SumUpPerLevel into distinct header files.

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