source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 6294b6

Candidate_v1.7.0 stable
Last change on this file since 6294b6 was 6294b6, checked in by Frederik Heber <frederik.heber@…>, 2 months ago

MPQCJob mutes output on verbosity level 0 and unmutes else.

  • we redirect stdout to /dev/null when verbose level of 0 is set.
  • passing on verbosity level to MPQCJob.
  • Tested that the verbosity can be changed per executed job and will not be touched with a job of the same verbosity level.
  • Property mode set to 100644
File size: 21.2 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 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * FragmentationAutomationAction.cpp
26 *
27 * Created on: May 18, 2012
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include <boost/archive/text_iarchive.hpp>
37// boost asio needs specific operator new
38#include <boost/asio.hpp>
39
40//#include "CodePatterns/MemDebug.hpp"
41
42//// include headers that implement a archive in simple text format
43#include <boost/archive/text_oarchive.hpp>
44#include <boost/archive/text_iarchive.hpp>
45
46//
47//#include <boost/mpl/remove.hpp>
48//#include <boost/lambda/lambda.hpp>
49
50//#include <iostream>
51
52#include "CodePatterns/Assert.hpp"
53#include "CodePatterns/Info.hpp"
54#include "CodePatterns/Log.hpp"
55
56#ifdef HAVE_JOBMARKET
57#include "JobMarket/Jobs/FragmentJob.hpp"
58#else
59#include "Jobs/JobMarket/FragmentJob.hpp"
60#endif
61
62#include "Fragmentation/Automation/FragmentJobQueue.hpp"
63#ifdef HAVE_JOBMARKET
64#include "Fragmentation/Automation/MPQCFragmentController.hpp"
65#else
66#include "Fragmentation/Automation/MPQCCommandFragmentController.hpp"
67#endif
68#include "Fragmentation/Exporters/ExportGraph_ToJobs.hpp"
69#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
70#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
71#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
72#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
73#include "Fragmentation/Summation/Containers/MPQCData.hpp"
74#include "Fragmentation/KeySetsContainer.hpp"
75#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
76#include "Fragmentation/Automation/VMGDebugGridFragmentController.hpp"
77#include "Fragmentation/Automation/VMGFragmentController.hpp"
78#include "Fragmentation/Summation/Containers/GridDownsampler.hpp"
79#include "Fragmentation/Summation/Containers/VMGData.hpp"
80#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
81#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
82#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
83#endif
84#include "World.hpp"
85
86#include <boost/bind.hpp>
87#include <boost/thread.hpp>
88#include <fstream>
89#include <iostream>
90#include <string>
91#include <vector>
92
93#include <boost/mpl/for_each.hpp>
94
95#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
96
97using namespace MoleCuilder;
98
99// and construct the stuff
100#include "FragmentationAutomationAction.def"
101#include "Action_impl_pre.hpp"
102/** =========== define the function ====================== */
103
104class controller_AddOn;
105
106// needs to be defined for using the FragmentController
107controller_AddOn *getAddOn()
108{
109 return NULL;
110}
111
112static void updateSteps(Process &p, const size_t step, const size_t total)
113{
114 LOG(1, "There are " << step << " steps out of " << total << " done.");
115 p.setCurrStep(step);
116}
117
118template <class ResultClass>
119std::pair<double, double> getResiduals(const ResultClass &_result)
120{ return std::pair<double, double>(0.,0.); }
121
122std::pair<double, double> getResiduals(const MPQCData &_result)
123{ return std::make_pair(_result.accuracy, _result.desired_accuracy); }
124
125std::pair<double, double> getResiduals(const VMGData &_result)
126{
127 // sensibility check on absolute residual
128 if (_result.residual > 1e-5)
129 ELOG(2, "Encountered absolute residual greater than 1e-5: " << _result.residual);
130 // take smaller value of the two as just one of them needs to be less than precision
131 const double residual = std::min(_result.relative_residual, _result.residual);
132 return std::make_pair(residual, _result.precision);
133}
134
135template <class ResultClass>
136bool checkResults(const typename std::map<JobId_t, ResultClass> &_results)
137{
138 bool result = true;
139 for (typename std::map<JobId_t, ResultClass>::const_iterator iter = _results.begin();
140 iter != _results.end(); ++iter) {
141 std::pair<double, double> residuals = getResiduals(iter->second);
142 if (residuals.second != 0.) {
143 if (residuals.first >= residuals.second) {
144 ELOG(1, "Fragment Job " << iter->first << " converged to " << residuals.first
145 << " instead of " << residuals.second);
146 result = false;
147 }
148 } else {
149 LOG(4, "DEBUG: Not checking accuracy because desired precision not given.");
150 }
151 }
152 return result;
153}
154
155
156#ifdef HAVE_JOBMARKET
157/** This performs a direct sum calculation for the nuclei-nuclei interaction energy
158 * and forces for each fragment contained in \a shortrangedata.
159 *
160 * Results are (re)placed in \a _longrangedata.
161 *
162 * \warning This is only valid for fully open boundary conditions.
163 *
164 * \param _shortrangedata containing information on position and charges per fragment
165 * \param _longrangedata containing energy and forces on return
166 */
167/* Is not used currently, commented out to disable warning message.
168static void calculateNucleiNucleiLongRangeContribution(
169 const std::map<JobId_t, MPQCData> &_shortrangedata,
170 std::map<JobId_t, VMGData>& _longrangedata
171 )
172{
173 ASSERT( _shortrangedata.size() == _longrangedata.size(),
174 "calculateNucleiNucleiLongRangeContribution() - shortrange and longrange data have inequal size.");
175 std::map<JobId_t, VMGData>::iterator longrangeiter = _longrangedata.begin();
176 std::map<JobId_t, MPQCData>::const_iterator iter = _shortrangedata.begin();
177 for (;iter != _shortrangedata.end(); ++iter, ++longrangeiter) {
178 const MPQCData &data = iter->second;
179 VMGData &longrange_data = longrangeiter->second;
180 // set long-range contributions to zero
181 longrange_data.nuclei_long = 0.;
182 longrange_data.forces.clear();
183 longrange_data.forces.resize(data.positions.size(), FragmentForces::force_t(3,0.));
184 longrange_data.hasForces = true;
185 // go through positions and evaluate sum naively
186 ASSERT( data.positions.size() == data.charges.size(),
187 "calculateNucleiNucleiLongRangeContribution() - positions and charges differ in size.");
188 std::vector< std::vector<double> >::const_iterator positer = data.positions.begin();
189 std::vector< double >::const_iterator chargeiter = data.charges.begin();
190 FragmentForces::iterator forceiter = longrange_data.forces.begin();
191 for (; (positer != data.positions.end()) && (chargeiter != data.charges.end());
192 ++positer, ++chargeiter, ++forceiter) {
193 ASSERT( positer->size() == NDIM,
194 "calculateNucleiNucleiLongRangeContribution() - position "
195 +toString(std::distance(data.positions.begin(), positer))+" has not 3 components.");
196 const Vector position((*positer)[0], (*positer)[1], (*positer)[2]);
197
198 std::vector< std::vector<double> >::const_iterator otherpositer = data.positions.begin();
199 std::vector< double >::const_iterator otherchargeiter = data.charges.begin();
200 for (; (otherpositer != data.positions.end()) && (otherchargeiter != data.charges.end());
201 ++otherpositer, ++otherchargeiter) {
202 if ((positer == otherpositer) || (chargeiter == otherchargeiter))
203 continue;
204 ASSERT( otherpositer->size() == NDIM,
205 "calculateNucleiNucleiLongRangeContribution() - other position "
206 +toString(std::distance(data.positions.begin(), otherpositer))+" has not 3 components.");
207 const Vector otherposition((*otherpositer)[0], (*otherpositer)[1], (*otherpositer)[2]);
208 const Vector distance = position - otherposition;
209 const double invsqrdist = 1./distance.Norm();
210 const double factor = (*otherchargeiter)*invsqrdist*invsqrdist*invsqrdist;
211 (*forceiter)[0] = factor*distance[0];
212 (*forceiter)[1] = factor*distance[1];
213 (*forceiter)[2] = factor*distance[2];
214 longrange_data.nuclei_long += 0.5*(*chargeiter)*(*otherchargeiter)*invsqrdist;
215 }
216 }
217 }
218}
219*/
220#endif
221
222ActionState::ptr FragmentationFragmentationAutomationAction::performCall() {
223 boost::asio::io_service io_service;
224
225 // TODO: Have io_service run in second thread and merge with current again eventually
226
227 FragmentationResultContainer &container =
228 FragmentationResultContainer::getInstance();
229 const KeySetsContainer& keysets = FragmentJobQueue::getInstance().getKeySets();
230 const KeySetsContainer& forcekeysets = FragmentJobQueue::getInstance().getFullKeySets();
231 const FragmentJobQueue::edges_per_fragment_t &edges_per_fragment =
232 FragmentJobQueue::getInstance().getEdgesPerFragment();
233
234 size_t Exitflag = 0;
235 std::map<JobId_t, MPQCData> shortrangedata;
236#ifdef HAVE_JOBMARKET
237 {
238 const size_t NumberJobs = FragmentJobQueue::getInstance().size();
239 MPQCFragmentController mpqccontroller(io_service);
240 mpqccontroller.setHost(params.host.get());
241 mpqccontroller.setPort(params.port.get());
242 // Phase One: obtain ids
243 mpqccontroller.requestIds(NumberJobs);
244 if (mpqccontroller.getExitflag() != 0) {
245 ELOG(1, "Could not request all ids from Server.");
246 return Action::failure;
247 }
248
249 // Phase Two: add MPQCJobs and send
250 const bool AddJobsStatus = mpqccontroller.addJobsFromQueue(
251 params.DoLongrange.get() ? MPQCData::DoSampleDensity : MPQCData::DontSampleDensity,
252 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
253 getVerbosity()
254 );
255 if (AddJobsStatus)
256 LOG(1, "INFO: Added jobs from FragmentJobsQueue.");
257 else {
258 ELOG(1, "Adding jobs failed.");
259 return Action::failure;
260 }
261 mpqccontroller.run();
262
263 // Phase Three: calculate result
264 setMaxSteps(NumberJobs);
265 mpqccontroller.setUpdateHandler(
266 boost::bind(&updateSteps, boost::ref(*this), _1, _2)
267 );
268 start();
269 boost::thread wait_thread(
270 boost::bind(&MPQCFragmentController::waitforResults, boost::ref(mpqccontroller), boost::cref(NumberJobs))
271 );
272 wait_thread.join();
273 stop();
274 if (mpqccontroller.getExitflag() != 0) {
275 ELOG(1, "Could not obtain all results from Server.");
276 return Action::failure;
277 }
278
279 mpqccontroller.getResults(shortrangedata);
280 if (!checkResults(shortrangedata)) {
281 ELOG(1, "At least one of the fragments' energy could not be properly minimized.");
282 return Action::failure;
283 }
284 if (mpqccontroller.getExitflag() != 0) {
285 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag.");
286 return Action::failure;
287 }
288
289 Exitflag += mpqccontroller.getExitflag();
290 }
291#else
292 {
293 const size_t NumberJobs = FragmentJobQueue::getInstance().size();
294 MPQCCommandFragmentController mpqccontroller;
295 // Phase One: obtain ids: not needed, we have infinite pool
296
297 // Phase Two: add MPQCJobs and send
298 const size_t NoJobs = mpqccontroller.addJobsFromQueue(
299 params.DoLongrange.get() ? MPQCData::DoSampleDensity : MPQCData::DontSampleDensity,
300 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
301 params.executable.get().string()
302 );
303 if (NoJobs != NumberJobs) {
304 ELOG(1, "Not all jobs were added succesfully.");
305 return Action::failure;
306 }
307 LOG(1, "INFO: Added " << NoJobs << " from FragmentJobsQueue.");
308
309 // prepare process
310 setMaxSteps(NumberJobs);
311 mpqccontroller.setUpdateHandler(
312 boost::bind(&updateSteps, boost::ref(*this), _1, _2)
313 );
314 start();
315 mpqccontroller.run();
316 stop();
317 if (mpqccontroller.getExitflag() != 0) {
318 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag before getting results.");
319 return Action::failure;
320 }
321
322 // get back the results and place them in shortrangedata
323 mpqccontroller.getResults(shortrangedata);
324 ASSERT( shortrangedata.size() == NumberJobs,
325 "FragmentationFragmentationAutomationAction::performCall() - number of converted results "
326 +toString(shortrangedata.size())+" and number of jobs "+toString(NumberJobs)+ " differ.");
327 if (!checkResults(shortrangedata)) {
328 ELOG(1, "At least one of the fragments' energy could not be properly minimized.");
329 return Action::failure;
330 }
331 if (mpqccontroller.getExitflag() != 0) {
332 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag after getting results.");
333 return Action::failure;
334 }
335
336 Exitflag += mpqccontroller.getExitflag();
337 }
338#endif
339
340#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
341 if (params.DoLongrange.get()) {
342 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() == 0) {
343 STATUS("Please load the full molecule into the world before starting this action.");
344 return Action::failure;
345 }
346
347 // obtain combined charge density
348 std::map<JobId_t, MPQCData> shortrangedata_downsampled;
349 SamplingGridProperties domain(ExportGraph_ToJobs::getDomainGrid(params.level.get()));
350 FragmentationChargeDensity summedChargeDensity(
351 shortrangedata);
352 {
353 SamplingGrid zero_globalgrid(domain);
354 summedChargeDensity(
355 shortrangedata,
356 FragmentJobQueue::getInstance().getKeySets(),
357 zero_globalgrid);
358 }
359 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
360 LOG(1, "INFO: There are " << shortrangedata.size() << " short-range and "
361 << full_sample.size() << " level-wise long-range jobs.");
362
363 // check boundary conditions
364 const BoundaryConditions::Conditions_t &conditions =
365 World::getInstance().getDomain().getConditions();
366 const bool OpenBoundaryConditions =
367 !((conditions[0] == BoundaryConditions::Wrap) &&
368 (conditions[1] == BoundaryConditions::Wrap) &&
369 (conditions[2] == BoundaryConditions::Wrap));
370 LOG(1, std::string("INFO: Using ")
371 << (OpenBoundaryConditions ? "open" : "periodic")
372 << " boundary conditions.");
373
374 // Phase Four: obtain more ids
375 std::map<JobId_t, VMGData> longrangedata;
376 {
377 VMGFragmentController vmgcontroller(io_service);
378 vmgcontroller.setHost(params.host.get());
379 vmgcontroller.setPort(params.port.get());
380 const size_t NoJobs = shortrangedata.size()+full_sample.size();
381 vmgcontroller.requestIds(2*NoJobs);
382 if (vmgcontroller.getExitflag() != 0) {
383 ELOG(1, "VMGFragmentController returned non-zero exit flag on requesting long-range ids.");
384 return Action::failure;
385 }
386
387 // Phase Five a: create VMGJobs for electronic charge distribution
388 const size_t near_field_cells = params.near_field_cells.get();
389 const size_t interpolation_degree = params.interpolation_degree.get();
390 if (!vmgcontroller.createLongRangeJobs(
391 shortrangedata,
392 full_sample,
393 near_field_cells,
394 interpolation_degree,
395 VMGFragmentController::DontSampleParticles,
396 VMGFragmentController::DoTreatGrid,
397 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
398 params.DoPrintDebug.get(),
399 OpenBoundaryConditions,
400 params.DoSmearCharges.get(),
401 false)) {
402 STATUS("Could not create long-range jobs for electronic charge distribution.");
403 return Action::failure;
404 }
405
406 // Phase Six a: calculate result
407 vmgcontroller.waitforResults(NoJobs);
408 if (vmgcontroller.getExitflag() != 0) {
409 ELOG(1, "VMGFragmentController returned non-zero exit flag before getting results.");
410 return Action::failure;
411 }
412 vmgcontroller.getResults(longrangedata);
413 ASSERT( NoJobs == longrangedata.size(),
414 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresults+"
415 +toString(full_sample.size())+"="+toString(NoJobs)
416 +" and first VMGresults "+toString(longrangedata.size())+" don't match.");
417 if (!checkResults(longrangedata)) {
418 ELOG(1, "At least one of the fragments' electronic long-range potential could not be properly minimized.");
419 return Action::failure;
420 }
421 Exitflag += vmgcontroller.getExitflag();
422
423 {
424 std::map<JobId_t, VMGData> longrangedata_both;
425 // Phase Five b: create VMGJobs for nuclei charge distributions
426 const size_t near_field_cells = params.near_field_cells.get();
427 const size_t interpolation_degree = params.interpolation_degree.get();
428 if (!vmgcontroller.createLongRangeJobs(
429 shortrangedata,
430 full_sample,
431 near_field_cells,
432 interpolation_degree,
433 VMGFragmentController::DoSampleParticles,
434 VMGFragmentController::DoTreatGrid,
435 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
436 params.DoPrintDebug.get(),
437 OpenBoundaryConditions,
438 params.DoSmearCharges.get(),
439 params.UseImplicitCharges.get())) {
440 STATUS("Could not create long-range jobs for nuclei charge distribution.");
441 return Action::failure;
442 }
443
444 // Phase Six b: calculate result
445 vmgcontroller.waitforResults(NoJobs);
446 if (vmgcontroller.getExitflag() != 0) {
447 ELOG(1, "VMGFragmentController returned non-zero exit flag before getting results.");
448 return Action::failure;
449 }
450 vmgcontroller.getResults(longrangedata_both);
451 ASSERT( NoJobs == longrangedata_both.size(),
452 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresults+"
453 +toString(full_sample.size())+"="+toString(NoJobs)
454 +" and second VMGresults "+toString(longrangedata_both.size())+" don't match.");
455 if (!checkResults(longrangedata_both)) {
456 ELOG(1, "At least one of the fragments' nuclei long-range potential could not be properly minimized.");
457 return Action::failure;
458 }
459 if (vmgcontroller.getExitflag() != 0) {
460 ELOG(1, "VMGFragmentController returned non-zero exit flag after getting results.");
461 return Action::failure;
462 }
463 Exitflag += vmgcontroller.getExitflag();
464
465 // now replace nuclei-nuclei contribution with values from direct summation (is exact for
466 // open boundary conditions
467 //
468 // NOTE: We need to calculate both_sampled_potential for fitting partial charges,
469 // nowhere else is this quantity needed.
470 //if (OpenBoundaryConditions)
471 // calculateNucleiNucleiLongRangeContribution(shortrangedata, longrangedata_both);
472
473 // go through either data and replace nuclei_long with contribution from both
474 ASSERT( longrangedata.size() == longrangedata_both.size(),
475 "FragmentationFragmentationAutomationAction::performCall() - longrange results have different sizes.");
476 std::map<JobId_t, VMGData>::iterator destiter = longrangedata.begin();
477 std::map<JobId_t, VMGData>::const_iterator srciter = longrangedata_both.begin();
478 for (;destiter != longrangedata.end(); ++srciter, ++destiter) {
479 destiter->second.both_sampled_potential = srciter->second.sampled_potential;
480 destiter->second.nuclei_long = srciter->second.nuclei_long;
481 destiter->second.forces = srciter->second.forces;
482 destiter->second.hasForces = srciter->second.hasForces;
483 }
484 }
485 }
486
487 if (params.DoPrintDebug.get()) {
488 std::map<JobId_t, std::string> debugData;
489 {
490 if (!full_sample.empty()) {
491 // create debug jobs for each level to print the summed-up potential to vtk files
492 VMGDebugGridFragmentController debugcontroller(io_service);
493 debugcontroller.setHost(params.host.get());
494 debugcontroller.setPort(params.port.get());
495 debugcontroller.requestIds(full_sample.size());
496 if (!debugcontroller.createDebugJobs(full_sample, OpenBoundaryConditions)) {
497 STATUS("Could not create debug jobs.");
498 return Action::failure;
499 }
500 debugcontroller.waitforResults(full_sample.size());
501 debugcontroller.getResults(debugData);
502 Exitflag += debugcontroller.getExitflag();
503 }
504 }
505 }
506 container.clear();
507 container.addFullResults(keysets, forcekeysets, edges_per_fragment, shortrangedata, longrangedata);
508 } else {
509 container.clear();
510 container.addShortRangeResults(keysets, forcekeysets, edges_per_fragment, shortrangedata);
511 }
512#else
513 container.clear();
514 container.addShortRangeResults(keysets, forcekeysets, edges_per_fragment, shortrangedata);
515#endif
516
517 // now clear all present jobs as we are done
518 FragmentJobQueue::getInstance().clear();
519
520 if (Exitflag != 0) {
521 STATUS("Controller has returned failure: "+toString(Exitflag));
522 }
523 return (Exitflag == 0) ? Action::success : Action::failure;
524}
525
526ActionState::ptr FragmentationFragmentationAutomationAction::performUndo(ActionState::ptr _state) {
527 return Action::success;
528}
529
530ActionState::ptr FragmentationFragmentationAutomationAction::performRedo(ActionState::ptr _state){
531 return Action::success;
532}
533
534bool FragmentationFragmentationAutomationAction::canUndo() {
535 return false;
536}
537
538bool FragmentationFragmentationAutomationAction::shouldUndo() {
539 return false;
540}
541/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.