source: src/controller_MPQCCommandJob.cpp@ fd4d5e

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 Candidate_v1.7.0 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 fd4d5e was 014bc4, checked in by Frederik Heber <heber@…>, 13 years ago

Introduced interface controller_AddOn.hpp that encapsulates controller extending functions in struct controller_AddOn.

  • allocating function for derived structure controller_AddOn is contained in extra module to allow indepent linking, i.e. combine controller.cpp, controller_AddOn_SystemCommandJob.cpp and controller_SystemCommandJon.cpp or with controller_AddOn_MPQCCommandJob.cpp and controller_MPQCCommandJon.cpp.
  • Property mode set to 100644
File size: 13.9 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: 01.06.2012
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20// boost asio needs specific operator new
21#include <boost/asio.hpp>
22
23#include "CodePatterns/MemDebug.hpp"
24
25#include "controller_MPQCCommandJob.hpp"
26
27#include <boost/assign.hpp>
28#include <boost/bind.hpp>
29#include <fstream>
30
31#include "FragmentController.hpp"
32#include "Jobs/MPQCCommandJob.hpp"
33#include "Results/FragmentResult.hpp"
34
35#include "ControllerCommand.hpp"
36#include "ControllerCommandRegistry.hpp"
37#include "ControllerOptions_MPQCCommandJob.hpp"
38
39#include "Fragmentation/EnergyMatrix.hpp"
40#include "Fragmentation/ForceMatrix.hpp"
41#include "Fragmentation/KeySetsContainer.hpp"
42#include "Fragmentation/defs.hpp"
43
44#include "Helpers/defs.hpp"
45
46#include "Jobs/MPQCCommandJob.hpp"
47#include "Jobs/MPQCCommandJob_MPQCData.hpp"
48
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
261/** Creates a SystemCommandJob out of give \a command with \a argument.
262 *
263 * @param controller reference to controller to add jobs
264 * @param ControllerInfo information on the job
265 */
266void createJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
267{
268 const JobId_t next_id = controller.getAvailableId();
269 LOG(2, "DEBUG: Creating new SystemCommandJob with '"
270 +toString(ControllerInfo.executable)+"' and argument '"
271 +toString(ControllerInfo.jobcommand)+"'.");
272 FragmentJob::ptr testJob(
273 new SystemCommandJob(ControllerInfo.executable, ControllerInfo.jobcommand, next_id) );
274 std::vector<FragmentJob::ptr> jobs;
275 jobs.push_back(testJob);
276 controller.addJobs(jobs);
277 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
278 LOG(1, "INFO: Added one SystemCommandJob.");
279}
280
281/** Creates a MPQCCommandJob out of give \a command with \a argument.
282 *
283 * @param controller reference to controller to add jobs
284 * @param ControllerInfo information on the job
285 */
286void AddJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
287{
288 std::vector<FragmentJob::ptr> jobs;
289 for (std::vector< std::string >::const_iterator iter = ControllerInfo.jobfiles.begin();
290 iter != ControllerInfo.jobfiles.end(); ++iter) {
291 const JobId_t next_id = controller.getAvailableId();
292 const std::string &filename = *iter;
293 LOG(1, "INFO: Creating MPQCCommandJob with filename '"
294 +filename+"', and id "+toString(next_id)+".");
295 parsejob(jobs, ControllerInfo.executable, filename, next_id);
296 }
297 controller.addJobs(jobs);
298 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
299}
300
301inline std::vector<std::string> getListOfCommands(const ControllerCommandRegistry &ControllerCommands)
302{
303 std::vector<std::string> Commands;
304 for (ControllerCommandRegistry::const_iterator iter = ControllerCommands.getBeginIter();
305 iter != ControllerCommands.getEndIter(); ++iter)
306 Commands.push_back(iter->first);
307
308 return Commands;
309}
310
311ControllerOptions *controller_MPQCCommandJob::allocateControllerInfo()
312{
313 return new ControllerOptions_MPQCCommandJob();
314}
315
316void controller_MPQCCommandJob::addSpecificCommands(
317 boost::function<void (ControllerCommand *)> &registrator,
318 FragmentController &controller,
319 ControllerOptions &ControllerInfo)
320{
321 ControllerOptions_MPQCCommandJob &CI =
322 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
323 registrator(new ControllerCommand("addjobs",
324 boost::assign::list_of< ControllerCommand::commands_t >
325 (boost::bind(&FragmentController::requestIds,
326 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport),
327 boost::bind(&std::vector<std::string>::size, boost::cref(CI.jobfiles))))
328 (boost::bind(&AddJobs, boost::ref(controller), boost::cref(CI)))
329 ));
330 registrator(new ControllerCommand("createjobs",
331 boost::assign::list_of< ControllerCommand::commands_t >
332 (boost::bind(&FragmentController::requestIds,
333 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport), 1))
334 (boost::bind(&createJobs, boost::ref(controller), boost::cref(CI)))
335 ));
336 registrator(new ControllerCommand("receiveresults",
337 boost::assign::list_of< ControllerCommand::commands_t >
338 (boost::bind(&FragmentController::receiveResults,
339 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
340 (boost::bind(&printReceivedResults,
341 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller))))
342 ));
343 registrator(new ControllerCommand("receivempqc",
344 boost::assign::list_of< ControllerCommand::commands_t >
345 (boost::bind(&FragmentController::receiveResults,
346 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
347 (boost::bind(&printReceivedMPQCResults,
348 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller)),
349 boost::cref(CI.fragmentpath),
350 boost::bind(&getNoAtomsFromAdjacencyFile, boost::cref(CI.fragmentpath))))
351 ));
352}
353
354void controller_MPQCCommandJob::addSpecificOptions(
355 boost::program_options::options_description_easy_init option)
356{
357 option
358 ("jobcommand", boost::program_options::value< std::string >(), "command argument for executable for 'createjobs'")
359 ("executable", boost::program_options::value< std::string >(), "executable for commands 'createjobs'")
360 ("fragment-path", boost::program_options::value< std::string >(), "path to fragment files for 'receivempqc'")
361 ("jobfiles", boost::program_options::value< std::vector< std::string > >()->multitoken(), "list of files as single argument toexecutable for 'addjobs'")
362 ;
363}
364
365int controller_MPQCCommandJob::addOtherParsings(
366 ControllerOptions &ControllerInfo,
367 boost::program_options::variables_map &vm)
368{
369 ControllerOptions_MPQCCommandJob &CI =
370 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
371 int status = 0;
372 status = CI.parseExecutable(vm);
373 if (status) return status;
374 status = CI.parseJobCommand(vm);
375 if (status) return status;
376 status = CI.parseFragmentpath(vm);
377 if (status) return status;
378 status = CI.parseJobfiles(vm);
379 return status;
380}
Note: See TracBrowser for help on using the repository browser.