source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 8b58ac

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

KeySetsContainer::ParseKeySets() may now parse arbitrary files.

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