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

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

Added conversion constructor from KeySetsContainer to IndexSetContainer.

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