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
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/archive/text_oarchive.hpp>
30#include <boost/archive/text_iarchive.hpp>
31#include <fstream>
32#include <iostream>
33#include <map>
34#include <sstream>
35#include <streambuf>
36#include <vector>
37
38#include "atexit.hpp"
39#include "CodePatterns/Info.hpp"
40#include "CodePatterns/Log.hpp"
41#include "Fragmentation/EnergyMatrix.hpp"
42#include "Fragmentation/ForceMatrix.hpp"
43#include "Fragmentation/KeySetsContainer.hpp"
44#include "FragmentController.hpp"
45#include "Jobs/MPQCCommandJob.hpp"
46#include "Jobs/MPQCCommandJob_MPQCData.hpp"
47#include "Jobs/SystemCommandJob.hpp"
48#include "Results/FragmentResult.hpp"
49
50enum CommandIndices {
51 UnknownCommandIndex = 0,
52 AddJobsIndex = 1,
53 CreateJobsIndex = 2,
54 CheckResultsIndex = 3,
55 ReceiveResultsIndex = 4,
56 ReceiveMPQCIndex = 5,
57 ShutdownIndex = 6,
58};
59
60
61/** Creates a SystemCommandJob out of give \a command with \a argument.
62 *
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
67 */
68void createjobs(
69 std::vector<FragmentJob::ptr> &jobs,
70 const std::string &command,
71 const std::string &argument,
72 const JobId_t nextid)
73{
74
75 FragmentJob::ptr testJob( new SystemCommandJob(command, argument, nextid) );
76 jobs.push_back(testJob);
77 LOG(1, "INFO: Added one SystemCommandJob.");
78}
79
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)
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>());
96 FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid) );
97 jobs.push_back(testJob);
98 file.close();
99 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
100}
101
102/** Print received results.
103 *
104 * @param results received results to print
105 */
106void printReceivedResults(std::vector<FragmentResult::ptr> &results)
107{
108 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
109 iter != results.end(); ++iter)
110 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
111}
112
113/** Print MPQCData from received results.
114 *
115 * @param results vector of all received FragmentResult's
116 * @param KeySetFilename filename containing keysets
117 */
118bool printReceivedMPQCResults(
119 std::vector<FragmentResult::ptr> &results,
120 const std::string &KeySetFilename)
121{
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;
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 }
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;
173}
174
175
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;
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) );
205 CommandsMap.insert( std::make_pair("checkresults", CheckResultsIndex) );
206 CommandsMap.insert( std::make_pair("receiveresults", ReceiveResultsIndex) );
207 CommandsMap.insert( std::make_pair("receivempqc", ReceiveMPQCIndex) );
208 CommandsMap.insert( std::make_pair("shutdown", ShutdownIndex) );
209 try
210 {
211 // Check command line arguments.
212 if (argc < 4)
213 {
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 }
220 return false;
221 }
222
223 boost::asio::io_service io_service;
224 FragmentController controller(io_service);
225
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
235 controller.requestIds(argv[1], argv[2], argc-4);
236 }
237 break;
238 }
239 case CreateJobsIndex:
240 {
241 std::vector<FragmentJob::ptr> jobs;
242 if (argc < 6) {
243 ELOG(1, "'createjobs' requires two options: [command] [argument].");
244 } else {
245 controller.requestIds(argv[1], argv[2], 1);
246 }
247 break;
248 }
249 case CheckResultsIndex:
250 break;
251 case ReceiveResultsIndex:
252 break;
253 case ReceiveMPQCIndex:
254 break;
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
271 switch(getCommandIndex(CommandsMap, argv[3])) {
272 case AddJobsIndex:
273 {
274 std::vector<FragmentJob::ptr> jobs;
275 if (argc < 5) {
276 ELOG(1, "Please add a filename for the MPQCCommandJob.");
277 } else {
278 for (int argcount = 4; argcount < argc; ++argcount) {
279 const JobId_t next_id = controller.getAvailableId();
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);
284 }
285 controller.addJobs(jobs);
286 controller.sendJobs(argv[1], argv[2]);
287 }
288 break;
289 }
290 case CreateJobsIndex:
291 {
292 std::vector<FragmentJob::ptr> jobs;
293 if (argc < 6) {
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]);
300 }
301 break;
302 }
303 case CheckResultsIndex:
304 {
305 controller.checkResults(argv[1], argv[2]);
306 break;
307 }
308 case ReceiveResultsIndex:
309 {
310 controller.receiveResults(argv[1], argv[2]);
311 break;
312 }
313 case ReceiveMPQCIndex:
314 {
315 controller.receiveResults(argv[1], argv[2]);
316 break;
317 }
318 case ShutdownIndex:
319 {
320 controller.shutdown(argv[1], argv[2]);
321 break;
322 }
323 case UnknownCommandIndex:
324 default:
325 ELOG(0, "Unrecognized command '"+toString(argv[3])+"'.");
326 break;
327 }
328
329 {
330 io_service.reset();
331 Info info("io_service: Phase Two");
332 io_service.run();
333 }
334
335 // Final phase: Print result of command
336
337 switch(getCommandIndex(CommandsMap, argv[3])) {
338 case AddJobsIndex:
339 case CreateJobsIndex:
340 break;
341 case CheckResultsIndex:
342 {
343 controller.printDoneJobs();
344 break;
345 }
346 case ReceiveResultsIndex:
347 {
348 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
349 printReceivedResults(results);
350 break;
351 }
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 << ".");
359 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
360 printReceivedMPQCResults(results, KeySetFilename);
361 }
362 break;
363 }
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}
380
Note: See TracBrowser for help on using the repository browser.