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

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

Completed printMPQCReceivedResults() in controller by using MatrixContainer::AddMatrix().

  • result is printed at end of function.
  • Added helper function to controller to parse total number of atoms from Adjacency file.
  • NOTE: This function is only temporary. It should lateron be outsourced to its own class, maybe as a functor, and then eventually be merged into the main molecuilder program to be accessible inside an Action.
  • Property mode set to 100644
File size: 15.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/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 "Helpers/defs.hpp"
46#include "Jobs/MPQCCommandJob.hpp"
47#include "Jobs/MPQCCommandJob_MPQCData.hpp"
48#include "Jobs/SystemCommandJob.hpp"
49#include "Results/FragmentResult.hpp"
50
51enum CommandIndices {
52 UnknownCommandIndex = 0,
53 AddJobsIndex = 1,
54 CreateJobsIndex = 2,
55 CheckResultsIndex = 3,
56 ReceiveResultsIndex = 4,
57 ReceiveMPQCIndex = 5,
58 ShutdownIndex = 6,
59};
60
61
62/** Creates a SystemCommandJob out of give \a command with \a argument.
63 *
64 * @param jobs created job is added to this vector
65 * @param command command to execute for SystemCommandJob
66 * @param argument argument for command to execute
67 * @param nextid id for this job
68 */
69void createjobs(
70 std::vector<FragmentJob::ptr> &jobs,
71 const std::string &command,
72 const std::string &argument,
73 const JobId_t nextid)
74{
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(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
290
291/** Returns a unique index for every command to allow switching over it.
292 *
293 * \param &commandmap map with command strings
294 * \param &cmd command string
295 * \return index from CommandIndices: UnkownCommandIndex - unknown command, else - command index
296 */
297CommandIndices getCommandIndex(std::map<std::string, CommandIndices> &commandmap, const std::string &cmd)
298{
299 std::map<std::string, CommandIndices>::const_iterator iter = commandmap.find(cmd);
300 if (iter != commandmap.end())
301 return iter->second;
302 else
303 return UnknownCommandIndex;
304}
305
306
307int main(int argc, char* argv[])
308{
309 // from this moment on, we need to be sure to deeinitialize in the correct order
310 // this is handled by the cleanup function
311 atexit(cleanUp);
312
313 setVerbosity(3);
314
315 size_t Exitflag = 0;
316 typedef std::map<std::string, CommandIndices> CommandsMap_t;
317 CommandsMap_t CommandsMap;
318 CommandsMap.insert( std::make_pair("addjobs", AddJobsIndex) );
319 CommandsMap.insert( std::make_pair("createjobs", CreateJobsIndex) );
320 CommandsMap.insert( std::make_pair("checkresults", CheckResultsIndex) );
321 CommandsMap.insert( std::make_pair("receiveresults", ReceiveResultsIndex) );
322 CommandsMap.insert( std::make_pair("receivempqc", ReceiveMPQCIndex) );
323 CommandsMap.insert( std::make_pair("shutdown", ShutdownIndex) );
324 try
325 {
326 // Check command line arguments.
327 if (argc < 4)
328 {
329 std::cerr << "Usage: " << argv[0] << " <host> <port> <command> [options to command]" << std::endl;
330 std::cerr << "List of available commands:" << std::endl;
331 for(CommandsMap_t::const_iterator iter = CommandsMap.begin();
332 iter != CommandsMap.end(); ++iter) {
333 std::cerr << "\t" << iter->first << std::endl;
334 }
335 return false;
336 }
337
338 boost::asio::io_service io_service;
339 FragmentController controller(io_service);
340
341 // Initial phase: information gathering from server
342
343 switch(getCommandIndex(CommandsMap, argv[3])) {
344 case AddJobsIndex:
345 {
346 if (argc < 6) {
347 ELOG(1, "'addjobs' requires at least two options: [mpqc] [list of input files ...].");
348 } else {
349 // get an id for every filename
350 controller.requestIds(argv[1], argv[2], argc-5);
351 }
352 break;
353 }
354 case CreateJobsIndex:
355 {
356 std::vector<FragmentJob::ptr> jobs;
357 if (argc < 6) {
358 ELOG(1, "'createjobs' requires two options: [command] [argument].");
359 } else {
360 controller.requestIds(argv[1], argv[2], 1);
361 }
362 break;
363 }
364 case CheckResultsIndex:
365 break;
366 case ReceiveResultsIndex:
367 break;
368 case ReceiveMPQCIndex:
369 break;
370 case ShutdownIndex:
371 break;
372 case UnknownCommandIndex:
373 default:
374 ELOG(1, "Unrecognized command '"+toString(argv[3])+"'.");
375 break;
376 }
377
378 {
379 io_service.reset();
380 Info info("io_service: Phase One");
381 io_service.run();
382 }
383
384 // Second phase: Building jobs and sending information to server
385
386 switch(getCommandIndex(CommandsMap, argv[3])) {
387 case AddJobsIndex:
388 {
389 std::vector<FragmentJob::ptr> jobs;
390 if (argc < 6) {
391 ELOG(1, "Please add a filename for the MPQCCommandJob.");
392 } else {
393 const std::string command(argv[4]);
394 for (int argcount = 5; argcount < argc; ++argcount) {
395 const JobId_t next_id = controller.getAvailableId();
396 const std::string filename(argv[argcount]);
397 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
398 +filename+"', and id "+toString(next_id)+".");
399 parsejob(jobs, command, filename, next_id);
400 }
401 controller.addJobs(jobs);
402 controller.sendJobs(argv[1], argv[2]);
403 }
404 break;
405 }
406 case CreateJobsIndex:
407 {
408 std::vector<FragmentJob::ptr> jobs;
409 if (argc < 6) {
410 ELOG(1, "'createjobs' requires two options: [command] [argument].");
411 } else {
412 const JobId_t next_id = controller.getAvailableId();
413 createjobs(jobs, argv[4], argv[5], next_id);
414 controller.addJobs(jobs);
415 controller.sendJobs(argv[1], argv[2]);
416 }
417 break;
418 }
419 case CheckResultsIndex:
420 {
421 controller.checkResults(argv[1], argv[2]);
422 break;
423 }
424 case ReceiveResultsIndex:
425 {
426 controller.receiveResults(argv[1], argv[2]);
427 break;
428 }
429 case ReceiveMPQCIndex:
430 {
431 controller.receiveResults(argv[1], argv[2]);
432 break;
433 }
434 case ShutdownIndex:
435 {
436 controller.shutdown(argv[1], argv[2]);
437 break;
438 }
439 case UnknownCommandIndex:
440 default:
441 ELOG(0, "Unrecognized command '"+toString(argv[3])+"'.");
442 break;
443 }
444
445 {
446 io_service.reset();
447 Info info("io_service: Phase Two");
448 io_service.run();
449 }
450
451 // Final phase: Print result of command
452
453 switch(getCommandIndex(CommandsMap, argv[3])) {
454 case AddJobsIndex:
455 case CreateJobsIndex:
456 break;
457 case CheckResultsIndex:
458 {
459 controller.printDoneJobs();
460 break;
461 }
462 case ReceiveResultsIndex:
463 {
464 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
465 printReceivedResults(results);
466 break;
467 }
468 case ReceiveMPQCIndex:
469 {
470 if (argc < 5) {
471 ELOG(1, "'receivempqc' require one option: [path to fragment files].");
472 } else {
473 const std::string path = argv[4];
474 LOG(1, "INFO: Parsing fragment files from " << path << ".");
475 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
476 printReceivedMPQCResults(
477 results,
478 path,
479 getNoAtomsFromAdjacencyFile(path));
480 }
481 break;
482 }
483 case ShutdownIndex:
484 break;
485 case UnknownCommandIndex:
486 default:
487 ELOG(0, "Unrecognized command '"+toString(argv[3])+"'.");
488 break;
489 }
490 Exitflag = controller.getExitflag();
491 }
492 catch (std::exception& e)
493 {
494 std::cerr << e.what() << std::endl;
495 }
496
497 return Exitflag;
498}
499
Note: See TracBrowser for help on using the repository browser.