source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ f0dea0

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults 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_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 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 f0dea0 was f0dea0, checked in by Frederik Heber <heber@…>, 9 years ago

FragmentationAutomationAction checks FragmentResults for non-zero exit status.

  • action fails in this case and the respective job is listed with reached and required precision.
  • Property mode set to 100644
File size: 16.6 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/Summation/Containers/FragmentationChargeDensity.hpp"
69#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
70#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
71#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
72#include "Fragmentation/Summation/Containers/MPQCData.hpp"
73#include "Fragmentation/KeySetsContainer.hpp"
74#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
75#include "Fragmentation/Automation/VMGDebugGridFragmentController.hpp"
76#include "Fragmentation/Automation/VMGFragmentController.hpp"
77#include "Fragmentation/Summation/Containers/VMGData.hpp"
78#include "Fragmentation/Summation/Containers/VMGDataFused.hpp"
79#include "Fragmentation/Summation/Containers/VMGDataMap.hpp"
80#include "Fragmentation/Summation/Containers/VMGData_printKeyNames.hpp"
81#endif
82#include "World.hpp"
83
84#include <boost/bind.hpp>
85#include <boost/thread.hpp>
86#include <fstream>
87#include <iostream>
88#include <string>
89#include <vector>
90
91#include <boost/mpl/for_each.hpp>
92
93#include "Actions/FragmentationAction/FragmentationAutomationAction.hpp"
94
95using namespace MoleCuilder;
96
97// and construct the stuff
98#include "FragmentationAutomationAction.def"
99#include "Action_impl_pre.hpp"
100/** =========== define the function ====================== */
101
102class controller_AddOn;
103
104// needs to be defined for using the FragmentController
105controller_AddOn *getAddOn()
106{
107 return NULL;
108}
109
110static void updateSteps(Process &p, const size_t step, const size_t total)
111{
112 LOG(1, "There are " << step << " steps out of " << total << " done.");
113 p.setCurrStep(step);
114}
115
116template <class ResultClass>
117std::pair<double, double> getResiduals(const ResultClass &_result)
118{ return std::pair<double, double>(0.,0.); }
119
120std::pair<double, double> getResiduals(const MPQCData &_result)
121{ return std::make_pair(_result.accuracy, _result.desired_accuracy); }
122
123std::pair<double, double> getResiduals(const VMGData &_result)
124{ return std::make_pair(_result.relative_residual, _result.precision); }
125
126template <class ResultClass>
127bool checkResults(const typename std::map<JobId_t, ResultClass> &_results)
128{
129 bool result = true;
130 for (typename std::map<JobId_t, ResultClass>::const_iterator iter = _results.begin();
131 iter != _results.end(); ++iter) {
132 std::pair<double, double> residuals = getResiduals(iter->second);
133 if (residuals.second != 0.) {
134 if (residuals.first >= residuals.second) {
135 ELOG(1, "Fragment Job " << iter->first << " converged to " << residuals.first
136 << " instead of " << residuals.second);
137 result = false;
138 }
139 } else {
140 LOG(4, "DEBUG: Not checking accuracy because desired precision not given.");
141 }
142 }
143 return result;
144}
145
146ActionState::ptr FragmentationFragmentationAutomationAction::performCall() {
147 boost::asio::io_service io_service;
148
149 // TODO: Have io_service run in second thread and merge with current again eventually
150
151 FragmentationResultContainer &container =
152 FragmentationResultContainer::getInstance();
153 const KeySetsContainer& keysets = FragmentJobQueue::getInstance().getKeySets();
154 const KeySetsContainer& forcekeysets = FragmentJobQueue::getInstance().getFullKeySets();
155
156 size_t Exitflag = 0;
157 std::map<JobId_t, MPQCData> shortrangedata;
158#ifdef HAVE_JOBMARKET
159 {
160 const size_t NumberJobs = FragmentJobQueue::getInstance().size();
161 MPQCFragmentController mpqccontroller(io_service);
162 mpqccontroller.setHost(params.host.get());
163 mpqccontroller.setPort(params.port.get());
164 // Phase One: obtain ids
165 mpqccontroller.requestIds(NumberJobs);
166 if (mpqccontroller.getExitflag() != 0)
167 return Action::failure;
168
169 // Phase Two: add MPQCJobs and send
170 const bool AddJobsStatus = mpqccontroller.addJobsFromQueue(
171 params.DoLongrange.get() ? MPQCData::DoSampleDensity : MPQCData::DontSampleDensity,
172 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly
173 );
174 if (AddJobsStatus)
175 LOG(1, "INFO: Added jobs from FragmentJobsQueue.");
176 else {
177 ELOG(1, "Adding jobs failed.");
178 return Action::failure;
179 }
180 mpqccontroller.run();
181
182 // Phase Three: calculate result
183 setMaxSteps(NumberJobs);
184 mpqccontroller.setUpdateHandler(
185 boost::bind(&updateSteps, boost::ref(*this), _1, _2)
186 );
187 start();
188 boost::thread wait_thread(
189 boost::bind(&MPQCFragmentController::waitforResults, boost::ref(mpqccontroller), boost::cref(NumberJobs))
190 );
191 wait_thread.join();
192 stop();
193 if (mpqccontroller.getExitflag() != 0)
194 return Action::failure;
195
196 mpqccontroller.getResults(shortrangedata);
197 if (!checkResults(shortrangedata)) {
198 ELOG(1, "At least one of the fragments' energy could not be properly minimized.");
199 return Action::failure;
200 }
201 if (mpqccontroller.getExitflag() != 0) {
202 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag.");
203 return Action::failure;
204 }
205
206 Exitflag += mpqccontroller.getExitflag();
207 }
208#else
209 {
210 const size_t NumberJobs = FragmentJobQueue::getInstance().size();
211 MPQCCommandFragmentController mpqccontroller;
212 // Phase One: obtain ids: not needed, we have infinite pool
213
214 // Phase Two: add MPQCJobs and send
215 const size_t NoJobs = mpqccontroller.addJobsFromQueue(
216 params.DoLongrange.get() ? MPQCData::DoSampleDensity : MPQCData::DontSampleDensity,
217 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
218 params.executable.get().string()
219 );
220 if (NoJobs != NumberJobs) {
221 ELOG(1, "Not all jobs were added succesfully.");
222 return Action::failure;
223 }
224 LOG(1, "INFO: Added " << NoJobs << " from FragmentJobsQueue.");
225
226 // prepare process
227 setMaxSteps(NumberJobs);
228 mpqccontroller.setUpdateHandler(
229 boost::bind(&updateSteps, boost::ref(*this), _1, _2)
230 );
231 start();
232 mpqccontroller.run();
233 stop();
234 if (mpqccontroller.getExitflag() != 0) {
235 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag before getting results.");
236 return Action::failure;
237 }
238
239 // get back the results and place them in shortrangedata
240 mpqccontroller.getResults(shortrangedata);
241 ASSERT( shortrangedata.size() == NumberJobs,
242 "FragmentationFragmentationAutomationAction::performCall() - number of converted results "
243 +toString(shortrangedata.size())+" and number of jobs "+toString(NumberJobs)+ " differ.");
244 if (!checkResults(shortrangedata)) {
245 ELOG(1, "At least one of the fragments' energy could not be properly minimized.");
246 return Action::failure;
247 }
248 if (mpqccontroller.getExitflag() != 0) {
249 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag after getting results.");
250 return Action::failure;
251 }
252
253 Exitflag += mpqccontroller.getExitflag();
254 }
255#endif
256
257#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
258 if (params.DoLongrange.get()) {
259 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() == 0) {
260 STATUS("Please load the full molecule into the world before starting this action.");
261 return Action::failure;
262 }
263
264 // obtain combined charge density
265 FragmentationChargeDensity summedChargeDensity(
266 shortrangedata,
267 FragmentJobQueue::getInstance().getKeySets());
268 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
269 LOG(1, "INFO: There are " << shortrangedata.size() << " short-range and "
270 << full_sample.size() << " level-wise long-range jobs.");
271
272 // check boundary conditions
273 const BoundaryConditions::Conditions_t &conditions =
274 World::getInstance().getDomain().getConditions();
275 const bool OpenBoundaryConditions =
276 !((conditions[0] == BoundaryConditions::Wrap) &&
277 (conditions[1] == BoundaryConditions::Wrap) &&
278 (conditions[2] == BoundaryConditions::Wrap));
279 LOG(1, std::string("INFO: Using ")
280 << (OpenBoundaryConditions ? "open" : "periodic")
281 << " boundary conditions.");
282
283 // Phase Four: obtain more ids
284 std::map<JobId_t, VMGData> longrangedata;
285 {
286 VMGFragmentController vmgcontroller(io_service);
287 vmgcontroller.setHost(params.host.get());
288 vmgcontroller.setPort(params.port.get());
289 const size_t NoJobs = shortrangedata.size()+full_sample.size();
290 vmgcontroller.requestIds(2*NoJobs);
291 if (vmgcontroller.getExitflag() != 0) {
292 ELOG(1, "VMGFragmentController returned non-zero exit flag on requesting long-range ids.");
293 return Action::failure;
294 }
295
296 // Phase Five a: create VMGJobs for electronic charge distribution
297 const size_t near_field_cells = params.near_field_cells.get();
298 const size_t interpolation_degree = params.interpolation_degree.get();
299 if (!vmgcontroller.createLongRangeJobs(
300 shortrangedata,
301 full_sample,
302 near_field_cells,
303 interpolation_degree,
304 VMGFragmentController::DontSampleParticles,
305 VMGFragmentController::DoTreatGrid,
306 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
307 params.DoPrintDebug.get(),
308 OpenBoundaryConditions,
309 params.DoSmearCharges.get(),
310 false)) {
311 STATUS("Could not create long-range jobs for electronic charge distribution.");
312 return Action::failure;
313 }
314
315 // Phase Six a: calculate result
316 vmgcontroller.waitforResults(NoJobs);
317 if (vmgcontroller.getExitflag() != 0) {
318 ELOG(1, "VMGFragmentController returned non-zero exit flag before getting results.");
319 return Action::failure;
320 }
321 vmgcontroller.getResults(longrangedata);
322 ASSERT( NoJobs == longrangedata.size(),
323 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresults+"
324 +toString(full_sample.size())+"="+toString(NoJobs)
325 +" and first VMGresults "+toString(longrangedata.size())+" don't match.");
326 if (!checkResults(longrangedata)) {
327 ELOG(1, "At least one of the fragments' electronic long-range potential could not be properly minimized.");
328 return Action::failure;
329 }
330 Exitflag += vmgcontroller.getExitflag();
331
332 {
333 std::map<JobId_t, VMGData> longrangedata_both;
334 // Phase Five b: create VMGJobs for nuclei charge distributions
335 const size_t near_field_cells = params.near_field_cells.get();
336 const size_t interpolation_degree = params.interpolation_degree.get();
337 if (!vmgcontroller.createLongRangeJobs(
338 shortrangedata,
339 full_sample,
340 near_field_cells,
341 interpolation_degree,
342 VMGFragmentController::DoSampleParticles,
343 VMGFragmentController::DoTreatGrid,
344 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
345 params.DoPrintDebug.get(),
346 OpenBoundaryConditions,
347 params.DoSmearCharges.get(),
348 params.UseImplicitCharges.get())) {
349 STATUS("Could not create long-range jobs for nuclei charge distribution.");
350 return Action::failure;
351 }
352
353 // Phase Six b: calculate result
354 vmgcontroller.waitforResults(NoJobs);
355 if (vmgcontroller.getExitflag() != 0)
356 return Action::failure;
357 vmgcontroller.getResults(longrangedata_both);
358 ASSERT( NoJobs == longrangedata_both.size(),
359 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresults+"
360 +toString(full_sample.size())+"="+toString(NoJobs)
361 +" and second VMGresults "+toString(longrangedata_both.size())+" don't match.");
362 if (!checkResults(longrangedata_both)) {
363 ELOG(1, "At least one of the fragments' nuclei long-range potential could not be properly minimized.");
364 return Action::failure;
365 }
366 if (vmgcontroller.getExitflag() != 0) {
367 ELOG(1, "VMGFragmentController returned non-zero exit flag after getting results.");
368 return Action::failure;
369 }
370 Exitflag += vmgcontroller.getExitflag();
371
372 // go through either data and replace nuclei_long with contribution from both
373 ASSERT( longrangedata.size() == longrangedata_both.size(),
374 "FragmentationFragmentationAutomationAction::performCall() - longrange results have different sizes.");
375 std::map<JobId_t, VMGData>::iterator destiter = longrangedata.begin();
376 std::map<JobId_t, VMGData>::const_iterator srciter = longrangedata_both.begin();
377 for (;destiter != longrangedata.end(); ++srciter, ++destiter) {
378 destiter->second.both_sampled_potential = srciter->second.sampled_potential;
379 destiter->second.nuclei_long = srciter->second.nuclei_long;
380 destiter->second.forces = srciter->second.forces;
381 destiter->second.hasForces = srciter->second.hasForces;
382 }
383 }
384 }
385
386 if (params.DoPrintDebug.get()) {
387 std::map<JobId_t, std::string> debugData;
388 {
389 if (!full_sample.empty()) {
390 // create debug jobs for each level to print the summed-up potential to vtk files
391 VMGDebugGridFragmentController debugcontroller(io_service);
392 debugcontroller.setHost(params.host.get());
393 debugcontroller.setPort(params.port.get());
394 debugcontroller.requestIds(full_sample.size());
395 if (!debugcontroller.createDebugJobs(full_sample, OpenBoundaryConditions)) {
396 STATUS("Could not create debug jobs.");
397 return Action::failure;
398 }
399 debugcontroller.waitforResults(full_sample.size());
400 debugcontroller.getResults(debugData);
401 Exitflag += debugcontroller.getExitflag();
402 }
403 }
404 }
405 container.addFullResults(keysets, forcekeysets, shortrangedata, longrangedata);
406 } else {
407 container.addShortRangeResults(keysets, forcekeysets, shortrangedata);
408 }
409#else
410 container.addShortRangeResults(keysets, forcekeysets, shortrangedata);
411#endif
412
413 // now clear all present jobs as we are done
414 FragmentJobQueue::getInstance().clear();
415
416 // if file is given, advise results container to store to file
417 if (!params.resultsfile.get().empty()) {
418 boost::filesystem::path resultsfile = params.resultsfile.get();
419 std::ofstream returnstream(resultsfile.string().c_str());
420 if (returnstream.good()) {
421 boost::archive::text_oarchive oa(returnstream);
422 oa << container;
423 }
424 Exitflag += (int)(!returnstream.good());
425 returnstream.close();
426 }
427
428 if (Exitflag != 0)
429 STATUS("Controller has returned failure.");
430 return (Exitflag == 0) ? Action::success : Action::failure;
431}
432
433ActionState::ptr FragmentationFragmentationAutomationAction::performUndo(ActionState::ptr _state) {
434 return Action::success;
435}
436
437ActionState::ptr FragmentationFragmentationAutomationAction::performRedo(ActionState::ptr _state){
438 return Action::success;
439}
440
441bool FragmentationFragmentationAutomationAction::canUndo() {
442 return false;
443}
444
445bool FragmentationFragmentationAutomationAction::shouldUndo() {
446 return false;
447}
448/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.