source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 6ca578

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

Simple use of OrthogonalSummation in FragmentationAutomationAction.

  • so far, we just make use of the already parsed in keysets, translate it to IndexSets and sum up the energy.total found in MPQCData.
  • note that internal MPQCJob just creates empty MPQCData regardless of the actual job.
  • TESTFIX: regression tests tests/JobMarket/molecuilderrun does not check for the resulting energy and forces as we only get empty results.
  • libMolecuilderUI now requires libMolecuilderFragmentationSummation.
  • Property mode set to 100644
File size: 15.4 KB
Line 
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 <boost/assign.hpp>
42
43#include "CodePatterns/Assert.hpp"
44#include "CodePatterns/Info.hpp"
45#include "CodePatterns/Log.hpp"
46#include "JobMarket/Controller/FragmentController.hpp"
47#include "JobMarket/Jobs/FragmentJob.hpp"
48
49#include "Atom/atom.hpp"
50#include "Fragmentation/EnergyMatrix.hpp"
51#include "Fragmentation/ForceMatrix.hpp"
52#include "Fragmentation/Fragmentation.hpp"
53#include "Fragmentation/HydrogenSaturation_enum.hpp"
54#include "Fragmentation/KeySet.hpp"
55#include "Fragmentation/KeySetsContainer.hpp"
56#include "Fragmentation/Summation/OrthogonalSummation.hpp"
57#include "Fragmentation/Summation/SetValue.hpp"
58#include "Graph/DepthFirstSearchAnalysis.hpp"
59#include "Jobs/MPQCJob.hpp"
60#include "Jobs/MPQCData.hpp"
61#include "molecule.hpp"
62#include "World.hpp"
63
64#include <iostream>
65#include <string>
66#include <vector>
67
68#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
69
70using namespace MoleCuilder;
71
72using namespace boost::assign;
73
74// and construct the stuff
75#include "FragmentationAutomationAction.def"
76#include "Action_impl_pre.hpp"
77/** =========== define the function ====================== */
78
79class controller_AddOn;
80
81// needs to be defined for using the FragmentController
82controller_AddOn *getAddOn()
83{
84 return NULL;
85}
86
87/** Creates a MPQCCommandJob with argument \a filename.
88 *
89 * @param jobs created job is added to this vector
90 * @param command mpqc command to execute
91 * @param filename filename being argument to job
92 * @param nextid id for this job
93 */
94void parsejob(
95 std::vector<FragmentJob::ptr> &jobs,
96 const std::string &command,
97 const std::string &filename,
98 const JobId_t nextid)
99{
100 std::ifstream file;
101 file.open(filename.c_str());
102 ASSERT( file.good(), "parsejob() - file "+filename+" does not exist.");
103 std::string output((std::istreambuf_iterator<char>(file)),
104 std::istreambuf_iterator<char>());
105 FragmentJob::ptr testJob( new MPQCJob(nextid, output) );
106 jobs.push_back(testJob);
107 file.close();
108 LOG(1, "INFO: Added MPQCCommandJob from file "+filename+".");
109}
110
111/** Helper function to get number of atoms somehow.
112 *
113 * Here, we just parse the number of lines in the adjacency file as
114 * it should correspond to the number of atoms, except when some atoms
115 * are not bonded, but then fragmentation makes no sense.
116 *
117 * @param path path to the adjacency file
118 */
119size_t getNoAtomsFromAdjacencyFile(const std::string &path)
120{
121 size_t NoAtoms = 0;
122
123 // parse in special file to get atom count (from line count)
124 std::string filename(path);
125 filename += FRAGMENTPREFIX;
126 filename += ADJACENCYFILE;
127 std::ifstream adjacency(filename.c_str());
128 if (adjacency.fail()) {
129 LOG(0, endl << "getNoAtomsFromAdjacencyFile() - Unable to open " << filename << ", is the directory correct?");
130 return false;
131 }
132 std::string buffer;
133 while (getline(adjacency, buffer))
134 NoAtoms++;
135 LOG(1, "INFO: There are " << NoAtoms << " atoms.");
136
137 return NoAtoms;
138}
139
140
141/** Print MPQCData from received results.
142 *
143 * @param results received results to extract MPQCData from
144 * @param KeySetFilename filename with keysets to associate forces correctly
145 * @param NoAtoms total number of atoms
146 */
147bool printReceivedMPQCResults(
148 const std::vector<FragmentResult::ptr> &results,
149 const std::string &KeySetFilename,
150 size_t NoAtoms)
151{
152 EnergyMatrix Energy;
153 EnergyMatrix EnergyFragments;
154 ForceMatrix Force;
155 ForceMatrix ForceFragments;
156
157 // align fragments
158 std::map< JobId_t, size_t > MatrixNrLookup;
159 size_t FragmentCounter = 0;
160 {
161 // bring ids in order ...
162 typedef std::map< JobId_t, FragmentResult::ptr> IdResultMap_t;
163 IdResultMap_t IdResultMap;
164 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
165 iter != results.end(); ++iter) {
166 #ifndef NDEBUG
167 std::pair< IdResultMap_t::iterator, bool> inserter =
168 #endif
169 IdResultMap.insert( make_pair((*iter)->getId(), *iter) );
170 ASSERT( inserter.second,
171 "printReceivedMPQCResults() - two results have same id "
172 +toString((*iter)->getId())+".");
173 }
174 // ... and fill lookup
175 for(IdResultMap_t::const_iterator iter = IdResultMap.begin();
176 iter != IdResultMap.end(); ++iter)
177 MatrixNrLookup.insert( make_pair(iter->first, FragmentCounter++) );
178 }
179 LOG(1, "INFO: There are " << FragmentCounter << " fragments.");
180
181 // extract results
182 std::vector<MPQCData> fragmentData(results.size());
183 MPQCData combinedData;
184
185 LOG(2, "DEBUG: Parsing now through " << results.size() << " results.");
186 for (std::vector<FragmentResult::ptr>::const_iterator iter = results.begin();
187 iter != results.end(); ++iter) {
188 LOG(1, "RESULT: job #"+toString((*iter)->getId())+": "+toString((*iter)->result));
189 MPQCData extractedData;
190 std::stringstream inputstream((*iter)->result);
191 LOG(2, "DEBUG: First 50 characters FragmentResult's string: "+(*iter)->result.substr(0, 50));
192 boost::archive::text_iarchive ia(inputstream);
193 ia >> extractedData;
194 LOG(1, "INFO: extracted data is " << extractedData << ".");
195
196 // place results into EnergyMatrix ...
197 {
198 MatrixContainer::MatrixArray matrix;
199 matrix.resize(1);
200 matrix[0].resize(1, extractedData.energies.total);
201 if (!Energy.AddMatrix(
202 std::string("MPQCJob ")+toString((*iter)->getId()),
203 matrix,
204 MatrixNrLookup[(*iter)->getId()])) {
205 ELOG(1, "Adding energy matrix failed.");
206 return false;
207 }
208 }
209 // ... and ForceMatrix (with two empty columns in front)
210 {
211 MatrixContainer::MatrixArray matrix;
212 const size_t rows = extractedData.forces.size();
213 matrix.resize(rows);
214 for (size_t i=0;i<rows;++i) {
215 const size_t columns = 2+extractedData.forces[i].size();
216 matrix[i].resize(columns, 0.);
217 // for (size_t j=0;j<2;++j)
218 // matrix[i][j] = 0.;
219 for (size_t j=2;j<columns;++j)
220 matrix[i][j] = extractedData.forces[i][j-2];
221 }
222 if (!Force.AddMatrix(
223 std::string("MPQCJob ")+toString((*iter)->getId()),
224 matrix,
225 MatrixNrLookup[(*iter)->getId()])) {
226 ELOG(1, "Adding force matrix failed.");
227 return false;
228 }
229 }
230 }
231 // add one more matrix (not required for energy)
232 MatrixContainer::MatrixArray matrix;
233 matrix.resize(1);
234 matrix[0].resize(1, 0.);
235 if (!Energy.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
236 return false;
237 // but for energy because we need to know total number of atoms
238 matrix.resize(NoAtoms);
239 for (size_t i = 0; i< NoAtoms; ++i)
240 matrix[i].resize(2+NDIM, 0.);
241 if (!Force.AddMatrix(std::string("MPQCJob total"), matrix, FragmentCounter))
242 return false;
243
244 // initialise indices
245 KeySetsContainer KeySet;
246 if (!Energy.InitialiseIndices()) return false;
247
248 if (!Force.ParseIndices(KeySetFilename.c_str())) return false;
249
250 if (!KeySet.ParseKeySets(KeySetFilename.c_str(), Force.RowCounter, Force.MatrixCounter)) return false;
251
252 /// prepare for OrthogonalSummation
253
254 // gather all present indices in AllIndices
255 IndexSet::ptr AllIndices(new IndexSet);
256 for (KeySetsContainer::ArrayOfIntVectors::const_iterator iter = KeySet.KeySets.begin();
257 iter != KeySet.KeySets.end(); ++iter)
258 for(KeySetsContainer::IntVector::const_iterator keyiter = (*iter).begin();
259 keyiter != (*iter).end(); ++keyiter) {
260 if (*keyiter != -1)
261 (*AllIndices) += *keyiter;
262 }
263 LOG(1, "INFO: AllIndices is " << AllIndices << ".");
264 // create container with all keysets
265 IndexSetContainer::ptr container(new IndexSetContainer(AllIndices));
266 for (KeySetsContainer::ArrayOfIntVectors::const_iterator iter = KeySet.KeySets.begin();
267 iter != KeySet.KeySets.end(); ++iter) {
268 IndexSet tempset;
269 for(KeySetsContainer::IntVector::const_iterator keyiter = (*iter).begin();
270 keyiter != (*iter).end(); ++keyiter)
271 if (*keyiter != -1)
272 tempset += *keyiter;
273 container->insert(tempset);
274 }
275 // create the map of all keysets
276 SubsetMap::ptr subsetmap(new SubsetMap(*container));
277
278 // associate each index set with its value
279 {
280 const IndexSetContainer::Container_t &_container = container->getContainer();
281 OrthogonalSummation<double>::InputSets_t indices(_container.begin(), _container.end());
282 OrthogonalSummation<double>::InputValues_t values(_container.size(), 0.);
283 std::vector<MPQCData>::const_iterator dataiter = fragmentData.begin();
284 std::vector<FragmentResult::ptr>::const_iterator resultiter = results.begin();
285 for (; dataiter != fragmentData.end(); ++dataiter, ++resultiter) {
286 const MPQCData &extractedData = *dataiter;
287 values[ MatrixNrLookup[(*resultiter)->getId()] ] = extractedData.energies.total;
288 }
289
290 // create the summation functor and evaluate
291 OrthogonalSummation<double> OS(indices, values, subsetmap);
292 const double energyresult = OS();
293 LOG(0, "STATUS: Resulting energy is " << energyresult << ".");
294 }
295
296 // combine all found data
297 if (!KeySet.ParseManyBodyTerms()) return false;
298
299 if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return false;
300 if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return false;
301
302 if(!Energy.SetLastMatrix(0., 0)) return false;
303 if(!Force.SetLastMatrix(0., 2)) return false;
304
305 for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
306 // --------- sum up energy --------------------
307 LOG(1, "INFO: Summing energy of order " << BondOrder+1 << " ...");
308 if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return false;
309 if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return false;
310
311 // --------- sum up Forces --------------------
312 LOG(1, "INFO: Summing forces of order " << BondOrder+1 << " ...");
313 if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return false;
314 if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return false;
315 }
316
317 // for debugging print resulting energy and forces
318 LOG(1, "INFO: Resulting energy is " << Energy.Matrix[ FragmentCounter ][0][0]);
319 std::stringstream output;
320 for (int i=0; i< Force.RowCounter[FragmentCounter]; ++i) {
321 for (int j=0; j< Force.ColumnCounter[FragmentCounter]; ++j)
322 output << Force.Matrix[ FragmentCounter ][i][j] << " ";
323 output << "\n";
324 }
325 LOG(1, "INFO: Resulting forces are " << std::endl << output.str());
326
327 return true;
328}
329
330
331void RunService(
332 boost::asio::io_service &io_service,
333 std::string message)
334{
335 message = std::string("io_service: ") + message;
336 io_service.reset();
337 Info info(message.c_str());
338 io_service.run();
339}
340
341void requestIds(
342 FragmentController &controller,
343 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
344 const size_t numberjobs)
345{
346 controller.requestIds(params.host.get(), params.port.get(), numberjobs);
347}
348
349bool createJobsFromFiles(
350 FragmentController &controller,
351 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
352 const std::vector< boost::filesystem::path > &jobfiles)
353{
354 std::vector<FragmentJob::ptr> jobs;
355 for (std::vector< boost::filesystem::path >::const_iterator iter = jobfiles.begin();
356 iter != jobfiles .end(); ++iter) {
357 const std::string &filename = (*iter).string();
358 if (boost::filesystem::exists(filename)) {
359 const JobId_t next_id = controller.getAvailableId();
360 LOG(1, "INFO: Creating MPQCCommandJob with filename'"
361 +filename+"', and id "+toString(next_id)+".");
362 parsejob(jobs, params.executable.get().string(), filename, next_id);
363 } else {
364 ELOG(1, "Fragment job "+filename+" does not exist.");
365 return false;
366 }
367 }
368 controller.addJobs(jobs);
369 controller.sendJobs(params.host.get(), params.port.get());
370 return true;
371}
372
373void WaitforResults(
374 boost::asio::io_service &io_service,
375 FragmentController &controller,
376 const FragmentationFragmentationAutomationAction::FragmentationFragmentationAutomationParameters &params,
377 const size_t NoExpectedResults
378 )
379{
380 size_t NoCalculatedResults = 0;
381 while (NoCalculatedResults != NoExpectedResults) {
382 // wait a bit
383 boost::asio::deadline_timer timer(io_service);
384 timer.expires_from_now(boost::posix_time::milliseconds(500));
385 timer.wait();
386 // then request status
387 controller.checkResults(params.host.get(), params.port.get());
388 RunService(io_service, "Checking on results");
389
390 const std::pair<size_t, size_t> JobStatus = controller.getJobStatus();
391 LOG(1, "INFO: #" << JobStatus.first << " are waiting in the queue and #" << JobStatus.second << " jobs are calculated so far.");
392 NoCalculatedResults = JobStatus.second;
393 }
394}
395
396
397Action::state_ptr FragmentationFragmentationAutomationAction::performCall() {
398 boost::asio::io_service io_service;
399 FragmentController controller(io_service);
400
401 // TODO: Have io_service run in second thread and merge with current again eventually
402
403 // Phase One: obtain ids
404 std::vector< boost::filesystem::path > jobfiles = params.jobfiles.get();
405 requestIds(controller, params, jobfiles.size());
406 RunService(io_service, "Requesting ids");
407
408 // Phase Two: create and add jobs
409 if (!createJobsFromFiles(controller, params, jobfiles))
410 return Action::failure;
411 RunService(io_service, "Adding jobs");
412
413 // Phase Three: calculate result
414 WaitforResults(io_service, controller, params, jobfiles.size());
415
416 // Phase Three: get result
417 controller.receiveResults(params.host.get(), params.port.get());
418 RunService(io_service, "Phase Four");
419
420 // Final phase: print result
421 {
422 LOG(1, "INFO: Parsing fragment files from " << params.path.get() << ".");
423 std::vector<FragmentResult::ptr> results = controller.getReceivedResults();
424 printReceivedMPQCResults(
425 results,
426 params.path.get(),
427 getNoAtomsFromAdjacencyFile(params.path.get()));
428 }
429 size_t Exitflag = controller.getExitflag();
430
431 return (Exitflag == 0) ? Action::success : Action::failure;
432}
433
434Action::state_ptr FragmentationFragmentationAutomationAction::performUndo(Action::state_ptr _state) {
435 return Action::success;
436}
437
438Action::state_ptr FragmentationFragmentationAutomationAction::performRedo(Action::state_ptr _state){
439 return Action::success;
440}
441
442bool FragmentationFragmentationAutomationAction::canUndo() {
443 return false;
444}
445
446bool FragmentationFragmentationAutomationAction::shouldUndo() {
447 return false;
448}
449/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.