source: src/controller_MPQCCommandJob.cpp@ 48d20d

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

Placed Containers, Converter, and SetValues as subfolders into Summation.

  • also libMolecuilderFragmentationSummation is now a shared library, easing linkage to libMolecuilderJobs, and contains all of the three convenience libraries.
  • libMolecuilderFragmentationSetValues is now again convenience, as contained in ..Summation which in turn is shared.
  • KeySetsContainer right now is the link between lib..Summation and lib.. Fragmentation. Hence, we had to extract the module and change it into a shared library, as it is required by libMolecuilderJobs through ..Summation but also by ..Fragmentation that heavily relies on this container.
  • moved parseKeySetFile down into Fragmentation folder to KeySetsContainer, it is also contained in new shared library libMolecuilderFragmentation_ KeySetsContainer.
  • Property mode set to 100644
File size: 13.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 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * controller_MPQCCommandJob.cpp
25 *
26 * Created on: 01.06.2012
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35// boost asio needs specific operator new
36#include <boost/asio.hpp>
37
38#include <boost/archive/text_iarchive.hpp>
39#include <boost/archive/text_oarchive.hpp>
40
41#include "CodePatterns/MemDebug.hpp"
42
43#include "controller_MPQCCommandJob.hpp"
44
45#include <boost/assign.hpp>
46#include <boost/bind.hpp>
47#include <fstream>
48#include <string>
49
50#include "CodePatterns/Info.hpp"
51#include "CodePatterns/Log.hpp"
52
53#include "JobMarket/Controller/ControllerCommand.hpp"
54#include "JobMarket/Controller/ControllerCommandRegistry.hpp"
55#include "JobMarket/Controller/FragmentController.hpp"
56#include "JobMarket/JobId.hpp"
57#include "JobMarket/Jobs/FragmentJob.hpp"
58#include "JobMarket/Results/FragmentResult.hpp"
59
60#include "Fragmentation/EnergyMatrix.hpp"
61#include "Fragmentation/ForceMatrix.hpp"
62#include "Fragmentation/KeySetsContainer.hpp"
63#include "Fragmentation/defs.hpp"
64
65#include "Helpers/defs.hpp"
66
67#include "Jobs/MPQCCommandJob.hpp"
68#include "Fragmentation/Summation/Containers/MPQCData.hpp"
69
70#include "LinearAlgebra/defs.hpp"
71
72#include "ControllerOptions_MPQCCommandJob.hpp"
73
74/** Creates a MPQCCommandJob with argument \a filename.
75 *
76 * @param jobs created job is added to this vector
77 * @param command mpqc command to execute
78 * @param filename filename being argument to job
79 * @param nextid id for this job
80 */
81void parsejob(
82 std::vector<FragmentJob::ptr> &jobs,
83 const std::string &command,
84 const std::string &filename,
85 const JobId_t nextid)
86{
87 std::ifstream file;
88 file.open(filename.c_str());
89 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
90 std::string output((std::istreambuf_iterator<char>(file)),
91 std::istreambuf_iterator<char>());
92 FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid, command) );
93 jobs.push_back(testJob);
94 file.close();
95 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
96}
97
98/** Print received results.
99 *
100 * @param results received results to print
101 */
102void printReceivedResults(const std::vector<FragmentResult::ptr> &results)
103{
104 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
105 iter != results.end(); ++iter)
106 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
107}
108
109/** Print MPQCData from received results.
110 *
111 * @param results received results to extract MPQCData from
112 * @param KeySetFilename filename with keysets to associate forces correctly
113 * @param NoAtoms total number of atoms
114 */
115bool printReceivedMPQCResults(
116 const std::vector<FragmentResult::ptr> &results,
117 const std::string &KeySetFilename,
118 size_t NoAtoms)
119{
120 EnergyMatrix Energy;
121 EnergyMatrix EnergyFragments;
122 ForceMatrix Force;
123 ForceMatrix ForceFragments;
124 KeySetsContainer KeySet;
125
126 // align fragments
127 std::map< JobId_t, size_t > MatrixNrLookup;
128 size_t FragmentCounter = 0;
129 {
130 // bring ids in order ...
131 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
132 IdResultMap_t IdResultMap;
133 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
134 iter != results.end(); ++iter) {
135 #ifndef NDEBUG
136 std::pair< IdResultMap_t::iterator, bool> inserter =
137 #endif
138 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
139 ASSERT( inserter.second,
140 "printReceivedMPQCResults() - two results have same id "
141 +toString((*iter)->getId())+".");
142 }
143 // ... and fill lookup
144 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
145 iter != IdResultMap.end(); ++iter)
146 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
147 }
148 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
149
150 // extract results
151 std::vector<MPQCData> fragmentData(results.size());
152 MPQCData combinedData;
153
154 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
155 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
156 iter != results.end(); ++iter) {
157 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
158 MPQCData extractedData;
159 std::stringstream inputstream((*iter)->result);
160 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
161 boost::archive::text_iarchive ia(inputstream);
162 ia >> extractedData;
163 LOG(1, "INFO: extracted data is " << extractedData << ".");
164
165 // place results into EnergyMatrix ...
166 {
167 MatrixContainer::MatrixArray matrix;
168 matrix.resize(1);
169 matrix[0].resize(1, extractedData.energies.total);
170 if (!Energy.AddMatrix(
171 std::string("MPQCJob ")+toString((*iter)->getId()),
172 matrix,
173 MatrixNrLookup[(*iter)->getId()])) {
174 ELOG(1, "Adding energy matrix failed.");
175 return false;
176 }
177 }
178 // ... and ForceMatrix (with two empty columns in front)
179 {
180 MatrixContainer::MatrixArray matrix;
181 const size_t rows = extractedData.forces.size();
182 matrix.resize(rows);
183 for (size_t i=0;i<rows;++i) {
184 const size_t columns = 2+extractedData.forces[i].size();
185 matrix[i].resize(columns, 0.);
186 // for (size_t j=0;j<2;++j)
187 // matrix[i][j] = 0.;
188 for (size_t j=2;j<columns;++j)
189 matrix[i][j] = extractedData.forces[i][j-2];
190 }
191 if (!Force.AddMatrix(
192 std::string("MPQCJob ")+toString((*iter)->getId()),
193 matrix,
194 MatrixNrLookup[(*iter)->getId()])) {
195 ELOG(1, "Adding force matrix failed.");
196 return false;
197 }
198 }
199 }
200 // add one more matrix (not required for energy)
201 MatrixContainer::MatrixArray matrix;
202 matrix.resize(1);
203 matrix[0].resize(1, 0.);
204 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
205 return false;
206 // but for energy because we need to know total number of atoms
207 matrix.resize(NoAtoms);
208 for (size_t i = 0; i< NoAtoms; ++i)
209 matrix[i].resize(2+NDIM, 0.);
210 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
211 return false;
212
213
214 // combine all found data
215 if (!Energy.InitialiseIndices()) return false;
216
217 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
218
219 {
220 std::stringstream filename;
221 filename << FRAGMENTPREFIX << KEYSETFILE;
222 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), filename.str(), Force.MatrixCounter)) return 1;
223 }
224
225 if (!KeySet.ParseManyBodyTerms()) return false;
226
227 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
228 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
229
230 if(!Energy.SetLastMatrix(0., 0)) return false;
231 if(!Force.SetLastMatrix(0., 2)) return false;
232
233 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
234 // --------- sum up energy --------------------
235 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
236 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
237 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
238
239 // --------- sum up Forces --------------------
240 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
241 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
242 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
243 }
244
245 // for debugging print resulting energy and forces
246 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
247 std::stringstream output;
248 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
249 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
250 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
251 output << "\n";
252 }
253 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
254
255 return true;
256}
257
258
259/** Helper function to get number of atoms somehow.
260 *
261 * Here, we just parse the number of lines in the adjacency file as
262 * it should correspond to the number of atoms, except when some atoms
263 * are not bonded, but then fragmentation makes no sense.
264 *
265 * @param path path to the adjacency file
266 */
267size_t getNoAtomsFromAdjacencyFile(const std::string &path)
268{
269 size_t NoAtoms = 0;
270
271 // parse in special file to get atom count (from line count)
272 std::string filename(path);
273 filename += FRAGMENTPREFIX;
274 filename += ADJACENCYFILE;
275 std::ifstream adjacency(filename.c_str());
276 if (adjacency.fail()) {
277 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
278 return false;
279 }
280 std::string buffer;
281 while (getline(adjacency, buffer))
282 NoAtoms++;
283 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
284
285 return NoAtoms;
286}
287
288/** Creates a MPQCCommandJob out of give \a command with \a argument.
289 *
290 * @param controller reference to controller to add jobs
291 * @param ControllerInfo information on the job
292 */
293void AddJobs(FragmentController &controller, const ControllerOptions_MPQCCommandJob &ControllerInfo)
294{
295 std::vector<FragmentJob::ptr> jobs;
296 for (std::vector< std::string >::const_iterator iter = ControllerInfo.jobfiles.begin();
297 iter != ControllerInfo.jobfiles.end(); ++iter) {
298 const JobId_t next_id = controller.getAvailableId();
299 const std::string &filename = *iter;
300 LOG(1, "INFO: Creating MPQCCommandJob with filename '"
301 +filename+"', and id "+toString(next_id)+".");
302 parsejob(jobs, ControllerInfo.executable, filename, next_id);
303 }
304 controller.addJobs(jobs);
305 controller.sendJobs(ControllerInfo.server, ControllerInfo.serverport);
306}
307
308inline std::vector<std::string> getListOfCommands(const ControllerCommandRegistry &ControllerCommands)
309{
310 std::vector<std::string> Commands;
311 for (ControllerCommandRegistry::const_iterator iter = ControllerCommands.getBeginIter();
312 iter != ControllerCommands.getEndIter(); ++iter)
313 Commands.push_back(iter->first);
314
315 return Commands;
316}
317
318ControllerOptions *controller_MPQCCommandJob::allocateControllerInfo()
319{
320 return new ControllerOptions_MPQCCommandJob();
321}
322
323void controller_MPQCCommandJob::addSpecificCommands(
324 boost::function<void (ControllerCommand *)> &registrator,
325 FragmentController &controller,
326 ControllerOptions &ControllerInfo)
327{
328 ControllerOptions_MPQCCommandJob &CI =
329 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
330 registrator(new ControllerCommand("addjobs",
331 boost::assign::list_of< ControllerCommand::commands_t >
332 (boost::bind(&FragmentController::requestIds,
333 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport),
334 boost::bind(&std::vector<std::string>::size, boost::cref(CI.jobfiles))))
335 (boost::bind(&AddJobs, boost::ref(controller), boost::cref(CI)))
336 ));
337 registrator(new ControllerCommand("receiveresults",
338 boost::assign::list_of< ControllerCommand::commands_t >
339 (boost::bind(&FragmentController::receiveResults,
340 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
341 (boost::bind(&printReceivedResults,
342 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller))))
343 ));
344 registrator(new ControllerCommand("receivempqc",
345 boost::assign::list_of< ControllerCommand::commands_t >
346 (boost::bind(&FragmentController_JobIdProxy::setJobids,
347 boost::ref(controller), boost::cref(CI.ids)))
348 (boost::bind(&FragmentController::receiveResults,
349 boost::ref(controller), boost::cref(ControllerInfo.server), boost::cref(ControllerInfo.serverport)))
350 (boost::bind(&printReceivedMPQCResults,
351 boost::bind(&FragmentController::getReceivedResults, boost::ref(controller)),
352 boost::cref(CI.fragmentpath),
353 boost::bind(&getNoAtomsFromAdjacencyFile, boost::cref(CI.fragmentpath))))
354 ));
355}
356
357void controller_MPQCCommandJob::addSpecificOptions(
358 boost::program_options::options_description_easy_init option)
359{
360 option
361 ("executable", boost::program_options::value< std::string >(), "executable for commands 'createjobs'")
362 ("fragment-path", boost::program_options::value< std::string >(), "path to fragment files for 'receivempqc'")
363 ("jobfiles", boost::program_options::value< std::vector< std::string > >()->multitoken(), "list of files as single argument toexecutable for 'addjobs'")
364 ("ids", boost::program_options::value< std::vector< JobId_t > >()->multitoken(), "list of jobids to request from server for 'receivempqc'")
365 ;
366}
367
368int controller_MPQCCommandJob::addOtherParsings(
369 ControllerOptions &ControllerInfo,
370 boost::program_options::variables_map &vm)
371{
372 ControllerOptions_MPQCCommandJob &CI =
373 reinterpret_cast<ControllerOptions_MPQCCommandJob &>(ControllerInfo);
374 int status = 0;
375 status = CI.parseExecutable(vm);
376 if (status) return status;
377 status = CI.parseFragmentpath(vm);
378 if (status) return status;
379 status = CI.parseJobfiles(vm);
380 if (status) return status;
381 status = CI.parseIds(vm);
382 return status;
383}
Note: See TracBrowser for help on using the repository browser.