source: src/controller_MPQCCommandJob.cpp@ 8e7dd9

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

Removed JobMarket as it is now in its own repository.

  • added ax_jobmarket.m4.
  • added check to configure.ac
  • Removed libraries libJobMarket... in Makefile.am's, replaced by JobMarket_..._LIBS.
  • changed some includes that now required JobMarket/ prefix.

Larger change to get JobMarket including its tests out of MoleCuilder:

  • configure has new enable-switch for JobMarket. Only then, we tests for its presence and usability (and also for boost::asio).
  • I do not know how to check for AM_CONDITIONAL or config.h values properly in a shell. Hence, I moved all regression tests dealing with the JobMarket into their own folder tests/JobMarket with depends on CONDJOBMARKET whether its included or not, similar to tests/Python.
  • TESTFIX: regression tests moved to tests/JobMarket have their paths changed.
  • FragmentationAutomationAction is now conditionally compiled in as well.
  • some Makefile.am's changed because we now have JobMarket_CFLAGS and _LIBS similar CodePatterns.
  • We use boost::preprocessor to add it dependently on HAVE_JOBMARKET to src/Actions/GlobalListOfActions.
  • TESTFIX: The former required a small change to CodeChecks test testsuite-globallistofactions_hpp as we can check no longer for the action name within brackets there.
  • FIX: I removed some unnecessary includes (defs.hpp) from MPQCCommandJob...hpp into the .cpp files.
  • Property mode set to 100644
