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

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

Added SamplingGrid summation to FragmentationAutomationAction.

  • added sampled_grid as key to boost::fusion::map.
  • Property mode set to 100644
File size: 24.0 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/assign.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 "Fragmentation/EnergyMatrix.hpp"
52#include "Fragmentation/ForceMatrix.hpp"
53#include "Fragmentation/Fragmentation.hpp"
54#include "Fragmentation/SetValues/Histogram.hpp"
55#include "Fragmentation/SetValues/IndexedVectors.hpp"
56#include "Fragmentation/HydrogenSaturation_enum.hpp"
57#include "Fragmentation/KeySet.hpp"
58#include "Fragmentation/KeySetsContainer.hpp"
59#include "Fragmentation/Summation/printSum.hpp"
60#include "Graph/DepthFirstSearchAnalysis.hpp"
61#include "Jobs/MPQCJob.hpp"
62#include "Jobs/MPQCData.hpp"
63#include "Jobs/MPQCData_printKeyNames.hpp"
64#include "LinearAlgebra/RealSpaceMatrix.hpp"
65#ifdef HAVE_VMG
66#include "Jobs/VMGJob.hpp"
67#endif
68#include "molecule.hpp"
69#include "World.hpp"
70
71#include <iostream>
72#include <string>
73#include <vector>
74
75#include <boost/mpl/for_each.hpp>
76
77#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
78
79using namespace MoleCuilder;
80
81using namespace boost::assign;
82
83// and construct the stuff
84#include "FragmentationAutomationAction.def"
85#include "Action_impl_pre.hpp"
86/** =========== define the function ====================== */
87
88class controller_AddOn;
89
90// needs to be defined for using the FragmentController
91controller_AddOn *getAddOn()
92{
93 return NULL;
94}
95
96const int LEVEL = 5;
97
98/** Creates a MPQCCommandJob with argument \a filename.
99 *
100 * @param jobs created job is added to this vector
101 * @param command mpqc command to execute
102 * @param filename filename being argument to job
103 * @param nextid id for this job
104 */
105void parsejob(
106 std::vector<FragmentJob::ptr> &jobs,
107 const std::string &command,
108 const std::string &filename,
109 const JobId_t nextid)
110{
111 std::ifstream file;
112 file.open(filename.c_str());
113 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
114 std::string output((std::istreambuf_iterator<char>(file)),
115 std::istreambuf_iterator<char>());
116 double begin[NDIM] = { 0., 0., 0. };
117 const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
118 const double size = M.at(0,0);
119 ASSERT( M.determinant() == size*size*size,
120 "parsejob() - current domain matrix "+toString(M)+" is not cubic.");
121 const int level = LEVEL;
122 FragmentJob::ptr testJob( new MPQCJob(nextid, output, begin, size, level) );
123 jobs.push_back(testJob);
124 file.close();
125 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
126}
127
128/** Helper function to get number of atoms somehow.
129 *
130 * Here, we just parse the number of lines in the adjacency file as
131 * it should correspond to the number of atoms, except when some atoms
132 * are not bonded, but then fragmentation makes no sense.
133 *
134 * @param path path to the adjacency file
135 */
136size_t getNoAtomsFromAdjacencyFile(const std::string &path)
137{
138 size_t NoAtoms = 0;
139
140 // parse in special file to get atom count (from line count)
141 std::string filename(path);
142 filename += FRAGMENTPREFIX;
143 filename += ADJACENCYFILE;
144 std::ifstream adjacency(filename.c_str());
145 if (adjacency.fail()) {
146 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
147 return false;
148 }
149 std::string buffer;
150 while (getline(adjacency, buffer))
151 NoAtoms++;
152 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
153
154 return NoAtoms;
155}
156
157/** Extracts MPQCData from received vector of FragmentResults.
158 *
159 * @param results results to extract MPQCData from
160 * @param fragmentData on return array filled with extracted MPQCData
161 */
162void ConvertFragmentResultToMPQCData(
163 const std::vector<FragmentResult::ptr> &results,
164 std::vector<MPQCData> &fragmentData)
165{
166 // extract results
167 fragmentData.clear();
168 fragmentData.reserve(results.size());
169
170 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
171 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
172 iter != results.end(); ++iter) {
173 //LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
174 MPQCData extractedData;
175 std::stringstream inputstream((*iter)->result);
176 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
177 boost::archive::text_iarchive ia(inputstream);
178 ia >> extractedData;
179 LOG(1, "INFO: extracted data is " << extractedData << ".");
180 fragmentData.push_back(extractedData);
181 }
182
183 ASSERT( results.size() == fragmentData.size(),
184 "ConvertFragmentResultToMPQCData() - the number of extracted data differs from the number of results.");
185}
186
187/** Print MPQCData from received results.
188 *
189 * @param results results with ids to associate with fragment number
190 * @param fragmentData MPQCData resulting from the jobs
191 * @param KeySetFilename filename with keysets to associate forces correctly
192 * @param NoAtoms total number of atoms
193 */
194bool printReceivedMPQCResults(
195 const std::vector<FragmentResult::ptr> &results,
196 const std::vector<MPQCData> &fragmentData,
197 const std::string &KeySetFilename,
198 size_t NoAtoms)
199{
200 EnergyMatrix Energy;
201 EnergyMatrix EnergyFragments;
202 ForceMatrix Force;
203 ForceMatrix ForceFragments;
204
205 // align fragments
206 std::map< JobId_t, size_t > MatrixNrLookup;
207 size_t FragmentCounter = 0;
208 {
209 // bring ids in order ...
210 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
211 IdResultMap_t IdResultMap;
212 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
213 iter != results.end(); ++iter) {
214 #ifndef NDEBUG
215 std::pair< IdResultMap_t::iterator, bool> inserter =
216 #endif
217 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
218 ASSERT( inserter.second,
219 "ExtractMPQCDataFromResults() - two results have same id "
220 +toString((*iter)->getId())+".");
221 }
222 // ... and fill lookup
223 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
224 iter != IdResultMap.end(); ++iter)
225 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
226 }
227 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
228
229 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
230 std::vector<FragmentResult::ptr>::const_iterator resultiter = results.begin();
231 for (; dataiter != fragmentData.end(); ++dataiter, ++resultiter) {
232 const MPQCData &extractedData = *dataiter;
233 // place results into EnergyMatrix ...
234 {
235 MatrixContainer::MatrixArray matrix;
236 matrix.resize(1);
237 matrix[0].resize(1, extractedData.energies.total);
238 if (!Energy.AddMatrix(
239 std::string("MPQCJob ")+toString((*resultiter)->getId()),
240 matrix,
241 MatrixNrLookup[(*resultiter)->getId()])) {
242 ELOG(1, "Adding energy matrix failed.");
243 return false;
244 }
245 }
246 // ... and ForceMatrix (with two empty columns in front)
247 {
248 MatrixContainer::MatrixArray matrix;
249 const size_t rows = extractedData.forces.size();
250 matrix.resize(rows);
251 for (size_t i=0;i<rows;++i) {
252 const size_t columns = 2+extractedData.forces[i].size();
253 matrix[i].resize(columns, 0.);
254 // for (size_t j=0;j<2;++j)
255 // matrix[i][j] = 0.;
256 for (size_t j=2;j<columns;++j)
257 matrix[i][j] = extractedData.forces[i][j-2];
258 }
259 if (!Force.AddMatrix(
260 std::string("MPQCJob ")+toString((*resultiter)->getId()),
261 matrix,
262 MatrixNrLookup[(*resultiter)->getId()])) {
263 ELOG(1, "Adding force matrix failed.");
264 return false;
265 }
266 }
267 }
268 // add one more matrix (not required for energy)
269 MatrixContainer::MatrixArray matrix;
270 matrix.resize(1);
271 matrix[0].resize(1, 0.);
272 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
273 return false;
274 // but for energy because we need to know total number of atoms
275 matrix.resize(NoAtoms);
276 for (size_t i = 0; i< NoAtoms; ++i)
277 matrix[i].resize(2+NDIM, 0.);
278 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
279 return false;
280
281 // initialise indices
282 KeySetsContainer KeySet;
283 if (!Energy.InitialiseIndices()) return false;
284
285 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
286
287 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
288
289 /// prepare for OrthogonalSummation
290
291 // gather all present indices in AllIndices
292 IndexSet::ptr AllIndices(new IndexSet);
293 for (KeySetsContainer::ArrayOfIntVectors::const_iterator iter = KeySet.KeySets.begin();
294 iter != KeySet.KeySets.end(); ++iter)
295 for(KeySetsContainer::IntVector::const_iterator keyiter = (*iter).begin();
296 keyiter != (*iter).end(); ++keyiter) {
297 if (*keyiter != -1)
298 (*AllIndices) += *keyiter;
299 }
300 LOG(1, "INFO: AllIndices is " << AllIndices << ".");
301 // create container with all keysets
302 IndexSetContainer::ptr container(new IndexSetContainer(AllIndices));
303 for (KeySetsContainer::ArrayOfIntVectors::const_iterator iter = KeySet.KeySets.begin();
304 iter != KeySet.KeySets.end(); ++iter) {
305 IndexSet tempset;
306 for(KeySetsContainer::IntVector::const_iterator keyiter = (*iter).begin();
307 keyiter != (*iter).end(); ++keyiter)
308 if (*keyiter != -1)
309 tempset += *keyiter;
310 container->insert(tempset);
311 }
312 // create the map of all keysets
313 SubsetMap::ptr subsetmap(new SubsetMap(*container));
314
315 /// convert all MPQCData to MPQCDataMap_t
316 {
317 // energy_t
318 std::vector<MPQCDataEnergyMap_t> MPQCData_Energy_fused;
319 MPQCData_Energy_fused.reserve(fragmentData.size());
320 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
321 dataiter != fragmentData.end(); ++dataiter) {
322 const MPQCData &extractedData = *dataiter;
323 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
324 MPQCDataEnergyMap_t instance;
325 boost::fusion::at_key<MPQCDataFused::energy_total>(instance) = extractedData.energies.total;
326 boost::fusion::at_key<MPQCDataFused::energy_nuclear_repulsion>(instance) = extractedData.energies.nuclear_repulsion;
327 boost::fusion::at_key<MPQCDataFused::energy_electron_coulomb>(instance) = extractedData.energies.electron_coulomb;
328 boost::fusion::at_key<MPQCDataFused::energy_electron_exchange>(instance) = extractedData.energies.electron_exchange;
329 boost::fusion::at_key<MPQCDataFused::energy_correlation>(instance) = extractedData.energies.correlation;
330 boost::fusion::at_key<MPQCDataFused::energy_overlap>(instance) = extractedData.energies.overlap;
331 boost::fusion::at_key<MPQCDataFused::energy_kinetic>(instance) = extractedData.energies.kinetic;
332 boost::fusion::at_key<MPQCDataFused::energy_hcore>(instance) = extractedData.energies.hcore;
333 boost::fusion::at_key<MPQCDataFused::energy_eigenvalues>(instance) = extractedData.energies.eigenvalues;
334 MPQCData_Energy_fused.push_back(instance);
335 }
336
337 // forces
338 const IndexSetContainer::Container_t &indices = container->getContainer();
339 ASSERT( indices.size() == fragmentData.size(),
340 "FragmentationAutomationAction::performCall() - indices and fragmentData differ in size.");
341 std::vector<MPQCDataForceMap_t> MPQCData_Force_fused;
342 MPQCData_Force_fused.reserve(fragmentData.size());
343 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
344 IndexSetContainer::Container_t::const_iterator indexiter = indices.begin();
345 for(;dataiter != fragmentData.end(); ++dataiter, ++indexiter) {
346 const MPQCData &extractedData = *dataiter;
347 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
348 MPQCDataForceMap_t instance;
349 boost::fusion::at_key<MPQCDataFused::forces>(instance) =
350 IndexedVectors(**indexiter, extractedData.forces);
351 MPQCData_Force_fused.push_back(instance);
352 }
353
354 // sampled_grid
355 std::vector<MPQCDataGridMap_t> MPQCData_Grid_fused;
356 MPQCData_Grid_fused.reserve(fragmentData.size());
357 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
358 dataiter != fragmentData.end(); ++dataiter) {
359 const MPQCData &extractedData = *dataiter;
360 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
361 MPQCDataGridMap_t instance;
362 boost::fusion::at_key<MPQCDataFused::sampled_grid>(instance) = extractedData.sampled_grid;
363 MPQCData_Grid_fused.push_back(instance);
364 }
365
366 // times
367 std::vector<MPQCDataTimeMap_t> MPQCData_Time_fused;
368 MPQCData_Time_fused.reserve(fragmentData.size());
369 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
370 dataiter != fragmentData.end(); ++dataiter) {
371 const MPQCData &extractedData = *dataiter;
372 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
373 MPQCDataTimeMap_t instance;
374 boost::fusion::at_key<MPQCDataFused::times_walltime>(instance) = extractedData.times.walltime;
375 boost::fusion::at_key<MPQCDataFused::times_cputime>(instance) = extractedData.times.cputime;
376 boost::fusion::at_key<MPQCDataFused::times_flops>(instance) = extractedData.times.flops;
377 MPQCData_Time_fused.push_back(instance);
378 }
379
380 // create a vector of all job ids
381 std::vector<JobId_t> jobids(results.size(), JobId::IllegalJob);
382 std::transform(results.begin(), results.end(), jobids.begin(),
383 boost::bind(&FragmentResult::getId,
384 boost::bind(&FragmentResult::ptr::operator->, _1)));
385
386 // sum up and print energies
387 boost::mpl::for_each<MPQCDataEnergyVector_t>(
388 printSum<MPQCDataEnergyMap_t>(
389 subsetmap,
390 MPQCData_Energy_fused,
391 jobids,
392 container->getContainer(),
393 MatrixNrLookup)
394 );
395
396 // sum up and print forces
397 boost::mpl::for_each<MPQCDataForceVector_t>(
398 printSum<MPQCDataForceMap_t>(
399 subsetmap,
400 MPQCData_Force_fused,
401 jobids,
402 container->getContainer(),
403 MatrixNrLookup)
404 );
405
406 // sum up and print grids
407 boost::mpl::for_each<MPQCDataGridVector_t>(
408 printSum<MPQCDataGridMap_t>(
409 subsetmap,
410 MPQCData_Grid_fused,
411 jobids,
412 container->getContainer(),
413 MatrixNrLookup)
414 );
415
416 // TODO: Times should just be summed not orthogonalized
417// // sum up and print times
418// boost::mpl::for_each<MPQCDataTimeVector_t>(
419// printSum<MPQCDataTimeMap_t>(
420// subsetmap,
421// MPQCData_Time_fused,
422// jobids,
423// container->getContainer(),
424// MatrixNrLookup)
425// );
426 }
427
428 // combine all found data
429 if (!KeySet.ParseManyBodyTerms()) return false;
430
431 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
432 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
433
434 if(!Energy.SetLastMatrix(0., 0)) return false;
435 if(!Force.SetLastMatrix(0., 2)) return false;
436
437 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
438 // --------- sum up energy --------------------
439 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
440 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
441 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
442
443 // --------- sum up Forces --------------------
444 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
445 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
446 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
447 }
448
449 // for debugging print resulting energy and forces
450 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
451 std::stringstream output;
452 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
453 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
454 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
455 output << "\n";
456 }
457 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
458
459 return true;
460}
461
462
463void RunService(
464 boost::asio::io_service &io_service,
465 std::string message)
466{
467 message = std::string("io_service: ") + message;
468 io_service.reset();
469 Info info(message.c_str());
470 io_service.run();
471}
472
473void requestIds(
474 FragmentController &controller,
475 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
476 const size_t numberjobs)
477{
478 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
479}
480
481bool createJobsFromFiles(
482 FragmentController &controller,
483 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
484 const std::vector< boost::filesystem::path > &jobfiles)
485{
486 std::vector<FragmentJob::ptr> jobs;
487 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
488 iter != jobfiles .end(); ++iter) {
489 const std::string &filename = (*iter).string();
490 if (boost::filesystem::exists(filename)) {
491 const JobId_t next_id = controller.getAvailableId();
492 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
493 +filename+"', and id "+toString(next_id)+".");
494 parsejob(jobs, params.executable.get().string(), filename, next_id);
495 } else {
496 ELOG(1, "Fragment job "+filename+" does not exist.");
497 return false;
498 }
499 }
500 controller.addJobs(jobs);
501 controller.sendJobs(params.host.get(), params.port.get());
502 return true;
503}
504
505#ifdef HAVE_VMG
506bool createLongRangeJobs(
507 FragmentController &controller,
508 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
509 const std::vector<MPQCData> &fragmentData)
510{
511 std::vector<FragmentJob::ptr> jobs;
512 // add one job for each fragment as the short-range correction which we need
513 // to subtract from the obtained full potential to get the long-range part only
514 for (std::vector<MPQCData>::const_iterator iter = fragmentData.begin();
515 iter != fragmentData.end(); ++iter) {
516 const JobId_t next_id = controller.getAvailableId();
517 LOG(1, "INFO: Creating VMGJob.");
518 FragmentJob::ptr testJob(
519 new VMGJob(next_id, iter->sampled_grid) );
520 jobs.push_back(testJob);
521 }
522
523 // add one more job for the full calculation
524 // TODO: Here, we actually have to combine all the other sampled_grids
525 {
526 const int level = LEVEL;
527 const int GRID = pow(2, level);
528 std::vector<double> full_sample(GRID*GRID*GRID, 0.);
529 double begin[NDIM] = { 0., 0., 0. };
530 const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
531 const double size = M.at(0,0);
532 ASSERT( M.determinant() == size*size*size,
533 "createLongRangeJobs() - current domain matrix "+toString(M)+" is not cubic.");
534 const SamplingGrid full_sampled_grid(begin, size, level, full_sample);
535 const JobId_t next_id = controller.getAvailableId();
536 FragmentJob::ptr testJob(
537 new VMGJob(next_id, full_sampled_grid) );
538 jobs.push_back(testJob);
539 }
540
541 // then send jobs to controller
542 controller.addJobs(jobs);
543 controller.sendJobs(params.host.get(), params.port.get());
544 return true;
545}
546#endif
547
548void WaitforResults(
549 boost::asio::io_service &io_service,
550 FragmentController &controller,
551 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
552 const size_t NoExpectedResults
553 )
554{
555 size_t NoCalculatedResults = 0;
556 while (NoCalculatedResults != NoExpectedResults) {
557 // wait a bit
558 boost::asio::deadline_timer timer(io_service);
559 timer.expires_from_now(boost::posix_time::milliseconds(500));
560 timer.wait();
561 // then request status
562 controller.checkResults(params.host.get(), params.port.get());
563 RunService(io_service, "Checking on results");
564
565 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
566 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
567 NoCalculatedResults = JobStatus.second;
568 }
569}
570
571
572Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
573 boost::asio::io_service io_service;
574 FragmentController controller(io_service);
575
576 // TODO: Have io_service run in second thread and merge with current again eventually
577
578 // Phase One: obtain ids
579 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
580 requestIds(controller, params, jobfiles.size());
581 RunService(io_service, "Requesting ids");
582
583 // Phase Two: create and add MPQCJobs
584 if (!createJobsFromFiles(controller, params, jobfiles))
585 return Action::failure;
586 RunService(io_service, "Adding MPQCJobs");
587
588 // Phase Three: calculate result
589 WaitforResults(io_service, controller, params, jobfiles.size());
590 controller.receiveResults(params.host.get(), params.port.get());
591 RunService(io_service, "Requesting short-range results");
592 std::vector<FragmentResult::ptr> MPQCresults = controller.getReceivedResults();
593 std::vector<MPQCData> fragmentData;
594 ConvertFragmentResultToMPQCData(MPQCresults, fragmentData);
595
596 // print intermediate short-range results
597 {
598 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
599 printReceivedMPQCResults(
600 MPQCresults,
601 fragmentData,
602 params.path.get(),
603 getNoAtomsFromAdjacencyFile(params.path.get()));
604 }
605
606#ifdef HAVE_VMG
607 if (params.DoLongrange.get()) {
608 // Phase Four: obtain more ids
609 requestIds(controller, params, fragmentData.size()+1);
610 RunService(io_service, "Requesting ids");
611
612 // Phase Five: create VMGJobs
613 if (!createLongRangeJobs(controller, params, fragmentData))
614 return Action::failure;
615 RunService(io_service, "Adding VMGJobs");
616
617 // Phase Six: calculate result
618 WaitforResults(io_service, controller, params, fragmentData.size()+1);
619 controller.receiveResults(params.host.get(), params.port.get());
620 RunService(io_service, "Requesting long-range results");
621 std::vector<FragmentResult::ptr> VMGresults = controller.getReceivedResults();
622 ASSERT( MPQCresults.size()+1 == VMGresults.size(),
623 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresultd and VMGresults don't match.");
624
625 // Final phase: print result
626 {
627 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
628 printReceivedMPQCResults(
629 MPQCresults,
630 fragmentData,
631 params.path.get(),
632 getNoAtomsFromAdjacencyFile(params.path.get()));
633 }
634 }
635#endif
636 size_t Exitflag = controller.getExitflag();
637
638 return (Exitflag == 0) ? Action::success : Action::failure;
639}
640
641Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
642 return Action::success;
643}
644
645Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
646 return Action::success;
647}
648
649bool FragmentationFragmentationAutomationAction::canUndo() {
650 return false;
651}
652
653bool FragmentationFragmentationAutomationAction::shouldUndo() {
654 return false;
655}
656/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.