source: src/Fragmentation/Automation/controller.cpp@ c4f43e

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

GetNextJobIdOperation now may request a vector of ids.

  • otherwise we needed multiple phase one calls, ever requesting a single id.
  • now, we state how many ids we want and may eventually get one by one as desired.
  • adapted FragmentScheduler::ControllerListener_t and FragmentController accordingly as we now have to exchange the desired number of ids, too.
  • requestid() needs now an additional parameter.
  • Property mode set to 100644
File size: 11.4 KB
RevLine 
[7ca772e]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
[986885]29#include <boost/archive/text_oarchive.hpp>
30#include <boost/archive/text_iarchive.hpp>
[ff60cfa]31#include <fstream>
[7ca772e]32#include <iostream>
33#include <map>
[ff60cfa]34#include <sstream>
35#include <streambuf>
36#include <vector>
[7ca772e]37
38#include "atexit.hpp"
39#include "CodePatterns/Info.hpp"
40#include "CodePatterns/Log.hpp"
[d7bb9b1]41#include "Fragmentation/EnergyMatrix.hpp"
42#include "Fragmentation/ForceMatrix.hpp"
43#include "Fragmentation/KeySetsContainer.hpp"
[d4885d]44#include "FragmentController.hpp"
[ff60cfa]45#include "Jobs/MPQCCommandJob.hpp"
[d7bb9b1]46#include "Jobs/MPQCCommandJob_MPQCData.hpp"
[d920b9]47#include "Jobs/SystemCommandJob.hpp"
[7670865]48#include "Results/FragmentResult.hpp"
[7ca772e]49
50enum CommandIndices {
51 UnknownCommandIndex = 0,
[ff60cfa]52 AddJobsIndex = 1,
53 CreateJobsIndex = 2,
54 CheckResultsIndex = 3,
55 ReceiveResultsIndex = 4,
[986885]56 ReceiveMPQCIndex = 5,
57 ShutdownIndex = 6,
[7ca772e]58};
59
[ff60cfa]60
[4dd16e]61/** Creates a SystemCommandJob out of give \a command with \a argument.
[d1dbfc]62 *
[4dd16e]63 * @param jobs created job is added to this vector
64 * @param command command to execute for SystemCommandJob
65 * @param argument argument for command to execute
66 * @param nextid id for this job
[d1dbfc]67 */
[554809]68void createjobs(
69 std::vector<FragmentJob::ptr> &jobs,
70 const std::string &command,
71 const std::string &argument,
72 const JobId_t nextid)
[d1dbfc]73{
[4dd16e]74
[554809]75 FragmentJob::ptr testJob( new SystemCommandJob(command, argument, nextid) );
[7ca772e]76 jobs.push_back(testJob);
[554809]77 LOG(1, "INFO: Added one SystemCommandJob.");
[7ca772e]78}
79
[d1dbfc]80/** Creates a MPQCCommandJob with argument \a filename.
81 *
82 * @param jobs created job is added to this vector
83 * @param filename filename being argument to job
84 * @param nextid id for this job
85 */
86void parsejob(
87 std::vector<FragmentJob::ptr> &jobs,
88 const std::string &filename,
89 const JobId_t nextid)
[ff60cfa]90{
91 std::ifstream file;
92 file.open(filename.c_str());
93 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
94 std::string output((std::istreambuf_iterator<char>(file)),
95 std::istreambuf_iterator<char>());
[d1dbfc]96 FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid) );
[ff60cfa]97 jobs.push_back(testJob);
98 file.close();
99 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
100}
101
[d1dbfc]102/** Print received results.
103 *
[4dd16e]104 * @param results received results to print
[d1dbfc]105 */
[4dd16e]106void printReceivedResults(std::vector<FragmentResult::ptr> &results)
[7ca772e]107{
[35f587]108 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
[7ca772e]109 iter != results.end(); ++iter)
[35f587]110 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
[7ca772e]111}
112
[d7bb9b1]113/** Print MPQCData from received results.
[986885]114 *
[4dd16e]115 * @param results vector of all received FragmentResult's
116 * @param KeySetFilename filename containing keysets
[986885]117 */
[d7bb9b1]118bool printReceivedMPQCResults(
119 std::vector<FragmentResult::ptr> &results,
120 const std::string &KeySetFilename)
[986885]121{
[d7bb9b1]122 EnergyMatrix Energy;
123 EnergyMatrix EnergyFragments;
124 ForceMatrix Force;
125 ForceMatrix ForceFragments;
126 KeySetsContainer KeySet;
127
128 // place results into EnergyMatrix and ForceMatrix
129 //if (!Energy.ParseFragmentMatrix(argv[1], dir, EnergySuffix, 0,0)) return false;
130 //if (!Force.ParseFragmentMatrix(argv[1], dir, ForcesSuffix, 0,0)) return false;
[986885]131 // combine all found data
132 std::vector<MPQCData> fragmentData(results.size());
133 MPQCData combinedData;
134
135 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
136 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
137 iter != results.end(); ++iter) {
138 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
139 MPQCData extractedData;
140 std::stringstream inputstream((*iter)->result);
141 boost::archive::text_iarchive ia(inputstream);
142 ia >> extractedData;
143 LOG(1, "INFO: extracted data is " << extractedData << ".");
144 }
[d7bb9b1]145
146 if (!Energy.InitialiseIndices()) return false;
147
148 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
149
150 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
151
152 if (!KeySet.ParseManyBodyTerms()) return false;
153
154 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
155 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
156
157 if(!Energy.SetLastMatrix(0., 0)) return false;
158 if(!Force.SetLastMatrix(0., 2)) return false;
159
160 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
161 // --------- sum up energy --------------------
162 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
163 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
164 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
165
166 // --------- sum up Forces --------------------
167 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
168 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
169 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
170 }
171
172 return true;
[986885]173}
174
[d7bb9b1]175
[7ca772e]176/** Returns a unique index for every command to allow switching over it.
177 *
178 * \param &commandmap map with command strings
179 * \param &cmd command string
180 * \return index from CommandIndices: UnkownCommandIndex - unknown command, else - command index
181 */
182CommandIndices getCommandIndex(std::map<std::string, CommandIndices> &commandmap, const std::string &cmd)
183{
184 std::map<std::string, CommandIndices>::const_iterator iter = commandmap.find(cmd);
185 if (iter != commandmap.end())
186 return iter->second;
187 else
188 return UnknownCommandIndex;
189}
190
191
192int main(int argc, char* argv[])
193{
194 // from this moment on, we need to be sure to deeinitialize in the correct order
195 // this is handled by the cleanup function
196 atexit(cleanUp);
197
198 setVerbosity(3);
199
200 size_t Exitflag = 0;
[ff60cfa]201 typedef std::map<std::string, CommandIndices> CommandsMap_t;
202 CommandsMap_t CommandsMap;
203 CommandsMap.insert( std::make_pair("addjobs", AddJobsIndex) );
204 CommandsMap.insert( std::make_pair("createjobs", CreateJobsIndex) );
[7ca772e]205 CommandsMap.insert( std::make_pair("checkresults", CheckResultsIndex) );
206 CommandsMap.insert( std::make_pair("receiveresults", ReceiveResultsIndex) );
[986885]207 CommandsMap.insert( std::make_pair("receivempqc", ReceiveMPQCIndex) );
[7ca772e]208 CommandsMap.insert( std::make_pair("shutdown", ShutdownIndex) );
209 try
210 {
211 // Check command line arguments.
[ff60cfa]212 if (argc < 4)
[7ca772e]213 {
[ff60cfa]214 std::cerr << "Usage: " << argv[0] << " <host> <port> <command> [options to command]" << std::endl;
215 std::cerr << "List of available commands:" << std::endl;
216 for(CommandsMap_t::const_iterator iter = CommandsMap.begin();
217 iter != CommandsMap.end(); ++iter) {
218 std::cerr << "\t" << iter->first << std::endl;
219 }
[d7bb9b1]220 return false;
[7ca772e]221 }
222
223 boost::asio::io_service io_service;
224 FragmentController controller(io_service);
225
[d1dbfc]226 // Initial phase: information gathering from server
227
228 switch(getCommandIndex(CommandsMap, argv[3])) {
229 case AddJobsIndex:
230 {
231 if (argc < 5) {
232 ELOG(1, "Please add a filename for the MPQCCommandJob.");
233 } else {
234 // get an id for every filename
[c4f43e]235 controller.requestIds(argv[1], argv[2], argc-4);
[d1dbfc]236 }
237 break;
238 }
239 case CreateJobsIndex:
240 {
[554809]241 std::vector<FragmentJob::ptr> jobs;
242 if (argc < 6) {
243 ELOG(1, "'createjobs' requires two options: [command] [argument].");
244 } else {
[c4f43e]245 controller.requestIds(argv[1], argv[2], 1);
[554809]246 }
[d1dbfc]247 break;
248 }
249 case CheckResultsIndex:
250 break;
251 case ReceiveResultsIndex:
252 break;
[986885]253 case ReceiveMPQCIndex:
254 break;
[d1dbfc]255 case ShutdownIndex:
256 break;
257 case UnknownCommandIndex:
258 default:
259 ELOG(1, "Unrecognized command '"+toString(argv[3])+"'.");
260 break;
261 }
262
263 {
264 io_service.reset();
265 Info info("io_service: Phase One");
266 io_service.run();
267 }
268
269 // Second phase: Building jobs and sending information to server
270
[7ca772e]271 switch(getCommandIndex(CommandsMap, argv[3])) {
[ff60cfa]272 case AddJobsIndex:
273 {
274 std::vector<FragmentJob::ptr> jobs;
[d1dbfc]275 if (argc < 5) {
[ff60cfa]276 ELOG(1, "Please add a filename for the MPQCCommandJob.");
277 } else {
278 for (int argcount = 4; argcount < argc; ++argcount) {
[4dd16e]279 const JobId_t next_id = controller.getAvailableId();
[d1dbfc]280 const std::string filename(argv[argcount]);
281 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
282 +filename+"', and id "+toString(next_id)+".");
283 parsejob(jobs, filename, next_id);
[ff60cfa]284 }
[4dd16e]285 controller.addJobs(jobs);
286 controller.sendJobs(argv[1], argv[2]);
[ff60cfa]287 }
288 break;
289 }
290 case CreateJobsIndex:
[7ca772e]291 {
[78ad7d]292 std::vector<FragmentJob::ptr> jobs;
[554809]293 if (argc < 6) {
[4dd16e]294 ELOG(1, "'createjobs' requires two options: [command] [argument].");
295 } else {
296 const JobId_t next_id = controller.getAvailableId();
297 createjobs(jobs, argv[4], argv[5], next_id);
298 controller.addJobs(jobs);
299 controller.sendJobs(argv[1], argv[2]);
[554809]300 }
[7ca772e]301 break;
302 }
303 case CheckResultsIndex:
304 {
[4dd16e]305 controller.checkResults(argv[1], argv[2]);
[7ca772e]306 break;
307 }
308 case ReceiveResultsIndex:
309 {
[4dd16e]310 controller.receiveResults(argv[1], argv[2]);
[7ca772e]311 break;
312 }
[986885]313 case ReceiveMPQCIndex:
314 {
[4dd16e]315 controller.receiveResults(argv[1], argv[2]);
[986885]316 break;
317 }
[7ca772e]318 case ShutdownIndex:
319 {
[4dd16e]320 controller.shutdown(argv[1], argv[2]);
[7ca772e]321 break;
322 }
323 case UnknownCommandIndex:
324 default:
325 ELOG(0, "Unrecognized command '"+toString(argv[3])+"'.");
326 break;
327 }
328
329 {
[d1dbfc]330 io_service.reset();
331 Info info("io_service: Phase Two");
[7ca772e]332 io_service.run();
333 }
334
[d1dbfc]335 // Final phase: Print result of command
336
[7ca772e]337 switch(getCommandIndex(CommandsMap, argv[3])) {
[ff60cfa]338 case AddJobsIndex:
339 case CreateJobsIndex:
[7ca772e]340 break;
341 case CheckResultsIndex:
342 {
[4dd16e]343 controller.printDoneJobs();
[7ca772e]344 break;
345 }
346 case ReceiveResultsIndex:
347 {
[4dd16e]348 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
349 printReceivedResults(results);
[7ca772e]350 break;
351 }
[986885]352 case ReceiveMPQCIndex:
353 {
354 if (argc == 4) {
355 ELOG(1, "'receivempqc' requires one option: [KeySetFilename].");
356 } else {
357 const std::string KeySetFilename = argv[4];
358 LOG(1, "INFO: Parsing id associations from " << KeySetFilename << ".");
[4dd16e]359 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
[d7bb9b1]360 printReceivedMPQCResults(results, KeySetFilename);
[986885]361 }
362 break;
363 }
[7ca772e]364 case ShutdownIndex:
365 break;
366 case UnknownCommandIndex:
367 default:
368 ELOG(0, "Unrecognized command '"+toString(argv[3])+"'.");
369 break;
370 }
371 Exitflag = controller.getExitflag();
372 }
373 catch (std::exception& e)
374 {
375 std::cerr << e.what() << std::endl;
376 }
377
378 return Exitflag;
379}
[4dd16e]380
Note: See TracBrowser for help on using the repository browser.