1 | /*
|
---|
2 | * Project: MoleCuilder
|
---|
3 | * Description: creates and alters molecular systems
|
---|
4 | * Copyright (C) 2010-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 | * FragmentationAutomationAction.cpp
|
---|
10 | *
|
---|
11 | * Created on: May 18, 2012
|
---|
12 | * Author: heber
|
---|
13 | */
|
---|
14 |
|
---|
15 | // include config.h
|
---|
16 | #ifdef HAVE_CONFIG_H
|
---|
17 | #include <config.h>
|
---|
18 | #endif
|
---|
19 |
|
---|
20 | #include <boost/archive/text_iarchive.hpp>
|
---|
21 | // boost asio needs specific operator new
|
---|
22 | #include <boost/asio.hpp>
|
---|
23 |
|
---|
24 | #include "CodePatterns/MemDebug.hpp"
|
---|
25 |
|
---|
26 | #include "CodePatterns/Info.hpp"
|
---|
27 | #include "CodePatterns/Log.hpp"
|
---|
28 | #include "JobMarket/Controller/FragmentController.hpp"
|
---|
29 | #include "JobMarket/Jobs/FragmentJob.hpp"
|
---|
30 |
|
---|
31 | #include "Atom/atom.hpp"
|
---|
32 | #include "Fragmentation/EnergyMatrix.hpp"
|
---|
33 | #include "Fragmentation/ForceMatrix.hpp"
|
---|
34 | #include "Fragmentation/Fragmentation.hpp"
|
---|
35 | #include "Fragmentation/HydrogenSaturation_enum.hpp"
|
---|
36 | #include "Fragmentation/KeySetsContainer.hpp"
|
---|
37 | #include "Graph/DepthFirstSearchAnalysis.hpp"
|
---|
38 | #include "Jobs/MPQCCommandJob.hpp"
|
---|
39 | #include "molecule.hpp"
|
---|
40 | #include "World.hpp"
|
---|
41 |
|
---|
42 | #include <iostream>
|
---|
43 | #include <string>
|
---|
44 | #include <vector>
|
---|
45 |
|
---|
46 | #include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
|
---|
47 |
|
---|
48 | using namespace MoleCuilder;
|
---|
49 |
|
---|
50 | // and construct the stuff
|
---|
51 | #include "FragmentationAutomationAction.def"
|
---|
52 | #include "Action_impl_pre.hpp"
|
---|
53 | /** =========== define the function ====================== */
|
---|
54 |
|
---|
55 | class controller_AddOn;
|
---|
56 |
|
---|
57 | // needs to be defined for using the FragmentController
|
---|
58 | controller_AddOn *getAddOn()
|
---|
59 | {
|
---|
60 | return NULL;
|
---|
61 | }
|
---|
62 |
|
---|
63 | /** Creates a MPQCCommandJob with argument \a filename.
|
---|
64 | *
|
---|
65 | * @param jobs created job is added to this vector
|
---|
66 | * @param command mpqc command to execute
|
---|
67 | * @param filename filename being argument to job
|
---|
68 | * @param nextid id for this job
|
---|
69 | */
|
---|
70 | void parsejob(
|
---|
71 | std::vector<FragmentJob::ptr> &jobs,
|
---|
72 | const std::string &command,
|
---|
73 | const std::string &filename,
|
---|
74 | const JobId_t nextid)
|
---|
75 | {
|
---|
76 | std::ifstream file;
|
---|
77 | file.open(filename.c_str());
|
---|
78 | ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
|
---|
79 | std::string output((std::istreambuf_iterator<char>(file)),
|
---|
80 | std::istreambuf_iterator<char>());
|
---|
81 | FragmentJob::ptr testJob( new MPQCCommandJob(output, nextid, command) );
|
---|
82 | jobs.push_back(testJob);
|
---|
83 | file.close();
|
---|
84 | LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
|
---|
85 | }
|
---|
86 |
|
---|
87 | /** Helper function to get number of atoms somehow.
|
---|
88 | *
|
---|
89 | * Here, we just parse the number of lines in the adjacency file as
|
---|
90 | * it should correspond to the number of atoms, except when some atoms
|
---|
91 | * are not bonded, but then fragmentation makes no sense.
|
---|
92 | *
|
---|
93 | * @param path path to the adjacency file
|
---|
94 | */
|
---|
95 | size_t getNoAtomsFromAdjacencyFile(const std::string &path)
|
---|
96 | {
|
---|
97 | size_t NoAtoms = 0;
|
---|
98 |
|
---|
99 | // parse in special file to get atom count (from line count)
|
---|
100 | std::string filename(path);
|
---|
101 | filename += FRAGMENTPREFIX;
|
---|
102 | filename += ADJACENCYFILE;
|
---|
103 | std::ifstream adjacency(filename.c_str());
|
---|
104 | if (adjacency.fail()) {
|
---|
105 | LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
|
---|
106 | return false;
|
---|
107 | }
|
---|
108 | std::string buffer;
|
---|
109 | while (getline(adjacency, buffer))
|
---|
110 | NoAtoms++;
|
---|
111 | LOG(1, "INFO: There are " << NoAtoms << " atoms.");
|
---|
112 |
|
---|
113 | return NoAtoms;
|
---|
114 | }
|
---|
115 |
|
---|
116 |
|
---|
117 | /** Print MPQCData from received results.
|
---|
118 | *
|
---|
119 | * @param results received results to extract MPQCData from
|
---|
120 | * @param KeySetFilename filename with keysets to associate forces correctly
|
---|
121 | * @param NoAtoms total number of atoms
|
---|
122 | */
|
---|
123 | bool printReceivedMPQCResults(
|
---|
124 | const std::vector<FragmentResult::ptr> &results,
|
---|
125 | const std::string &KeySetFilename,
|
---|
126 | size_t NoAtoms)
|
---|
127 | {
|
---|
128 | EnergyMatrix Energy;
|
---|
129 | EnergyMatrix EnergyFragments;
|
---|
130 | ForceMatrix Force;
|
---|
131 | ForceMatrix ForceFragments;
|
---|
132 | KeySetsContainer KeySet;
|
---|
133 |
|
---|
134 | // align fragments
|
---|
135 | std::map< JobId_t, size_t > MatrixNrLookup;
|
---|
136 | size_t FragmentCounter = 0;
|
---|
137 | {
|
---|
138 | // bring ids in order ...
|
---|
139 | typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
|
---|
140 | IdResultMap_t IdResultMap;
|
---|
141 | for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
|
---|
142 | iter != results.end(); ++iter) {
|
---|
143 | #ifndef NDEBUG
|
---|
144 | std::pair< IdResultMap_t::iterator, bool> inserter =
|
---|
145 | #endif
|
---|
146 | IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
|
---|
147 | ASSERT( inserter.second,
|
---|
148 | "printReceivedMPQCResults() - two results have same id "
|
---|
149 | +toString((*iter)->getId())+".");
|
---|
150 | }
|
---|
151 | // ... and fill lookup
|
---|
152 | for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
|
---|
153 | iter != IdResultMap.end(); ++iter)
|
---|
154 | MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
|
---|
155 | }
|
---|
156 | LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
|
---|
157 |
|
---|
158 | // extract results
|
---|
159 | std::vector<MPQCData> fragmentData(results.size());
|
---|
160 | MPQCData combinedData;
|
---|
161 |
|
---|
162 | LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
|
---|
163 | for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
|
---|
164 | iter != results.end(); ++iter) {
|
---|
165 | LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
|
---|
166 | MPQCData extractedData;
|
---|
167 | std::stringstream inputstream((*iter)->result);
|
---|
168 | LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
|
---|
169 | boost::archive::text_iarchive ia(inputstream);
|
---|
170 | ia >> extractedData;
|
---|
171 | LOG(1, "INFO: extracted data is " << extractedData << ".");
|
---|
172 |
|
---|
173 | // place results into EnergyMatrix ...
|
---|
174 | {
|
---|
175 | MatrixContainer::MatrixArray matrix;
|
---|
176 | matrix.resize(1);
|
---|
177 | matrix[0].resize(1, extractedData.energy);
|
---|
178 | if (!Energy.AddMatrix(
|
---|
179 | std::string("MPQCJob ")+toString((*iter)->getId()),
|
---|
180 | matrix,
|
---|
181 | MatrixNrLookup[(*iter)->getId()])) {
|
---|
182 | ELOG(1, "Adding energy matrix failed.");
|
---|
183 | return false;
|
---|
184 | }
|
---|
185 | }
|
---|
186 | // ... and ForceMatrix (with two empty columns in front)
|
---|
187 | {
|
---|
188 | MatrixContainer::MatrixArray matrix;
|
---|
189 | const size_t rows = extractedData.forces.size();
|
---|
190 | matrix.resize(rows);
|
---|
191 | for (size_t i=0;i<rows;++i) {
|
---|
192 | const size_t columns = 2+extractedData.forces[i].size();
|
---|
193 | matrix[i].resize(columns, 0.);
|
---|
194 | // for (size_t j=0;j<2;++j)
|
---|
195 | // matrix[i][j] = 0.;
|
---|
196 | for (size_t j=2;j<columns;++j)
|
---|
197 | matrix[i][j] = extractedData.forces[i][j-2];
|
---|
198 | }
|
---|
199 | if (!Force.AddMatrix(
|
---|
200 | std::string("MPQCJob ")+toString((*iter)->getId()),
|
---|
201 | matrix,
|
---|
202 | MatrixNrLookup[(*iter)->getId()])) {
|
---|
203 | ELOG(1, "Adding force matrix failed.");
|
---|
204 | return false;
|
---|
205 | }
|
---|
206 | }
|
---|
207 | }
|
---|
208 | // add one more matrix (not required for energy)
|
---|
209 | MatrixContainer::MatrixArray matrix;
|
---|
210 | matrix.resize(1);
|
---|
211 | matrix[0].resize(1, 0.);
|
---|
212 | if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
|
---|
213 | return false;
|
---|
214 | // but for energy because we need to know total number of atoms
|
---|
215 | matrix.resize(NoAtoms);
|
---|
216 | for (size_t i = 0; i< NoAtoms; ++i)
|
---|
217 | matrix[i].resize(2+NDIM, 0.);
|
---|
218 | if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
|
---|
219 | return false;
|
---|
220 |
|
---|
221 |
|
---|
222 | // combine all found data
|
---|
223 | if (!Energy.InitialiseIndices()) return false;
|
---|
224 |
|
---|
225 | if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
|
---|
226 |
|
---|
227 | if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
|
---|
228 |
|
---|
229 | if (!KeySet.ParseManyBodyTerms()) return false;
|
---|
230 |
|
---|
231 | if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
|
---|
232 | if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
|
---|
233 |
|
---|
234 | if(!Energy.SetLastMatrix(0., 0)) return false;
|
---|
235 | if(!Force.SetLastMatrix(0., 2)) return false;
|
---|
236 |
|
---|
237 | for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
|
---|
238 | // --------- sum up energy --------------------
|
---|
239 | LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
|
---|
240 | if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
|
---|
241 | if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
|
---|
242 |
|
---|
243 | // --------- sum up Forces --------------------
|
---|
244 | LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
|
---|
245 | if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
|
---|
246 | if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
|
---|
247 | }
|
---|
248 |
|
---|
249 | // for debugging print resulting energy and forces
|
---|
250 | LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
|
---|
251 | std::stringstream output;
|
---|
252 | for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
|
---|
253 | for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
|
---|
254 | output << Force.Matrix[ FragmentCounter ][i][j] << " ";
|
---|
255 | output << "\n";
|
---|
256 | }
|
---|
257 | LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
|
---|
258 |
|
---|
259 | return true;
|
---|
260 | }
|
---|
261 |
|
---|
262 | Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
|
---|
263 | boost::asio::io_service io_service;
|
---|
264 | FragmentController controller(io_service);
|
---|
265 |
|
---|
266 | // TODO: Have io_service run in second thread and merge with current again eventually
|
---|
267 |
|
---|
268 | // Phase One: obtain ids
|
---|
269 | controller.requestIds(params.host, params.port, params.jobfiles.size());
|
---|
270 | {
|
---|
271 | io_service.reset();
|
---|
272 | Info info("io_service: Phase One");
|
---|
273 | io_service.run();
|
---|
274 | }
|
---|
275 | // Phase Two: create and add jobs
|
---|
276 | {
|
---|
277 | std::vector<FragmentJob::ptr> jobs;
|
---|
278 | for (std::vector< boost::filesystem::path >::const_iterator iter = params.jobfiles.begin();
|
---|
279 | iter != params.jobfiles.end(); ++iter) {
|
---|
280 | const std::string &filename = (*iter).string();
|
---|
281 | if (boost::filesystem::exists(filename)) {
|
---|
282 | const JobId_t next_id = controller.getAvailableId();
|
---|
283 | LOG(1, "INFO: Creating MPQCCommandJob with filename'"
|
---|
284 | +filename+"', and id "+toString(next_id)+".");
|
---|
285 | parsejob(jobs, params.executable.string(), filename, next_id);
|
---|
286 | } else {
|
---|
287 | ELOG(1, "Fragment job "+filename+" does not exist.");
|
---|
288 | return Action::failure;
|
---|
289 | }
|
---|
290 | }
|
---|
291 | controller.addJobs(jobs);
|
---|
292 | controller.sendJobs(params.host, params.port);
|
---|
293 | }
|
---|
294 | {
|
---|
295 | io_service.reset();
|
---|
296 | Info info("io_service: Phase Two");
|
---|
297 | io_service.run();
|
---|
298 | }
|
---|
299 | // Phase Three: calculate result
|
---|
300 | size_t NoCalculatedResults = 0;
|
---|
301 | while (NoCalculatedResults != params.jobfiles.size()) {
|
---|
302 | // wait a bit
|
---|
303 | boost::asio::deadline_timer timer(io_service);
|
---|
304 | timer.expires_from_now(boost::posix_time::milliseconds(500));
|
---|
305 | timer.wait();
|
---|
306 | // then request status
|
---|
307 | controller.checkResults(params.host, params.port);
|
---|
308 | {
|
---|
309 | io_service.reset();
|
---|
310 | Info info("io_service: Phase Three");
|
---|
311 | io_service.run();
|
---|
312 | }
|
---|
313 | const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
|
---|
314 | LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
|
---|
315 | NoCalculatedResults = JobStatus.second;
|
---|
316 | }
|
---|
317 | // Phase Three: get result
|
---|
318 | controller.receiveResults(params.host, params.port);
|
---|
319 | {
|
---|
320 | io_service.reset();
|
---|
321 | Info info("io_service: Phase Four");
|
---|
322 | io_service.run();
|
---|
323 | }
|
---|
324 | // Final phase: print result
|
---|
325 | {
|
---|
326 | LOG(1, "INFO: Parsing fragment files from " << params.path << ".");
|
---|
327 | std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
|
---|
328 | printReceivedMPQCResults(
|
---|
329 | results,
|
---|
330 | params.path,
|
---|
331 | getNoAtomsFromAdjacencyFile(params.path));
|
---|
332 | }
|
---|
333 | size_t Exitflag = controller.getExitflag();
|
---|
334 |
|
---|
335 | return (Exitflag == 0) ? Action::success : Action::failure;
|
---|
336 | }
|
---|
337 |
|
---|
338 | Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
|
---|
339 | return Action::success;
|
---|
340 | }
|
---|
341 |
|
---|
342 | Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
|
---|
343 | return Action::success;
|
---|
344 | }
|
---|
345 |
|
---|
346 | bool FragmentationFragmentationAutomationAction::canUndo() {
|
---|
347 | return false;
|
---|
348 | }
|
---|
349 |
|
---|
350 | bool FragmentationFragmentationAutomationAction::shouldUndo() {
|
---|
351 | return false;
|
---|
352 | }
|
---|
353 | /** =========== end of function ====================== */
|
---|