source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 995e2f

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

createMatrixNrLookup() now just needs vector<JobId_t>.

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