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

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

(Orthogonal)Summation now goes level-wise.

  • print(Orthogonal)Sum go through all levels and call on (Orthogonal)Summator to get value which is stored in vector of result of MapType.
  • (Orthogonal)Summator hands on level to (Orthogonal)Summation
  • (Orthogonal)Summation::operator() and Sum() now require level as parameter.
  • NOTE: We cannot set the value to zero (this depends on the default cstor). If level==0, then we return an uninitialized value.
  • Renamed print(Orthogonal)Sum -> AllLevel(Orthogonal)Summator.
  • Property mode set to 100644
File size: 24.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/AllLevelOrthogonalSummator.hpp"
58#include "Fragmentation/Summation/AllLevelSummator.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 /// prepare for OrthogonalSummation
299
300 // convert KeySetContainer to IndexSetContainer
301 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
302 // create the map of all keysets
303 SubsetMap::ptr subsetmap(new SubsetMap(*container));
304
305// we probably don't need this, it suffices if IndexedVectors has some extra indices
306// // forces need different keysets: they must include hydrogen
307// // (though without ones added by saturation)
308// IndexSetContainer::ptr forceindices(new IndexSetContainer(ForceKeySet));
309// // create the map of all keysets
310// SubsetMap::ptr subsetmapforces(new SubsetMap(*forceindices));
311
312 /// convert all MPQCData to MPQCDataMap_t
313 {
314 // energy_t
315 std::vector<MPQCDataEnergyMap_t> MPQCData_Energy_fused;
316 MPQCData_Energy_fused.reserve(fragmentData.size());
317 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
318 dataiter != fragmentData.end(); ++dataiter) {
319 const MPQCData &extractedData = *dataiter;
320 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
321 MPQCDataEnergyMap_t instance;
322 boost::fusion::at_key<MPQCDataFused::energy_total>(instance) = extractedData.energies.total;
323 boost::fusion::at_key<MPQCDataFused::energy_nuclear_repulsion>(instance) = extractedData.energies.nuclear_repulsion;
324 boost::fusion::at_key<MPQCDataFused::energy_electron_coulomb>(instance) = extractedData.energies.electron_coulomb;
325 boost::fusion::at_key<MPQCDataFused::energy_electron_exchange>(instance) = extractedData.energies.electron_exchange;
326 boost::fusion::at_key<MPQCDataFused::energy_correlation>(instance) = extractedData.energies.correlation;
327 boost::fusion::at_key<MPQCDataFused::energy_overlap>(instance) = extractedData.energies.overlap;
328 boost::fusion::at_key<MPQCDataFused::energy_kinetic>(instance) = extractedData.energies.kinetic;
329 boost::fusion::at_key<MPQCDataFused::energy_hcore>(instance) = extractedData.energies.hcore;
330 boost::fusion::at_key<MPQCDataFused::energy_eigenvalues>(instance) = extractedData.energies.eigenvalues;
331 MPQCData_Energy_fused.push_back(instance);
332 }
333
334 // forces
335 ASSERT( ForceKeySet.KeySets.size() == fragmentData.size(),
336 "FragmentationAutomationAction::performCall() - ForceKeySet's KeySets and fragmentData differ in size.");
337 std::vector<MPQCDataForceMap_t> MPQCData_Force_fused;
338 MPQCData_Force_fused.reserve(fragmentData.size());
339 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
340 KeySetsContainer::ArrayOfIntVectors::const_iterator arrayiter = ForceKeySet.KeySets.begin();
341 for(;dataiter != fragmentData.end(); ++dataiter, ++arrayiter) {
342 const MPQCData &extractedData = *dataiter;
343 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
344 MPQCDataForceMap_t instance;
345 // must convert int to index_t
346 IndexedVectors::indices_t indices(arrayiter->begin(), arrayiter->end());
347 boost::fusion::at_key<MPQCDataFused::forces>(instance) =
348 IndexedVectors(indices, extractedData.forces);
349 MPQCData_Force_fused.push_back(instance);
350 }
351
352 // sampled_grid
353 std::vector<MPQCDataGridMap_t> MPQCData_Grid_fused;
354 MPQCData_Grid_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 MPQCDataGridMap_t instance;
360 boost::fusion::at_key<MPQCDataFused::sampled_grid>(instance) = extractedData.sampled_grid;
361 MPQCData_Grid_fused.push_back(instance);
362 }
363
364 // times
365 std::vector<MPQCDataTimeMap_t> MPQCData_Time_fused;
366 MPQCData_Time_fused.reserve(fragmentData.size());
367 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
368 dataiter != fragmentData.end(); ++dataiter) {
369 const MPQCData &extractedData = *dataiter;
370 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
371 MPQCDataTimeMap_t instance;
372 boost::fusion::at_key<MPQCDataFused::times_walltime>(instance) = extractedData.times.walltime;
373 boost::fusion::at_key<MPQCDataFused::times_cputime>(instance) = extractedData.times.cputime;
374 boost::fusion::at_key<MPQCDataFused::times_flops>(instance) = extractedData.times.flops;
375 MPQCData_Time_fused.push_back(instance);
376 }
377
378 // create a vector of all job ids
379 std::vector<JobId_t> jobids(results.size(), JobId::IllegalJob);
380 std::transform(results.begin(), results.end(), jobids.begin(),
381 boost::bind(&FragmentResult::getId,
382 boost::bind(&FragmentResult::ptr::operator->, _1)));
383
384 // create summation instances
385 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(subsetmap->getMaximumSubsetLevel());
386 AllLevelOrthogonalSummator<MPQCDataEnergyMap_t> energySummer(
387 subsetmap,
388 MPQCData_Energy_fused,
389 jobids,
390 container->getContainer(),
391 MatrixNrLookup,
392 Result_Energy_fused);
393 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
394 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
395 subsetmap,
396 MPQCData_Force_fused,
397 jobids,
398 container->getContainer(),
399 MatrixNrLookup,
400 Result_Force_fused);
401 std::vector<MPQCDataGridMap_t> Result_Grid_fused(subsetmap->getMaximumSubsetLevel());
402 AllLevelOrthogonalSummator<MPQCDataGridMap_t> gridSummer(
403 subsetmap,
404 MPQCData_Grid_fused,
405 jobids,
406 container->getContainer(),
407 MatrixNrLookup,
408 Result_Grid_fused);
409 std::vector<MPQCDataTimeMap_t> Result_Time_fused(subsetmap->getMaximumSubsetLevel());
410 AllLevelSummator<MPQCDataTimeMap_t> timeSummer(
411 subsetmap,
412 MPQCData_Time_fused,
413 jobids,
414 container->getContainer(),
415 MatrixNrLookup,
416 Result_Time_fused);
417
418 // sum up
419 boost::mpl::for_each<MPQCDataEnergyVector_t>(boost::ref(energySummer));
420 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
421 boost::mpl::for_each<MPQCDataGridVector_t>(boost::ref(gridSummer));
422 boost::mpl::for_each<MPQCDataTimeVector_t>(boost::ref(timeSummer));
423 }
424
425 // combine all found data
426 if (!KeySet.ParseManyBodyTerms()) return false;
427
428 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
429 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
430
431 if(!Energy.SetLastMatrix(0., 0)) return false;
432 if(!Force.SetLastMatrix(0., 2)) return false;
433
434 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
435 // --------- sum up energy --------------------
436 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
437 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
438 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
439
440 // --------- sum up Forces --------------------
441 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
442 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
443 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
444 }
445
446 // for debugging print resulting energy and forces
447 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
448 std::stringstream output;
449 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
450 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
451 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
452 output << "\n";
453 }
454 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
455
456 return true;
457}
458
459
460void RunService(
461 boost::asio::io_service &io_service,
462 std::string message)
463{
464 message = std::string("io_service: ") + message;
465 io_service.reset();
466 Info info(message.c_str());
467 io_service.run();
468}
469
470void requestIds(
471 FragmentController &controller,
472 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
473 const size_t numberjobs)
474{
475 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
476}
477
478bool createJobsFromFiles(
479 FragmentController &controller,
480 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
481 const std::vector< boost::filesystem::path > &jobfiles)
482{
483 std::vector<FragmentJob::ptr> jobs;
484 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
485 iter != jobfiles .end(); ++iter) {
486 const std::string &filename = (*iter).string();
487 if (boost::filesystem::exists(filename)) {
488 const JobId_t next_id = controller.getAvailableId();
489 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
490 +filename+"', and id "+toString(next_id)+".");
491 parsejob(jobs, params.executable.get().string(), filename, next_id);
492 } else {
493 ELOG(1, "Fragment job "+filename+" does not exist.");
494 return false;
495 }
496 }
497 controller.addJobs(jobs);
498 controller.sendJobs(params.host.get(), params.port.get());
499 return true;
500}
501
502#ifdef HAVE_VMG
503bool createLongRangeJobs(
504 FragmentController &controller,
505 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
506 const std::vector<MPQCData> &fragmentData)
507{
508 std::vector<FragmentJob::ptr> jobs;
509 // add one job for each fragment as the short-range correction which we need
510 // to subtract from the obtained full potential to get the long-range part only
511 for (std::vector<MPQCData>::const_iterator iter = fragmentData.begin();
512 iter != fragmentData.end(); ++iter) {
513 const JobId_t next_id = controller.getAvailableId();
514 LOG(1, "INFO: Creating VMGJob.");
515 FragmentJob::ptr testJob(
516 new VMGJob(next_id, iter->sampled_grid, iter->positions, iter->charges) );
517 jobs.push_back(testJob);
518 }
519
520 // add one more job for the full calculation
521 // TODO: Here, we actually have to combine all the other sampled_grids
522 {
523 const int level = LEVEL;
524 const int GRID = pow(2, level);
525 std::vector<double> full_sample(GRID*GRID*GRID, 0.);
526 double begin[NDIM] = { 0., 0., 0. };
527 const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
528 const double size = M.at(0,0);
529 ASSERT( M.determinant() == size*size*size,
530 "createLongRangeJobs() - current domain matrix "+toString(M)+" is not cubic.");
531 const SamplingGrid full_sampled_grid(begin, size, level, full_sample);
532 const std::vector< std::vector<double> > positions;
533 const std::vector<double> charges;
534 const JobId_t next_id = controller.getAvailableId();
535 FragmentJob::ptr testJob(
536 new VMGJob(next_id, full_sampled_grid, positions, charges) );
537 jobs.push_back(testJob);
538 }
539
540 // then send jobs to controller
541 controller.addJobs(jobs);
542 controller.sendJobs(params.host.get(), params.port.get());
543 return true;
544}
545#endif
546
547void WaitforResults(
548 boost::asio::io_service &io_service,
549 FragmentController &controller,
550 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
551 const size_t NoExpectedResults
552 )
553{
554 size_t NoCalculatedResults = 0;
555 while (NoCalculatedResults != NoExpectedResults) {
556 // wait a bit
557 boost::asio::deadline_timer timer(io_service);
558 timer.expires_from_now(boost::posix_time::milliseconds(500));
559 timer.wait();
560 // then request status
561 controller.checkResults(params.host.get(), params.port.get());
562 RunService(io_service, "Checking on results");
563
564 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
565 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
566 NoCalculatedResults = JobStatus.second;
567 }
568}
569
570
571Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
572 boost::asio::io_service io_service;
573 FragmentController controller(io_service);
574
575 // TODO: Have io_service run in second thread and merge with current again eventually
576
577 // Phase One: obtain ids
578 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
579 requestIds(controller, params, jobfiles.size());
580 RunService(io_service, "Requesting ids");
581
582 // Phase Two: create and add MPQCJobs
583 if (!createJobsFromFiles(controller, params, jobfiles))
584 return Action::failure;
585 RunService(io_service, "Adding MPQCJobs");
586
587 // Phase Three: calculate result
588 WaitforResults(io_service, controller, params, jobfiles.size());
589 controller.receiveResults(params.host.get(), params.port.get());
590 RunService(io_service, "Requesting short-range results");
591 std::vector<FragmentResult::ptr> MPQCresults = controller.getReceivedResults();
592 std::vector<MPQCData> fragmentData;
593 ConvertFragmentResultToMPQCData(MPQCresults, fragmentData);
594
595 // print intermediate short-range results
596 {
597 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
598 printReceivedMPQCResults(
599 MPQCresults,
600 fragmentData,
601 params.path.get(),
602 getNoAtomsFromAdjacencyFile(params.path.get()));
603 }
604
605#ifdef HAVE_VMG
606 if (params.DoLongrange.get()) {
607 // Phase Four: obtain more ids
608 requestIds(controller, params, fragmentData.size()+1);
609 RunService(io_service, "Requesting ids");
610
611 // Phase Five: create VMGJobs
612 if (!createLongRangeJobs(controller, params, fragmentData))
613 return Action::failure;
614 RunService(io_service, "Adding VMGJobs");
615
616 // Phase Six: calculate result
617 WaitforResults(io_service, controller, params, fragmentData.size()+1);
618 controller.receiveResults(params.host.get(), params.port.get());
619 RunService(io_service, "Requesting long-range results");
620 std::vector<FragmentResult::ptr> VMGresults = controller.getReceivedResults();
621 ASSERT( MPQCresults.size()+1 == VMGresults.size(),
622 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresultd and VMGresults don't match.");
623
624 // Final phase: print result
625 {
626 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
627 printReceivedMPQCResults(
628 MPQCresults,
629 fragmentData,
630 params.path.get(),
631 getNoAtomsFromAdjacencyFile(params.path.get()));
632 }
633 }
634#endif
635 size_t Exitflag = controller.getExitflag();
636
637 return (Exitflag == 0) ? Action::success : Action::failure;
638}
639
640Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
641 return Action::success;
642}
643
644Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
645 return Action::success;
646}
647
648bool FragmentationFragmentationAutomationAction::canUndo() {
649 return false;
650}
651
652bool FragmentationFragmentationAutomationAction::shouldUndo() {
653 return false;
654}
655/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.