source: src/controller_MPQCCommandJob.cpp@ cbcbbd

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

Split off SystemCommandJob-specific stuff in controller into module controller_SystemCommandJob and controller_MPQCCommandJob

  • this is preparatory for introducing a generic interface.
  • Property mode set to 100644
File size: 13.4 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * controller_MPQCCommandJob.cpp
10 *
11 * Created on: Jun 6, 2012
12 * Author: heber
13 */
14
15
16// include config.h
17#ifdef HAVE_CONFIG_H
18#include <config.h>
19#endif
20
21// boost asio needs specific operator new
22#include <boost/asio.hpp>
23
24#include "CodePatterns/MemDebug.hpp"
25
26#include "controller_MPQCCommandJob.hpp"
27
28#include <boost/assign.hpp>
29#include <boost/bind.hpp>
30#include <fstream>
31
32#include "FragmentController.hpp"
33#include "Jobs/SystemCommandJob.hpp"
34#include "Results/FragmentResult.hpp"
35
36#include "ControllerCommand.hpp"
37#include "ControllerCommandRegistry.hpp"
38#include "ControllerOptions_MPQCCommandJob.hpp"
39
40#include "Fragmentation/EnergyMatrix.hpp"
41#include "Fragmentation/ForceMatrix.hpp"
42#include "Fragmentation/KeySetsContainer.hpp"
43#include "Fragmentation/defs.hpp"
44
45#include "Helpers/defs.hpp"
46
47#include "Jobs/MPQCCommandJob.hpp"
48#include "Jobs/MPQCCommandJob_MPQCData.hpp"
49
50/** Creates a MPQCCommandJob with argument \a filename.
51 *
52 * @param jobs created job is added to this vector
53 * @param command mpqc command to execute
54 * @param filename filename being argument to job
55 * @param nextid id for this job
56 */
57void parsejob(
58 std::vector<FragmentJob::ptr> &jobs,
59 const std::string &command,
60 const std::string &filename,
61 const JobId_t nextid)
62{
63 std::ifstream file;
64 file.open(filename.c_str());
65 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
66 std::string output((std::istreambuf_iterator<char>(file)),
67 std::istreambuf_iterator<char>());
68 FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid, command) );
69 jobs.push_back(testJob);
70 file.close();
71 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
72}
73
74/** Print received results.
75 *
76 * @param results received results to print
77 */
78void printReceivedResults(const std::vector<FragmentResult::ptr> &results)
79{
80 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
81 iter != results.end(); ++iter)
82 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
83}
84
85/** Print MPQCData from received results.
86 *
87 * @param results received results to extract MPQCData from
88 * @param KeySetFilename filename with keysets to associate forces correctly
89 * @param NoAtoms total number of atoms
90 */
91bool printReceivedMPQCResults(
92 const std::vector<FragmentResult::ptr> &results,
93 const std::string &KeySetFilename,
94 size_t NoAtoms)
95{
96 EnergyMatrix Energy;
97 EnergyMatrix EnergyFragments;
98 ForceMatrix Force;
99 ForceMatrix ForceFragments;
100 KeySetsContainer KeySet;
101
102 // align fragments
103 std::map< JobId_t, size_t > MatrixNrLookup;
104 size_t FragmentCounter = 0;
105 {
106 // bring ids in order ...
107 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
108 IdResultMap_t IdResultMap;
109 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
110 iter != results.end(); ++iter) {
111 #ifndef NDEBUG
112 std::pair< IdResultMap_t::iterator, bool> inserter =
113 #endif
114 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
115 ASSERT( inserter.second,
116 "printReceivedMPQCResults() - two results have same id "
117 +toString((*iter)->getId())+".");
118 }
119 // ... and fill lookup
120 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
121 iter != IdResultMap.end(); ++iter)
122 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
123 }
124 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
125
126 // extract results
127 std::vector<MPQCData> fragmentData(results.size());
128 MPQCData combinedData;
129
130 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
131 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
132 iter != results.end(); ++iter) {
133 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
134 MPQCData extractedData;
135 std::stringstream inputstream((*iter)->result);
136 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
137 boost::archive::text_iarchive ia(inputstream);
138 ia >> extractedData;
139 LOG(1, "INFO: extracted data is " << extractedData << ".");
140
141 // place results into EnergyMatrix ...
142 {
143 MatrixContainer::MatrixArray matrix;
144 matrix.resize(1);
145 matrix[0].resize(1, extractedData.energy);
146 if (!Energy.AddMatrix(
147 std::string("MPQCJob ")+toString((*iter)->getId()),
148 matrix,
149 MatrixNrLookup[(*iter)->getId()])) {
150 ELOG(1, "Adding energy matrix failed.");
151 return false;
152 }
153 }
154 // ... and ForceMatrix (with two empty columns in front)
155 {
156 MatrixContainer::MatrixArray matrix;
157 const size_t rows = extractedData.forces.size();
158 matrix.resize(rows);
159 for (size_t i=0;i<rows;++i) {
160 const size_t columns = 2+extractedData.forces[i].size();
161 matrix[i].resize(columns, 0.);
162 // for (size_t j=0;j<2;++j)
163 // matrix[i][j] = 0.;
164 for (size_t j=2;j<columns;++j)
165 matrix[i][j] = extractedData.forces[i][j-2];
166 }
167 if (!Force.AddMatrix(
168 std::string("MPQCJob ")+toString((*iter)->getId()),
169 matrix,
170 MatrixNrLookup[(*iter)->getId()])) {
171 ELOG(1, "Adding force matrix failed.");
172 return false;
173 }
174 }
175 }
176 // add one more matrix (not required for energy)
177 MatrixContainer::MatrixArray matrix;
178 matrix.resize(1);
179 matrix[0].resize(1, 0.);
180 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
181 return false;
182 // but for energy because we need to know total number of atoms
183 matrix.resize(NoAtoms);
184 for (size_t i = 0; i< NoAtoms; ++i)
185 matrix[i].resize(2+NDIM, 0.);
186 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
187 return false;
188
189
190 // combine all found data
191 if (!Energy.InitialiseIndices()) return false;
192
193 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
194
195 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
196
197 if (!KeySet.ParseManyBodyTerms()) return false;
198
199 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
200 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
201
202 if(!Energy.SetLastMatrix(0., 0)) return false;
203 if(!Force.SetLastMatrix(0., 2)) return false;
204
205 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
206 // --------- sum up energy --------------------
207 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
208 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
209 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
210
211 // --------- sum up Forces --------------------
212 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
213 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
214 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
215 }
216
217 // for debugging print resulting energy and forces
218 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
219 std::stringstream output;
220 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
221 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
222 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
223 output << "\n";
224 }
225 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
226
227 return true;
228}
229
230
231/** Helper function to get number of atoms somehow.
232 *
233 * Here, we just parse the number of lines in the adjacency file as
234 * it should correspond to the number of atoms, except when some atoms
235 * are not bonded, but then fragmentation makes no sense.
236 *
237 * @param path path to the adjacency file
238 */
239size_t getNoAtomsFromAdjacencyFile(const std::string &path)
240{
241 size_t NoAtoms = 0;
242
243 // parse in special file to get atom count (from line count)
244 std::string filename(path);
245 filename += FRAGMENTPREFIX;
246 filename += ADJACENCYFILE;
247 std::ifstream adjacency(filename.c_str());
248 if (adjacency.fail()) {
249 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
250 return false;
251 }
252 std::string buffer;
253 while (getline(adjacency, buffer))
254 NoAtoms++;
255 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
256
257 return NoAtoms;
258}
259
260/** Creates a SystemCommandJob out of give \a command with \a argument.
261 *
262 * @param controller reference to controller to add jobs
263 * @param ControllerInfo information on the job
264 */
265void createJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
266{
267 const JobId_t next_id = controller.getAvailableId();
268 FragmentJob::ptr testJob(
269 new SystemCommandJob(ControllerInfo.executable, ControllerInfo.jobcommand, next_id) );
270 std::vector<FragmentJob::ptr> jobs;
271 jobs.push_back(testJob);
272 controller.addJobs(jobs);
273 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
274 LOG(1, "INFO: Added one SystemCommandJob.");
275}
276
277/** Creates a MPQCCommandJob out of give \a command with \a argument.
278 *
279 * @param controller reference to controller to add jobs
280 * @param ControllerInfo information on the job
281 */
282void AddJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
283{
284 std::vector<FragmentJob::ptr> jobs;
285 for (std::vector< std::string >::const_iterator iter = ControllerInfo.jobfiles.begin();
286 iter != ControllerInfo.jobfiles.end(); ++iter) {
287 const JobId_t next_id = controller.getAvailableId();
288 const std::string &filename = *iter;
289 LOG(1, "INFO: Creating MPQCCommandJob with filename '"
290 +filename+"', and id "+toString(next_id)+".");
291 parsejob(jobs, ControllerInfo.executable, filename, next_id);
292 }
293 controller.addJobs(jobs);
294 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
295}
296
297ControllerOptions *allocateControllerInfo()
298{
299 return new ControllerOptions_MPQCCommandJob();
300}
301
302void addSpecificCommands(
303 boost::function<void (ControllerCommand *)> &registrator,
304 FragmentController &controller,
305 ControllerOptions &ControllerInfo,
306 boost::program_options::variables_map &vm)
307{
308 ControllerOptions_MPQCCommandJob &CI =
309 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
310 registrator(new ControllerCommand("addjobs",
311 boost::assign::list_of< ControllerCommand::commands_t >
312 (boost::bind(&FragmentController::requestIds,
313 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport),
314 boost::bind(&std::vector<std::string>::size, boost::cref(CI.jobfiles))))
315 (boost::bind(&AddJobs, boost::ref(controller), boost::cref(CI)))
316 ));
317 registrator(new ControllerCommand("createjobs",
318 boost::assign::list_of< ControllerCommand::commands_t >
319 (boost::bind(&FragmentController::requestIds,
320 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport), 1))
321 (boost::bind(&createJobs, boost::ref(controller), boost::cref(CI)))
322 ));
323 registrator(new ControllerCommand("receivempqc",
324 boost::assign::list_of< ControllerCommand::commands_t >
325 (boost::bind(&FragmentController::receiveResults,
326 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
327 (boost::bind(&printReceivedMPQCResults,
328 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller)),
329 boost::cref(CI.fragmentpath),
330 boost::bind(&getNoAtomsFromAdjacencyFile, boost::cref(CI.fragmentpath))))
331 ));
332 registrator(new ControllerCommand("receiveresults",
333 boost::assign::list_of< ControllerCommand::commands_t >
334 (boost::bind(&FragmentController::receiveResults,
335 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
336 (boost::bind(&printReceivedResults,
337 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller))))
338 ));
339}
340
341void addSpecificOptions(
342 boost::program_options::options_description_easy_init option)
343{
344 option
345 ("executable", boost::program_options::value< std::string >(), "executable for commands 'addjobs' and 'createjobs'")
346 ("jobcommand", boost::program_options::value< std::string >(), "command argument for executable for 'createjobs'")
347 ("fragment-path", boost::program_options::value< std::string >(), "path to fragment files for 'receivempqc'")
348 ("jobfiles", boost::program_options::value< std::vector< std::string > >()->multitoken(), "list of files as single argument to executable for 'addjobs'")
349 ;
350}
351
352int addOtherParsings(
353 ControllerOptions &ControllerInfo,
354 boost::program_options::variables_map &vm,
355 const ControllerCommandRegistry &ControllerCommands)
356{
357 ControllerOptions_MPQCCommandJob &CI =
358 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
359
360 int status = 0;
361 status = CI.parseExecutable(vm);
362 if (status) return status;
363 status = CI.parseJobCommand(vm);
364 if (status) return status;
365 status = CI.parseFragmentpath(vm);
366 if (status) return status;
367 status = CI.parseJobfiles(vm);
368 return status;
369}
Note: See TracBrowser for help on using the repository browser.