File size: 12.8 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * controller_MPQCCommandJob.cpp
10 *
11 * Created on: 01.06.2012
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20// boost asio needs specific operator new
21#include <boost/asio.hpp>
22
23#include <boost/archive/text_iarchive.hpp>
24#include <boost/archive/text_oarchive.hpp>
25
26#include "CodePatterns/MemDebug.hpp"
27
28#include "controller_MPQCCommandJob.hpp"
29
30#include <boost/assign.hpp>
31#include <boost/bind.hpp>
32#include <fstream>
33#include <string>
34
35#include "CodePatterns/Info.hpp"
36#include "CodePatterns/Log.hpp"
37
38#include "JobMarket/Controller/ControllerCommand.hpp"
39#include "JobMarket/Controller/ControllerCommandRegistry.hpp"
40#include "JobMarket/Controller/FragmentController.hpp"
41#include "JobMarket/JobId.hpp"
42#include "JobMarket/Jobs/FragmentJob.hpp"
43#include "JobMarket/Results/FragmentResult.hpp"
44
45#include "Fragmentation/EnergyMatrix.hpp"
46#include "Fragmentation/ForceMatrix.hpp"
47#include "Fragmentation/KeySetsContainer.hpp"
48#include "Fragmentation/defs.hpp"
49
50#include "Helpers/defs.hpp"
51
52#include "Jobs/MPQCCommandJob.hpp"
53#include "Jobs/MPQCCommandJob_MPQCData.hpp"
54
55#include "LinearAlgebra/defs.hpp"
56
57#include "ControllerOptions_MPQCCommandJob.hpp"
58
59/** Creates a MPQCCommandJob with argument \a filename.
60 *
61 * @param jobs created job is added to this vector
62 * @param command mpqc command to execute
63 * @param filename filename being argument to job
64 * @param nextid id for this job
65 */
66void parsejob(
67 std::vector<FragmentJob::ptr> &jobs,
68 const std::string &command,
69 const std::string &filename,
70 const JobId_t nextid)
71{
72 std::ifstream file;
73 file.open(filename.c_str());
74 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
75 std::string output((std::istreambuf_iterator<char>(file)),
76 std::istreambuf_iterator<char>());
77 FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid, command) );
78 jobs.push_back(testJob);
79 file.close();
80 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
81}
82
83/** Print received results.
84 *
85 * @param results received results to print
86 */
87void printReceivedResults(const std::vector<FragmentResult::ptr> &results)
88{
89 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
90 iter != results.end(); ++iter)
91 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
92}
93
94/** Print MPQCData from received results.
95 *
96 * @param results received results to extract MPQCData from
97 * @param KeySetFilename filename with keysets to associate forces correctly
98 * @param NoAtoms total number of atoms
99 */
100bool printReceivedMPQCResults(
101 const std::vector<FragmentResult::ptr> &results,
102 const std::string &KeySetFilename,
103 size_t NoAtoms)
104{
105 EnergyMatrix Energy;
106 EnergyMatrix EnergyFragments;
107 ForceMatrix Force;
108 ForceMatrix ForceFragments;
109 KeySetsContainer KeySet;
110
111 // align fragments
112 std::map< JobId_t, size_t > MatrixNrLookup;
113 size_t FragmentCounter = 0;
114 {
115 // bring ids in order ...
116 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
117 IdResultMap_t IdResultMap;
118 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
119 iter != results.end(); ++iter) {
120 #ifndef NDEBUG
121 std::pair< IdResultMap_t::iterator, bool> inserter =
122 #endif
123 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
124 ASSERT( inserter.second,
125 "printReceivedMPQCResults() - two results have same id "
126 +toString((*iter)->getId())+".");
127 }
128 // ... and fill lookup
129 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
130 iter != IdResultMap.end(); ++iter)
131 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
132 }
133 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
134
135 // extract results
136 std::vector<MPQCData> fragmentData(results.size());
137 MPQCData combinedData;
138
139 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
140 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
141 iter != results.end(); ++iter) {
142 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
143 MPQCData extractedData;
144 std::stringstream inputstream((*iter)->result);
145 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
146 boost::archive::text_iarchive ia(inputstream);
147 ia >> extractedData;
148 LOG(1, "INFO: extracted data is " << extractedData << ".");
149
150 // place results into EnergyMatrix ...
151 {
152 MatrixContainer::MatrixArray matrix;
153 matrix.resize(1);
154 matrix[0].resize(1, extractedData.energy);
155 if (!Energy.AddMatrix(
156 std::string("MPQCJob ")+toString((*iter)->getId()),
157 matrix,
158 MatrixNrLookup[(*iter)->getId()])) {
159 ELOG(1, "Adding energy matrix failed.");
160 return false;
161 }
162 }
163 // ... and ForceMatrix (with two empty columns in front)
164 {
165 MatrixContainer::MatrixArray matrix;
166 const size_t rows = extractedData.forces.size();
167 matrix.resize(rows);
168 for (size_t i=0;i<rows;++i) {
169 const size_t columns = 2+extractedData.forces[i].size();
170 matrix[i].resize(columns, 0.);
171 // for (size_t j=0;j<2;++j)
172 // matrix[i][j] = 0.;
173 for (size_t j=2;j<columns;++j)
174 matrix[i][j] = extractedData.forces[i][j-2];
175 }
176 if (!Force.AddMatrix(
177 std::string("MPQCJob ")+toString((*iter)->getId()),
178 matrix,
179 MatrixNrLookup[(*iter)->getId()])) {
180 ELOG(1, "Adding force matrix failed.");
181 return false;
182 }
183 }
184 }
185 // add one more matrix (not required for energy)
186 MatrixContainer::MatrixArray matrix;
187 matrix.resize(1);
188 matrix[0].resize(1, 0.);
189 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
190 return false;
191 // but for energy because we need to know total number of atoms
192 matrix.resize(NoAtoms);
193 for (size_t i = 0; i< NoAtoms; ++i)
194 matrix[i].resize(2+NDIM, 0.);
195 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
196 return false;
197
198
199 // combine all found data
200 if (!Energy.InitialiseIndices()) return false;
201
202 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
203
204 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
205
206 if (!KeySet.ParseManyBodyTerms()) return false;
207
208 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
209 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
210
211 if(!Energy.SetLastMatrix(0., 0)) return false;
212 if(!Force.SetLastMatrix(0., 2)) return false;
213
214 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
215 // --------- sum up energy --------------------
216 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
217 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
218 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
219
220 // --------- sum up Forces --------------------
221 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
222 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
223 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
224 }
225
226 // for debugging print resulting energy and forces
227 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
228 std::stringstream output;
229 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
230 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
231 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
232 output << "\n";
233 }
234 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
235
236 return true;
237}
238
239
240/** Helper function to get number of atoms somehow.
241 *
242 * Here, we just parse the number of lines in the adjacency file as
243 * it should correspond to the number of atoms, except when some atoms
244 * are not bonded, but then fragmentation makes no sense.
245 *
246 * @param path path to the adjacency file
247 */
248size_t getNoAtomsFromAdjacencyFile(const std::string &path)
249{
250 size_t NoAtoms = 0;
251
252 // parse in special file to get atom count (from line count)
253 std::string filename(path);
254 filename += FRAGMENTPREFIX;
255 filename += ADJACENCYFILE;
256 std::ifstream adjacency(filename.c_str());
257 if (adjacency.fail()) {
258 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
259 return false;
260 }
261 std::string buffer;
262 while (getline(adjacency, buffer))
263 NoAtoms++;
264 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
265
266 return NoAtoms;
267}
268
269/** Creates a MPQCCommandJob out of give \a command with \a argument.
270 *
271 * @param controller reference to controller to add jobs
272 * @param ControllerInfo information on the job
273 */
274void AddJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
275{
276 std::vector<FragmentJob::ptr> jobs;
277 for (std::vector< std::string >::const_iterator iter = ControllerInfo.jobfiles.begin();
278 iter != ControllerInfo.jobfiles.end(); ++iter) {
279 const JobId_t next_id = controller.getAvailableId();
280 const std::string &filename = *iter;
281 LOG(1, "INFO: Creating MPQCCommandJob with filename '"
282 +filename+"', and id "+toString(next_id)+".");
283 parsejob(jobs, ControllerInfo.executable, filename, next_id);
284 }
285 controller.addJobs(jobs);
286 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
287}
288
289inline std::vector<std::string> getListOfCommands(const ControllerCommandRegistry &ControllerCommands)
290{
291 std::vector<std::string> Commands;
292 for (ControllerCommandRegistry::const_iterator iter = ControllerCommands.getBeginIter();
293 iter != ControllerCommands.getEndIter(); ++iter)
294 Commands.push_back(iter->first);
295
296 return Commands;
297}
298
299ControllerOptions *controller_MPQCCommandJob::allocateControllerInfo()
300{
301 return new ControllerOptions_MPQCCommandJob();
302}
303
304void controller_MPQCCommandJob::addSpecificCommands(
305 boost::function<void (ControllerCommand *)> &registrator,
306 FragmentController &controller,
307 ControllerOptions &ControllerInfo)
308{
309 ControllerOptions_MPQCCommandJob &CI =
310 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
311 registrator(new ControllerCommand("addjobs",
312 boost::assign::list_of< ControllerCommand::commands_t >
313 (boost::bind(&FragmentController::requestIds,
314 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport),
315 boost::bind(&std::vector<std::string>::size, boost::cref(CI.jobfiles))))
316 (boost::bind(&AddJobs, boost::ref(controller), boost::cref(CI)))
317 ));
318 registrator(new ControllerCommand("receiveresults",
319 boost::assign::list_of< ControllerCommand::commands_t >
320 (boost::bind(&FragmentController::receiveResults,
321 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
322 (boost::bind(&printReceivedResults,
323 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller))))
324 ));
325 registrator(new ControllerCommand("receivempqc",
326 boost::assign::list_of< ControllerCommand::commands_t >
327 (boost::bind(&FragmentController::receiveResults,
328 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
329 (boost::bind(&printReceivedMPQCResults,
330 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller)),
331 boost::cref(CI.fragmentpath),
332 boost::bind(&getNoAtomsFromAdjacencyFile, boost::cref(CI.fragmentpath))))
333 ));
334}
335
336void controller_MPQCCommandJob::addSpecificOptions(
337 boost::program_options::options_description_easy_init option)
338{
339 option
340 ("executable", boost::program_options::value< std::string >(), "executable for commands 'createjobs'")
341 ("fragment-path", boost::program_options::value< std::string >(), "path to fragment files for 'receivempqc'")
342 ("jobfiles", boost::program_options::value< std::vector< std::string > >()->multitoken(), "list of files as single argument toexecutable for 'addjobs'")
343 ;
344}
345
346int controller_MPQCCommandJob::addOtherParsings(
347 ControllerOptions &ControllerInfo,
348 boost::program_options::variables_map &vm)
349{
350 ControllerOptions_MPQCCommandJob &CI =
351 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
352 int status = 0;
353 status = CI.parseExecutable(vm);
354 if (status) return status;
355 status = CI.parseFragmentpath(vm);
356 if (status) return status;
357 status = CI.parseJobfiles(vm);
358 return status;
359}
Note: See TracBrowser for help on using the repository browser.