source: src/controller.cpp@ 5fa1f0

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

Outsourced DefaultOptions, ControllerOptions, ControllerOptions_SystemCommandJob, and ControllerOptions_MPQCCommandJob, into own modules.

  • Property mode set to 100644
File size: 17.5 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2011 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * \file controller.cpp
10 *
11 * This file strongly follows the Serialization example from the boost::asio
12 * library (see client.cpp)
13 *
14 * Created on: Nov 27, 2011
15 * Author: heber
16 */
17
18
19// include config.h
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24// boost asio needs specific operator new
25#include <boost/asio.hpp>
26
27#include "CodePatterns/MemDebug.hpp"
28
29#include <boost/assign.hpp>
30#include <boost/program_options.hpp>
31#include <deque>
32#include <fstream>
33#include <iostream>
34#include <map>
35#include <sstream>
36#include <streambuf>
37#include <vector>
38
39#include "Fragmentation/Automation/atexit.hpp"
40#include "CodePatterns/Info.hpp"
41#include "CodePatterns/Log.hpp"
42#include "Fragmentation/EnergyMatrix.hpp"
43#include "Fragmentation/ForceMatrix.hpp"
44#include "Fragmentation/KeySetsContainer.hpp"
45#include "FragmentController.hpp"
46#include "Helpers/defs.hpp"
47#include "Jobs/MPQCCommandJob.hpp"
48#include "Jobs/MPQCCommandJob_MPQCData.hpp"
49#include "Fragmentation/Automation/Jobs/SystemCommandJob.hpp"
50#include "Fragmentation/Automation/Results/FragmentResult.hpp"
51#include "ControllerOptions_MPQCCommandJob.hpp"
52
53/** Print the status of scheduled and done jobs.
54 *
55 * @param status pair of number of schedule and done jobs
56 */
57void printJobStatus(const std::pair<size_t, size_t> &JobStatus)
58{
59 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #"
60 << JobStatus.second << " jobs are calculated so far.");
61}
62
63/** Creates a SystemCommandJob out of give \a command with \a argument.
64 *
65 * @param jobs created job is added to this vector
66 * @param command command to execute for SystemCommandJob
67 * @param argument argument for command to execute
68 * @param nextid id for this job
69 */
70void createjobs(
71 std::vector<FragmentJob::ptr> &jobs,
72 const std::string &command,
73 const std::string &argument,
74 const JobId_t nextid)
75{
76 FragmentJob::ptr testJob( new SystemCommandJob(command, argument, nextid) );
77 jobs.push_back(testJob);
78 LOG(1, "INFO: Added one SystemCommandJob.");
79}
80
81/** Creates a MPQCCommandJob with argument \a filename.
82 *
83 * @param jobs created job is added to this vector
84 * @param command mpqc command to execute
85 * @param filename filename being argument to job
86 * @param nextid id for this job
87 */
88void parsejob(
89 std::vector<FragmentJob::ptr> &jobs,
90 const std::string &command,
91 const std::string &filename,
92 const JobId_t nextid)
93{
94 std::ifstream file;
95 file.open(filename.c_str());
96 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
97 std::string output((std::istreambuf_iterator<char>(file)),
98 std::istreambuf_iterator<char>());
99 FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid, command) );
100 jobs.push_back(testJob);
101 file.close();
102 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
103}
104
105/** Print received results.
106 *
107 * @param results received results to print
108 */
109void printReceivedResults(const std::vector<FragmentResult::ptr> &results)
110{
111 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
112 iter != results.end(); ++iter)
113 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
114}
115
116/** Print MPQCData from received results.
117 *
118 * @param results received results to extract MPQCData from
119 * @param KeySetFilename filename with keysets to associate forces correctly
120 * @param NoAtoms total number of atoms
121 */
122bool printReceivedMPQCResults(
123 const std::vector<FragmentResult::ptr> &results,
124 const std::string &KeySetFilename,
125 size_t NoAtoms)
126{
127 EnergyMatrix Energy;
128 EnergyMatrix EnergyFragments;
129 ForceMatrix Force;
130 ForceMatrix ForceFragments;
131 KeySetsContainer KeySet;
132
133 // align fragments
134 std::map< JobId_t, size_t > MatrixNrLookup;
135 size_t FragmentCounter = 0;
136 {
137 // bring ids in order ...
138 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
139 IdResultMap_t IdResultMap;
140 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
141 iter != results.end(); ++iter) {
142 #ifndef NDEBUG
143 std::pair< IdResultMap_t::iterator, bool> inserter =
144 #endif
145 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
146 ASSERT( inserter.second,
147 "printReceivedMPQCResults() - two results have same id "
148 +toString((*iter)->getId())+".");
149 }
150 // ... and fill lookup
151 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
152 iter != IdResultMap.end(); ++iter)
153 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
154 }
155 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
156
157 // extract results
158 std::vector<MPQCData> fragmentData(results.size());
159 MPQCData combinedData;
160
161 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
162 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
163 iter != results.end(); ++iter) {
164 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
165 MPQCData extractedData;
166 std::stringstream inputstream((*iter)->result);
167 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
168 boost::archive::text_iarchive ia(inputstream);
169 ia >> extractedData;
170 LOG(1, "INFO: extracted data is " << extractedData << ".");
171
172 // place results into EnergyMatrix ...
173 {
174 MatrixContainer::MatrixArray matrix;
175 matrix.resize(1);
176 matrix[0].resize(1, extractedData.energy);
177 if (!Energy.AddMatrix(
178 std::string("MPQCJob ")+toString((*iter)->getId()),
179 matrix,
180 MatrixNrLookup[(*iter)->getId()])) {
181 ELOG(1, "Adding energy matrix failed.");
182 return false;
183 }
184 }
185 // ... and ForceMatrix (with two empty columns in front)
186 {
187 MatrixContainer::MatrixArray matrix;
188 const size_t rows = extractedData.forces.size();
189 matrix.resize(rows);
190 for (size_t i=0;i<rows;++i) {
191 const size_t columns = 2+extractedData.forces[i].size();
192 matrix[i].resize(columns, 0.);
193 // for (size_t j=0;j<2;++j)
194 // matrix[i][j] = 0.;
195 for (size_t j=2;j<columns;++j)
196 matrix[i][j] = extractedData.forces[i][j-2];
197 }
198 if (!Force.AddMatrix(
199 std::string("MPQCJob ")+toString((*iter)->getId()),
200 matrix,
201 MatrixNrLookup[(*iter)->getId()])) {
202 ELOG(1, "Adding force matrix failed.");
203 return false;
204 }
205 }
206 }
207 // add one more matrix (not required for energy)
208 MatrixContainer::MatrixArray matrix;
209 matrix.resize(1);
210 matrix[0].resize(1, 0.);
211 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
212 return false;
213 // but for energy because we need to know total number of atoms
214 matrix.resize(NoAtoms);
215 for (size_t i = 0; i< NoAtoms; ++i)
216 matrix[i].resize(2+NDIM, 0.);
217 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
218 return false;
219
220
221 // combine all found data
222 if (!Energy.InitialiseIndices()) return false;
223
224 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
225
226 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
227
228 if (!KeySet.ParseManyBodyTerms()) return false;
229
230 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
231 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
232
233 if(!Energy.SetLastMatrix(0., 0)) return false;
234 if(!Force.SetLastMatrix(0., 2)) return false;
235
236 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
237 // --------- sum up energy --------------------
238 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
239 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
240 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
241
242 // --------- sum up Forces --------------------
243 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
244 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
245 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
246 }
247
248 // for debugging print resulting energy and forces
249 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
250 std::stringstream output;
251 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
252 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
253 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
254 output << "\n";
255 }
256 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
257
258 return true;
259}
260
261/** Helper function to get number of atoms somehow.
262 *
263 * Here, we just parse the number of lines in the adjacency file as
264 * it should correspond to the number of atoms, except when some atoms
265 * are not bonded, but then fragmentation makes no sense.
266 *
267 * @param path path to the adjacency file
268 */
269size_t getNoAtomsFromAdjacencyFile(const std::string &path)
270{
271 size_t NoAtoms = 0;
272
273 // parse in special file to get atom count (from line count)
274 std::string filename(path);
275 filename += FRAGMENTPREFIX;
276 filename += ADJACENCYFILE;
277 std::ifstream adjacency(filename.c_str());
278 if (adjacency.fail()) {
279 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
280 return false;
281 }
282 std::string buffer;
283 while (getline(adjacency, buffer))
284 NoAtoms++;
285 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
286
287 return NoAtoms;
288}
289
290void creatingJob(FragmentController &controller, const ControllerOptions_SystemCommandJob &ControllerInfo)
291{
292 const JobId_t next_id = controller.getAvailableId();
293 std::vector<FragmentJob::ptr> jobs;
294 createjobs(jobs, ControllerInfo.executable, ControllerInfo.jobcommand, next_id);
295 controller.addJobs(jobs);
296 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
297}
298
299/** Creates a MPQCCommandJob out of give \a command with \a argument.
300 *
301 * @param controller reference to controller to add jobs
302 * @param ControllerInfo information on the job
303 */
304void AddJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
305{
306 std::vector<FragmentJob::ptr> jobs;
307 for (std::vector< std::string >::const_iterator iter = ControllerInfo.jobfiles.begin();
308 iter != ControllerInfo.jobfiles.end(); ++iter) {
309 const JobId_t next_id = controller.getAvailableId();
310 const std::string &filename = *iter;
311 LOG(1, "INFO: Creating MPQCCommandJob with filename '"
312 +filename+"', and id "+toString(next_id)+".");
313 parsejob(jobs, ControllerInfo.executable, filename, next_id);
314 }
315 controller.addJobs(jobs);
316 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
317}
318
319int main(int argc, char* argv[])
320{
321 // from this moment on, we need to be sure to deeinitialize in the correct order
322 // this is handled by the cleanup function
323 atexit(cleanUp);
324
325 size_t Exitflag = 0;
326
327 ControllerOptions_MPQCCommandJob ControllerInfo;
328 boost::asio::io_service io_service;
329 FragmentController controller(io_service);
330 boost::program_options::variables_map vm;
331
332 typedef boost::function<void ()> ControllerCommand;
333 typedef std::map<std::string, std::deque<ControllerCommand> > CommandsMap_t;
334 CommandsMap_t CommandsMap;
335
336 // prepare the command queues for each ControllerCommand
337 // note: we need "< ControllerCommand >" because parseExecutable(),... return int
338 // in contrast to other functions that return void
339 std::deque<ControllerCommand> addjobsQueue = boost::assign::list_of< ControllerCommand >
340 (boost::bind(&FragmentController::requestIds,
341 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport),
342 boost::bind(&std::vector<std::string>::size, boost::cref(ControllerInfo.jobfiles))))
343 (boost::bind(&AddJobs, boost::ref(controller), boost::cref(ControllerInfo)))
344 ;
345 std::deque<ControllerCommand> createjobsQueue = boost::assign::list_of< ControllerCommand >
346 (boost::bind(&FragmentController::requestIds,
347 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport), 1))
348 (boost::bind(&creatingJob, boost::ref(controller), boost::cref(ControllerInfo)))
349 ;
350 std::deque<ControllerCommand> checkresultsQueue = boost::assign::list_of< ControllerCommand >
351 (boost::bind(&FragmentController::checkResults,
352 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
353 (boost::bind(&printJobStatus,
354 boost::bind(&FragmentController::getJobStatus, boost::ref(controller))))
355 ;
356 std::deque<ControllerCommand> receiveresultsQueue = boost::assign::list_of< ControllerCommand >
357 (boost::bind(&FragmentController::receiveResults,
358 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
359 (boost::bind(&printReceivedResults,
360 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller))))
361 ;
362 std::deque<ControllerCommand> receivempqcresultsQueue = boost::assign::list_of< ControllerCommand >
363 (boost::bind(&FragmentController::receiveResults,
364 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
365 (boost::bind(&printReceivedMPQCResults,
366 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller)),
367 boost::cref(ControllerInfo.fragmentpath),
368 boost::bind(&getNoAtomsFromAdjacencyFile, boost::cref(ControllerInfo.fragmentpath))))
369 ;
370 std::deque<ControllerCommand> removeallQueue = boost::assign::list_of< ControllerCommand >
371 (boost::bind(&FragmentController::removeall,
372 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
373 ;
374 std::deque<ControllerCommand> shutdownQueue = boost::assign::list_of< ControllerCommand >
375 (boost::bind(&FragmentController::shutdown,
376 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
377 ;
378 CommandsMap.insert( std::make_pair("addjobs", addjobsQueue) );
379 CommandsMap.insert( std::make_pair("createjobs", createjobsQueue) );
380 CommandsMap.insert( std::make_pair("checkresults", checkresultsQueue) );
381 CommandsMap.insert( std::make_pair("receiveresults", receiveresultsQueue) );
382 CommandsMap.insert( std::make_pair("receivempqc", receivempqcresultsQueue) );
383 CommandsMap.insert( std::make_pair("removeall", removeallQueue) );
384 CommandsMap.insert( std::make_pair("shutdown", shutdownQueue) );
385 std::vector<std::string> Commands;
386 for (CommandsMap_t::const_iterator iter = CommandsMap.begin(); iter != CommandsMap.end(); ++iter)
387 Commands.push_back(iter->first);
388
389 // Declare the supported options.
390 boost::program_options::options_description desc("Allowed options");
391 desc.add_options()
392 ("help,h", "produce help message")
393 ("verbosity,v", boost::program_options::value<size_t>(), "set verbosity level")
394 ("server", boost::program_options::value< std::string >(), "connect to server at this address (host:port)")
395 ("command", boost::program_options::value< std::string >(), (std::string("command to send to server: ")+toString(Commands)).c_str())
396 ("executable", boost::program_options::value< std::string >(), "executable for commands 'addjobs' and 'createjobs'")
397 ("fragment-path", boost::program_options::value< std::string >(), "path to fragment files for 'receivempqc'")
398 ("jobcommand", boost::program_options::value< std::string >(), "command argument for executable for 'createjobs'")
399 ("jobfiles", boost::program_options::value< std::vector< std::string > >()->multitoken(), "list of files as single argument to executable for 'addjobs'")
400 ;
401
402 // parse command line
403 boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
404 boost::program_options::notify(vm);
405
406 // set controller information
407 int status = 0;
408 status = ControllerInfo.parseHelp(vm, desc);
409 if (status) return status;
410 status = ControllerInfo.parseVerbosity(vm);
411 if (status) return status;
412 status = ControllerInfo.parseServerPort(vm);
413 if (status) return status;
414 status = ControllerInfo.parseCommand(vm, Commands);
415 if (status) return status;
416
417 // all later parse functions depend on parsed command
418 status = ControllerInfo.parseExecutable(vm);
419 if (status) return status;
420 status = ControllerInfo.parseJobCommand(vm);
421 if (status) return status;
422 status = ControllerInfo.parseFragmentpath(vm);
423 if (status) return status;
424 status = ControllerInfo.parseJobfiles(vm);
425 if (status) return status;
426
427 // parse given ControllerCommand
428 if( CommandsMap.count(ControllerInfo.command) == 0) {
429 ELOG(1, "Unrecognized command '"+toString(ControllerInfo.command)+"'.");
430 return 255;
431 }
432 std::deque<ControllerCommand> &commands = CommandsMap[ControllerInfo.command];
433 try
434 {
435 // execute each command in the queue synchronously
436 size_t phase = 1;
437 while (!commands.empty()) {
438 ControllerCommand command = commands.front();
439 commands.pop_front();
440 command();
441 {
442 io_service.reset();
443 Info info((std::string("io_service: ")+toString(phase)).c_str());
444 io_service.run();
445 }
446 }
447 Exitflag = controller.getExitflag();
448 }
449 catch (std::exception& e)
450 {
451 std::cerr << e.what() << std::endl;
452 }
453
454 return Exitflag;
455}
456
Note: See TracBrowser for help on using the repository browser.