source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 965e2f

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

Added OrthogonalSummation of eigenvalues as Histogram to FragmentationAutomationAction.

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