source: src/controller.cpp@ 865a218

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

Merged createjobs() and creatingJob() into createJob() in controller.cpp.

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