source: src/Fragmentation/Automation/controller.cpp@ 917be8

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

MPQCCommandJob now takes command argument to the mpqc executable.

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