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