source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 4adef7

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

Added some debugging output to FragmentationAutomationAction.

  • Property mode set to 100644
File size: 26.2 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * FragmentationAutomationAction.cpp
25 *
26 * Created on: May 18, 2012
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include <boost/archive/text_iarchive.hpp>
36// boost asio needs specific operator new
37#include <boost/asio.hpp>
38
39#include "CodePatterns/MemDebug.hpp"
40
41#include <boost/mpl/remove.hpp>
42
43#include "CodePatterns/Assert.hpp"
44#include "CodePatterns/Info.hpp"
45#include "CodePatterns/Log.hpp"
46#include "JobMarket/Controller/FragmentController.hpp"
47#include "JobMarket/Jobs/FragmentJob.hpp"
48
49#include "Atom/atom.hpp"
50#include "Box.hpp"
51#include "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/AllLevelOrthogonalSummator.hpp"
60#include "Fragmentation/Summation/AllLevelSummator.hpp"
61#include "Fragmentation/Summation/writeTable.hpp"
62#include "Graph/DepthFirstSearchAnalysis.hpp"
63#include "Helpers/defs.hpp"
64#include "Jobs/MPQCJob.hpp"
65#include "Jobs/MPQCData.hpp"
66#include "Jobs/MPQCData_printKeyNames.hpp"
67#include "LinearAlgebra/RealSpaceMatrix.hpp"
68#ifdef HAVE_VMG
69#include "Jobs/VMGJob.hpp"
70#endif
71#include "molecule.hpp"
72#include "World.hpp"
73
74#include <iostream>
75#include <string>
76#include <vector>
77
78#include <boost/mpl/for_each.hpp>
79
80#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
81
82using namespace MoleCuilder;
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
189/** Print MPQCData from received results.
190 *
191 * @param results results with ids to associate with fragment number
192 * @param fragmentData MPQCData resulting from the jobs
193 * @param KeySetFilename filename with keysets to associate forces correctly
194 * @param NoAtoms total number of atoms
195 */
196bool printReceivedMPQCResults(
197 const std::vector<FragmentResult::ptr> &results,
198 const std::vector<MPQCData> &fragmentData,
199 const std::string &KeySetFilename,
200 size_t NoAtoms)
201{
202 EnergyMatrix Energy;
203 EnergyMatrix EnergyFragments;
204 ForceMatrix Force;
205 ForceMatrix ForceFragments;
206
207 // align fragments
208 std::map< JobId_t, size_t > MatrixNrLookup;
209 size_t FragmentCounter = 0;
210 {
211 // bring ids in order ...
212 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
213 IdResultMap_t IdResultMap;
214 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
215 iter != results.end(); ++iter) {
216 #ifndef NDEBUG
217 std::pair< IdResultMap_t::iterator, bool> inserter =
218 #endif
219 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
220 ASSERT( inserter.second,
221 "ExtractMPQCDataFromResults() - two results have same id "
222 +toString((*iter)->getId())+".");
223 }
224 // ... and fill lookup
225 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
226 iter != IdResultMap.end(); ++iter)
227 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
228 }
229 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
230
231 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
232 std::vector<FragmentResult::ptr>::const_iterator resultiter = results.begin();
233 for (; dataiter != fragmentData.end(); ++dataiter, ++resultiter) {
234 const MPQCData &extractedData = *dataiter;
235 // place results into EnergyMatrix ...
236 {
237 MatrixContainer::MatrixArray matrix;
238 matrix.resize(1);
239 matrix[0].resize(1, extractedData.energies.total);
240 if (!Energy.AddMatrix(
241 std::string("MPQCJob ")+toString((*resultiter)->getId()),
242 matrix,
243 MatrixNrLookup[(*resultiter)->getId()])) {
244 ELOG(1, "Adding energy matrix failed.");
245 return false;
246 }
247 }
248 // ... and ForceMatrix (with two empty columns in front)
249 {
250 MatrixContainer::MatrixArray matrix;
251 const size_t rows = extractedData.forces.size();
252 matrix.resize(rows);
253 for (size_t i=0;i<rows;++i) {
254 const size_t columns = 2+extractedData.forces[i].size();
255 matrix[i].resize(columns, 0.);
256 // for (size_t j=0;j<2;++j)
257 // matrix[i][j] = 0.;
258 for (size_t j=2;j<columns;++j)
259 matrix[i][j] = extractedData.forces[i][j-2];
260 }
261 if (!Force.AddMatrix(
262 std::string("MPQCJob ")+toString((*resultiter)->getId()),
263 matrix,
264 MatrixNrLookup[(*resultiter)->getId()])) {
265 ELOG(1, "Adding force matrix failed.");
266 return false;
267 }
268 }
269 }
270 // add one more matrix (not required for energy)
271 MatrixContainer::MatrixArray matrix;
272 matrix.resize(1);
273 matrix[0].resize(1, 0.);
274 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
275 return false;
276 // but for energy because we need to know total number of atoms
277 matrix.resize(NoAtoms);
278 for (size_t i = 0; i< NoAtoms; ++i)
279 matrix[i].resize(2+NDIM, 0.);
280 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
281 return false;
282
283 // initialise indices
284 KeySetsContainer KeySet;
285 KeySetsContainer ForceKeySet;
286 if (!Energy.InitialiseIndices()) return false;
287
288 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
289
290 {
291 std::stringstream filename;
292 filename << FRAGMENTPREFIX << KEYSETFILE;
293 if (!KeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
294 }
295
296 {
297 std::stringstream filename;
298 filename << FRAGMENTPREFIX << FORCESFILE;
299 if (!ForceKeySet.ParseKeySets(KeySetFilename, filename.str(), FragmentCounter)) return false;
300 }
301
302 /// prepare for OrthogonalSummation
303
304 // convert KeySetContainer to IndexSetContainer
305 IndexSetContainer::ptr container(new IndexSetContainer(KeySet));
306 // create the map of all keysets
307 SubsetMap::ptr subsetmap(new SubsetMap(*container));
308
309// we probably don't need this, it suffices if IndexedVectors has some extra indices
310// // forces need different keysets: they must include hydrogen
311// // (though without ones added by saturation)
312// IndexSetContainer::ptr forceindices(new IndexSetContainer(ForceKeySet));
313// // create the map of all keysets
314// SubsetMap::ptr subsetmapforces(new SubsetMap(*forceindices));
315
316 /// convert all MPQCData to MPQCDataMap_t
317 {
318 // energy_t
319 std::vector<MPQCDataEnergyMap_t> MPQCData_Energy_fused;
320 MPQCData_Energy_fused.reserve(fragmentData.size());
321 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
322 dataiter != fragmentData.end(); ++dataiter) {
323 const MPQCData &extractedData = *dataiter;
324 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
325 MPQCDataEnergyMap_t instance;
326 boost::fusion::at_key<MPQCDataFused::energy_total>(instance) = extractedData.energies.total;
327 boost::fusion::at_key<MPQCDataFused::energy_nuclear_repulsion>(instance) = extractedData.energies.nuclear_repulsion;
328 boost::fusion::at_key<MPQCDataFused::energy_electron_coulomb>(instance) = extractedData.energies.electron_coulomb;
329 boost::fusion::at_key<MPQCDataFused::energy_electron_exchange>(instance) = extractedData.energies.electron_exchange;
330 boost::fusion::at_key<MPQCDataFused::energy_correlation>(instance) = extractedData.energies.correlation;
331 boost::fusion::at_key<MPQCDataFused::energy_overlap>(instance) = extractedData.energies.overlap;
332 boost::fusion::at_key<MPQCDataFused::energy_kinetic>(instance) = extractedData.energies.kinetic;
333 boost::fusion::at_key<MPQCDataFused::energy_hcore>(instance) = extractedData.energies.hcore;
334 boost::fusion::at_key<MPQCDataFused::energy_eigenvalues>(instance) = extractedData.energies.eigenvalues;
335 MPQCData_Energy_fused.push_back(instance);
336 }
337
338 // forces
339 ASSERT( ForceKeySet.KeySets.size() == fragmentData.size(),
340 "FragmentationAutomationAction::performCall() - ForceKeySet's KeySets 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 KeySetsContainer::ArrayOfIntVectors::const_iterator arrayiter = ForceKeySet.KeySets.begin();
345 for(;dataiter != fragmentData.end(); ++dataiter, ++arrayiter) {
346 const MPQCData &extractedData = *dataiter;
347 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
348 MPQCDataForceMap_t instance;
349 // must convert int to index_t
350 IndexedVectors::indices_t indices(arrayiter->begin(), arrayiter->end());
351 boost::fusion::at_key<MPQCDataFused::forces>(instance) =
352 IndexedVectors(indices, extractedData.forces);
353 MPQCData_Force_fused.push_back(instance);
354 }
355
356 // sampled_grid
357 std::vector<MPQCDataGridMap_t> MPQCData_Grid_fused;
358 MPQCData_Grid_fused.reserve(fragmentData.size());
359 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
360 dataiter != fragmentData.end(); ++dataiter) {
361 const MPQCData &extractedData = *dataiter;
362 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
363 MPQCDataGridMap_t instance;
364 boost::fusion::at_key<MPQCDataFused::sampled_grid>(instance) = extractedData.sampled_grid;
365 MPQCData_Grid_fused.push_back(instance);
366 }
367
368 // times
369 std::vector<MPQCDataTimeMap_t> MPQCData_Time_fused;
370 MPQCData_Time_fused.reserve(fragmentData.size());
371 for(std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
372 dataiter != fragmentData.end(); ++dataiter) {
373 const MPQCData &extractedData = *dataiter;
374 LOG(2, "DEBUG: Current extracted Data is " << extractedData << ".");
375 MPQCDataTimeMap_t instance;
376 boost::fusion::at_key<MPQCDataFused::times_walltime>(instance) = extractedData.times.walltime;
377 boost::fusion::at_key<MPQCDataFused::times_cputime>(instance) = extractedData.times.cputime;
378 boost::fusion::at_key<MPQCDataFused::times_flops>(instance) = extractedData.times.flops;
379 MPQCData_Time_fused.push_back(instance);
380 }
381
382 // create a vector of all job ids
383 std::vector<JobId_t> jobids(results.size(), JobId::IllegalJob);
384 std::transform(results.begin(), results.end(), jobids.begin(),
385 boost::bind(&FragmentResult::getId,
386 boost::bind(&FragmentResult::ptr::operator->, _1)));
387
388 // create summation instances
389 std::vector<MPQCDataEnergyMap_t> Result_Energy_fused(subsetmap->getMaximumSubsetLevel());
390 AllLevelOrthogonalSummator<MPQCDataEnergyMap_t> energySummer(
391 subsetmap,
392 MPQCData_Energy_fused,
393 jobids,
394 container->getContainer(),
395 MatrixNrLookup,
396 Result_Energy_fused);
397 std::vector<MPQCDataForceMap_t> Result_Force_fused(subsetmap->getMaximumSubsetLevel());
398 AllLevelOrthogonalSummator<MPQCDataForceMap_t> forceSummer(
399 subsetmap,
400 MPQCData_Force_fused,
401 jobids,
402 container->getContainer(),
403 MatrixNrLookup,
404 Result_Force_fused);
405 std::vector<MPQCDataGridMap_t> Result_Grid_fused(subsetmap->getMaximumSubsetLevel());
406 AllLevelOrthogonalSummator<MPQCDataGridMap_t> gridSummer(
407 subsetmap,
408 MPQCData_Grid_fused,
409 jobids,
410 container->getContainer(),
411 MatrixNrLookup,
412 Result_Grid_fused);
413 std::vector<MPQCDataTimeMap_t> Result_Time_fused(subsetmap->getMaximumSubsetLevel());
414 AllLevelSummator<MPQCDataTimeMap_t> timeSummer(
415 subsetmap,
416 MPQCData_Time_fused,
417 jobids,
418 container->getContainer(),
419 MatrixNrLookup,
420 Result_Time_fused);
421
422 // sum up
423 boost::mpl::for_each<MPQCDataEnergyVector_t>(boost::ref(energySummer));
424 boost::mpl::for_each<MPQCDataForceVector_t>(boost::ref(forceSummer));
425 boost::mpl::for_each<MPQCDataGridVector_t>(boost::ref(gridSummer));
426 boost::mpl::for_each<MPQCDataTimeVector_t>(boost::ref(timeSummer));
427
428 // print tables (without eigenvalues, they go extra)
429 const size_t MaxLevel = subsetmap->getMaximumSubsetLevel();
430 typedef boost::mpl::remove<MPQCDataEnergyVector_t, MPQCDataFused::energy_eigenvalues>::type MPQCDataEnergyVector_noeigenvalues_t;
431 const std::string energyresult =
432 writeTable<MPQCDataEnergyMap_t, MPQCDataEnergyVector_noeigenvalues_t >()(
433 Result_Energy_fused, MaxLevel);
434 LOG(0, "Energy table is \n" << energyresult);
435 const std::string eigenvalueresult;
436
437 LOG(0, "Eigenvalue table is \n" << eigenvalueresult);
438 const std::string forceresult =
439 writeTable<MPQCDataForceMap_t, MPQCDataForceVector_t>()(
440 Result_Force_fused, MaxLevel);
441 LOG(0, "Force table is \n" << forceresult);
442 // we don't want to print grid to a table
443 // print times (without flops for now)
444 typedef boost::mpl::remove<MPQCDataTimeVector_t, MPQCDataFused::times_flops>::type MPQCDataTimeVector_noflops_t;
445 const std::string timesresult =
446 writeTable<MPQCDataTimeMap_t, MPQCDataTimeVector_noflops_t >()(
447 Result_Time_fused, MaxLevel);
448 LOG(0, "Times table is \n" << timesresult);
449 }
450
451 // combine all found data
452 if (!KeySet.ParseManyBodyTerms()) return false;
453
454 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
455 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
456
457 if(!Energy.SetLastMatrix(0., 0)) return false;
458 if(!Force.SetLastMatrix(0., 2)) return false;
459
460 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
461 // --------- sum up energy --------------------
462 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
463 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
464 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
465
466 // --------- sum up Forces --------------------
467 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
468 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
469 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
470 }
471
472 // for debugging print resulting energy and forces
473 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
474 std::stringstream output;
475 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
476 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
477 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
478 output << "\n";
479 }
480 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
481
482 return true;
483}
484
485
486void RunService(
487 boost::asio::io_service &io_service,
488 std::string message)
489{
490 message = std::string("io_service: ") + message;
491 io_service.reset();
492 Info info(message.c_str());
493 io_service.run();
494}
495
496void requestIds(
497 FragmentController &controller,
498 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
499 const size_t numberjobs)
500{
501 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
502}
503
504bool createJobsFromFiles(
505 FragmentController &controller,
506 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
507 const std::vector< boost::filesystem::path > &jobfiles)
508{
509 std::vector<FragmentJob::ptr> jobs;
510 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
511 iter != jobfiles .end(); ++iter) {
512 const std::string &filename = (*iter).string();
513 if (boost::filesystem::exists(filename)) {
514 const JobId_t next_id = controller.getAvailableId();
515 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
516 +filename+"', and id "+toString(next_id)+".");
517 parsejob(jobs, params.executable.get().string(), filename, next_id);
518 } else {
519 ELOG(1, "Fragment job "+filename+" does not exist.");
520 return false;
521 }
522 }
523 controller.addJobs(jobs);
524 controller.sendJobs(params.host.get(), params.port.get());
525 return true;
526}
527
528#ifdef HAVE_VMG
529bool createLongRangeJobs(
530 FragmentController &controller,
531 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
532 const std::vector<MPQCData> &fragmentData)
533{
534 std::vector<FragmentJob::ptr> jobs;
535 // add one job for each fragment as the short-range correction which we need
536 // to subtract from the obtained full potential to get the long-range part only
537 for (std::vector<MPQCData>::const_iterator iter = fragmentData.begin();
538 iter != fragmentData.end(); ++iter) {
539 const JobId_t next_id = controller.getAvailableId();
540 LOG(1, "INFO: Creating VMGJob with " << iter->sampled_grid.sampled_grid.size()
541 << " gridpoints and " << iter->charges.size() << " particle charges.");
542 FragmentJob::ptr testJob(
543 new VMGJob(next_id, iter->sampled_grid, iter->positions, iter->charges) );
544 jobs.push_back(testJob);
545 }
546
547 // add one more job for the full calculation
548 // TODO: Here, we actually have to combine all the other sampled_grids
549 {
550 const int level = LEVEL;
551 const int GRID = pow(2, level);
552 std::vector<double> full_sample(GRID*GRID*GRID, 0.);
553 double begin[NDIM] = { 0., 0., 0. };
554 const RealSpaceMatrix& M = World::getInstance().getDomain().getM();
555 const double size = M.at(0,0);
556 ASSERT( M.determinant() == size*size*size,
557 "createLongRangeJobs() - current domain matrix "+toString(M)+" is not cubic.");
558 const SamplingGrid full_sampled_grid(begin, size, level, full_sample);
559 const std::vector< std::vector<double> > positions;
560 const std::vector<double> charges;
561 const JobId_t next_id = controller.getAvailableId();
562 LOG(1, "INFO: Creating full VMGJob with " << full_sample.size()
563 << " gridpoints and " << charges.size() << " particle charges.");
564 FragmentJob::ptr testJob(
565 new VMGJob(next_id, full_sampled_grid, positions, charges) );
566 jobs.push_back(testJob);
567 }
568
569 // then send jobs to controller
570 controller.addJobs(jobs);
571 controller.sendJobs(params.host.get(), params.port.get());
572 return true;
573}
574#endif
575
576void WaitforResults(
577 boost::asio::io_service &io_service,
578 FragmentController &controller,
579 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
580 const size_t NoExpectedResults
581 )
582{
583 size_t NoCalculatedResults = 0;
584 while (NoCalculatedResults != NoExpectedResults) {
585 // wait a bit
586 boost::asio::deadline_timer timer(io_service);
587 timer.expires_from_now(boost::posix_time::milliseconds(500));
588 timer.wait();
589 // then request status
590 controller.checkResults(params.host.get(), params.port.get());
591 RunService(io_service, "Checking on results");
592
593 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
594 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
595 NoCalculatedResults = JobStatus.second;
596 }
597}
598
599
600Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
601 boost::asio::io_service io_service;
602 FragmentController controller(io_service);
603
604 // TODO: Have io_service run in second thread and merge with current again eventually
605
606 // Phase One: obtain ids
607 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
608 requestIds(controller, params, jobfiles.size());
609 RunService(io_service, "Requesting ids");
610
611 // Phase Two: create and add MPQCJobs
612 if (!createJobsFromFiles(controller, params, jobfiles))
613 return Action::failure;
614 RunService(io_service, "Adding MPQCJobs");
615
616 // Phase Three: calculate result
617 WaitforResults(io_service, controller, params, jobfiles.size());
618 controller.receiveResults(params.host.get(), params.port.get());
619 RunService(io_service, "Requesting short-range results");
620 std::vector<FragmentResult::ptr> MPQCresults = controller.getReceivedResults();
621 std::vector<MPQCData> fragmentData;
622 ConvertFragmentResultToMPQCData(MPQCresults, fragmentData);
623
624 // print intermediate short-range results
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#ifdef HAVE_VMG
635 if (params.DoLongrange.get()) {
636 // Phase Four: obtain more ids
637 requestIds(controller, params, fragmentData.size()+1);
638 RunService(io_service, "Requesting ids");
639
640 // Phase Five: create VMGJobs
641 if (!createLongRangeJobs(controller, params, fragmentData))
642 return Action::failure;
643 RunService(io_service, "Adding VMGJobs");
644
645 // Phase Six: calculate result
646 WaitforResults(io_service, controller, params, fragmentData.size()+1);
647 controller.receiveResults(params.host.get(), params.port.get());
648 RunService(io_service, "Requesting long-range results");
649 std::vector<FragmentResult::ptr> VMGresults = controller.getReceivedResults();
650 ASSERT( MPQCresults.size()+1 == VMGresults.size(),
651 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresultd and VMGresults don't match.");
652
653 // Final phase: print result
654 {
655 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
656 printReceivedMPQCResults(
657 MPQCresults,
658 fragmentData,
659 params.path.get(),
660 getNoAtomsFromAdjacencyFile(params.path.get()));
661 }
662 }
663#endif
664 size_t Exitflag = controller.getExitflag();
665
666 return (Exitflag == 0) ? Action::success : Action::failure;
667}
668
669Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
670 return Action::success;
671}
672
673Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
674 return Action::success;
675}
676
677bool FragmentationFragmentationAutomationAction::canUndo() {
678 return false;
679}
680
681bool FragmentationFragmentationAutomationAction::shouldUndo() {
682 return false;
683}
684/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.