source: src/Actions/FragmentationAction/FragmentationAutomationAction.cpp@ 45f4b6b

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator 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_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 45f4b6b was ebadb4, checked in by Frederik Heber <heber@…>, 9 years ago

FragmentationChargeDensity requires additional zeroinstance in cstor.

  • Property mode set to 100644
File size: 17.0 KB
RevLine 
[edecba]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
[5aaa43]5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
[94d5ac6]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/>.
[edecba]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
[a3427f]42//// include headers that implement a archive in simple text format
[55e1bc]43#include <boost/archive/text_oarchive.hpp>
44#include <boost/archive/text_iarchive.hpp>
[240c3e]45
[a3427f]46//
47//#include <boost/mpl/remove.hpp>
48//#include <boost/lambda/lambda.hpp>
[fb881a]49
[a3427f]50//#include <iostream>
[240c3e]51
[6ca578]52#include "CodePatterns/Assert.hpp"
[edecba]53#include "CodePatterns/Info.hpp"
54#include "CodePatterns/Log.hpp"
[1dfe00]55
56#ifdef HAVE_JOBMARKET
[edecba]57#include "JobMarket/Jobs/FragmentJob.hpp"
[1dfe00]58#else
59#include "Jobs/JobMarket/FragmentJob.hpp"
60#endif
[edecba]61
[ac9ca4]62#include "Fragmentation/Automation/FragmentJobQueue.hpp"
[1dfe00]63#ifdef HAVE_JOBMARKET
[ffe057]64#include "Fragmentation/Automation/MPQCFragmentController.hpp"
[1dfe00]65#else
[bf0ff3]66#include "Fragmentation/Automation/MPQCCommandFragmentController.hpp"
[1dfe00]67#endif
[4a3df8]68#include "Fragmentation/Exporters/ExportGraph_ToJobs.hpp"
[fbf143]69#include "Fragmentation/Summation/Containers/FragmentationChargeDensity.hpp"
70#include "Fragmentation/Summation/Containers/FragmentationLongRangeResults.hpp"
[a3427f]71#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
[fbf143]72#include "Fragmentation/Summation/Containers/FragmentationShortRangeResults.hpp"
73#include "Fragmentation/Summation/Containers/MPQCData.hpp"
[a3427f]74#include "Fragmentation/KeySetsContainer.hpp"
[18ed8c]75#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
[a3427f]76#include "Fragmentation/Automation/VMGDebugGridFragmentController.hpp"
77#include "Fragmentation/Automation/VMGFragmentController.hpp"
[11edf0]78#include "Fragmentation/Summation/Containers/GridDownsampler.hpp"
[fbf143]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"
[69c733]83#endif
[edecba]84#include "World.hpp"
85
[c09f94]86#include <boost/bind.hpp>
87#include <boost/thread.hpp>
[86cfac5]88#include <fstream>
[edecba]89#include <iostream>
90#include <string>
91#include <vector>
92
[8cae4c]93#include <boost/mpl/for_each.hpp>
94
[edecba]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
[c09f94]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
[f0dea0]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)
[7debff]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}
[f0dea0]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
[b5b01e]155ActionState::ptr FragmentationFragmentationAutomationAction::performCall() {
[c5324f]156 boost::asio::io_service io_service;
157
158 // TODO: Have io_service run in second thread and merge with current again eventually
159
[a3427f]160 FragmentationResultContainer &container =
161 FragmentationResultContainer::getInstance();
162 const KeySetsContainer& keysets = FragmentJobQueue::getInstance().getKeySets();
163 const KeySetsContainer& forcekeysets = FragmentJobQueue::getInstance().getFullKeySets();
164
[4f056e]165 size_t Exitflag = 0;
[a3427f]166 std::map<JobId_t, MPQCData> shortrangedata;
[1dfe00]167#ifdef HAVE_JOBMARKET
[4f056e]168 {
[ac9ca4]169 const size_t NumberJobs = FragmentJobQueue::getInstance().size();
[4f056e]170 MPQCFragmentController mpqccontroller(io_service);
171 mpqccontroller.setHost(params.host.get());
172 mpqccontroller.setPort(params.port.get());
173 // Phase One: obtain ids
[ac9ca4]174 mpqccontroller.requestIds(NumberJobs);
[ca09be]175 if (mpqccontroller.getExitflag() != 0)
176 return Action::failure;
[4f056e]177
[ac9ca4]178 // Phase Two: add MPQCJobs and send
[a61dbb]179 const bool AddJobsStatus = mpqccontroller.addJobsFromQueue(
[6ff62c]180 params.DoLongrange.get() ? MPQCData::DoSampleDensity : MPQCData::DontSampleDensity,
181 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly
182 );
[a61dbb]183 if (AddJobsStatus)
184 LOG(1, "INFO: Added jobs from FragmentJobsQueue.");
185 else {
186 ELOG(1, "Adding jobs failed.");
187 return Action::failure;
188 }
[ac9ca4]189 mpqccontroller.run();
[4f056e]190
191 // Phase Three: calculate result
[c09f94]192 setMaxSteps(NumberJobs);
193 mpqccontroller.setUpdateHandler(
194 boost::bind(&updateSteps, boost::ref(*this), _1, _2)
195 );
196 start();
197 boost::thread wait_thread(
198 boost::bind(&MPQCFragmentController::waitforResults, boost::ref(mpqccontroller), boost::cref(NumberJobs))
199 );
200 wait_thread.join();
201 stop();
[ca09be]202 if (mpqccontroller.getExitflag() != 0)
203 return Action::failure;
204
[a3427f]205 mpqccontroller.getResults(shortrangedata);
[f0dea0]206 if (!checkResults(shortrangedata)) {
207 ELOG(1, "At least one of the fragments' energy could not be properly minimized.");
[ca09be]208 return Action::failure;
[f0dea0]209 }
210 if (mpqccontroller.getExitflag() != 0) {
211 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag.");
212 return Action::failure;
213 }
[4f056e]214
215 Exitflag += mpqccontroller.getExitflag();
216 }
[bf0ff3]217#else
218 {
219 const size_t NumberJobs = FragmentJobQueue::getInstance().size();
220 MPQCCommandFragmentController mpqccontroller;
221 // Phase One: obtain ids: not needed, we have infinite pool
222
223 // Phase Two: add MPQCJobs and send
224 const size_t NoJobs = mpqccontroller.addJobsFromQueue(
225 params.DoLongrange.get() ? MPQCData::DoSampleDensity : MPQCData::DontSampleDensity,
[d6a7b9]226 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
227 params.executable.get().string()
[bf0ff3]228 );
[07ecc5]229 if (NoJobs != NumberJobs) {
230 ELOG(1, "Not all jobs were added succesfully.");
231 return Action::failure;
232 }
[bf0ff3]233 LOG(1, "INFO: Added " << NoJobs << " from FragmentJobsQueue.");
[45cdce6]234
235 // prepare process
236 setMaxSteps(NumberJobs);
237 mpqccontroller.setUpdateHandler(
238 boost::bind(&updateSteps, boost::ref(*this), _1, _2)
239 );
240 start();
[bf0ff3]241 mpqccontroller.run();
[45cdce6]242 stop();
[f0dea0]243 if (mpqccontroller.getExitflag() != 0) {
244 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag before getting results.");
[ca09be]245 return Action::failure;
[f0dea0]246 }
[bf0ff3]247
248 // get back the results and place them in shortrangedata
249 mpqccontroller.getResults(shortrangedata);
250 ASSERT( shortrangedata.size() == NumberJobs,
251 "FragmentationFragmentationAutomationAction::performCall() - number of converted results "
252 +toString(shortrangedata.size())+" and number of jobs "+toString(NumberJobs)+ " differ.");
[f0dea0]253 if (!checkResults(shortrangedata)) {
254 ELOG(1, "At least one of the fragments' energy could not be properly minimized.");
255 return Action::failure;
256 }
257 if (mpqccontroller.getExitflag() != 0) {
258 ELOG(1, "MPQCCommandFragmentController returned non-zero exit flag after getting results.");
[ca09be]259 return Action::failure;
[f0dea0]260 }
[bf0ff3]261
[4f056e]262 Exitflag += mpqccontroller.getExitflag();
263 }
[1dfe00]264#endif
[c5324f]265
[18ed8c]266#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
[69c733]267 if (params.DoLongrange.get()) {
[a58c16]268 if ( const_cast<const World &>(World::getInstance()).getAllAtoms().size() == 0) {
[26b4d62]269 STATUS("Please load the full molecule into the world before starting this action.");
[db6f7d]270 return Action::failure;
271 }
[06865e]272
[849cd8]273 // obtain combined charge density
[4a3df8]274 std::map<JobId_t, MPQCData> shortrangedata_downsampled;
275 SamplingGridProperties domain(ExportGraph_ToJobs::getDomainGrid(params.level.get()));
[27594e]276 FragmentationChargeDensity summedChargeDensity(
[b5134a]277 shortrangedata);
[ebadb4]278 {
279 SamplingGrid zero_globalgrid(ZeroInstance<SamplingGrid>());
280 summedChargeDensity(
281 shortrangedata,
282 FragmentJobQueue::getInstance().getKeySets(),
283 zero_globalgrid);
284 }
[27594e]285 const std::vector<SamplingGrid> full_sample = summedChargeDensity.getFullSampledGrid();
[a3427f]286 LOG(1, "INFO: There are " << shortrangedata.size() << " short-range and "
[4f056e]287 << full_sample.size() << " level-wise long-range jobs.");
[69c733]288
[1e5f84]289 // check boundary conditions
290 const BoundaryConditions::Conditions_t &conditions =
291 World::getInstance().getDomain().getConditions();
292 const bool OpenBoundaryConditions =
293 !((conditions[0] == BoundaryConditions::Wrap) &&
294 (conditions[1] == BoundaryConditions::Wrap) &&
295 (conditions[2] == BoundaryConditions::Wrap));
296 LOG(1, std::string("INFO: Using ")
297 << (OpenBoundaryConditions ? "open" : "periodic")
298 << " boundary conditions.");
299
[4f056e]300 // Phase Four: obtain more ids
[a3427f]301 std::map<JobId_t, VMGData> longrangedata;
[4f056e]302 {
303 VMGFragmentController vmgcontroller(io_service);
304 vmgcontroller.setHost(params.host.get());
305 vmgcontroller.setPort(params.port.get());
[a3427f]306 const size_t NoJobs = shortrangedata.size()+full_sample.size();
[e2925fd]307 vmgcontroller.requestIds(2*NoJobs);
[f0dea0]308 if (vmgcontroller.getExitflag() != 0) {
309 ELOG(1, "VMGFragmentController returned non-zero exit flag on requesting long-range ids.");
[ca09be]310 return Action::failure;
[f0dea0]311 }
[4f056e]312
[e2925fd]313 // Phase Five a: create VMGJobs for electronic charge distribution
[4f056e]314 const size_t near_field_cells = params.near_field_cells.get();
[cd2591]315 const size_t interpolation_degree = params.interpolation_degree.get();
[4f056e]316 if (!vmgcontroller.createLongRangeJobs(
[a3427f]317 shortrangedata,
[4f056e]318 full_sample,
[cd2591]319 near_field_cells,
[6ff62c]320 interpolation_degree,
[e2925fd]321 VMGFragmentController::DontSampleParticles,
322 VMGFragmentController::DoTreatGrid,
[b6b21a]323 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
[1e5f84]324 params.DoPrintDebug.get(),
[17e4fd]325 OpenBoundaryConditions,
[666e9e]326 params.DoSmearCharges.get(),
327 false)) {
[26b4d62]328 STATUS("Could not create long-range jobs for electronic charge distribution.");
[4f056e]329 return Action::failure;
[26b4d62]330 }
[4f056e]331
[e2925fd]332 // Phase Six a: calculate result
[4f056e]333 vmgcontroller.waitforResults(NoJobs);
[f0dea0]334 if (vmgcontroller.getExitflag() != 0) {
335 ELOG(1, "VMGFragmentController returned non-zero exit flag before getting results.");
[ca09be]336 return Action::failure;
[f0dea0]337 }
[a3427f]338 vmgcontroller.getResults(longrangedata);
339 ASSERT( NoJobs == longrangedata.size(),
[4f056e]340 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresults+"
341 +toString(full_sample.size())+"="+toString(NoJobs)
[e2925fd]342 +" and first VMGresults "+toString(longrangedata.size())+" don't match.");
[f0dea0]343 if (!checkResults(longrangedata)) {
344 ELOG(1, "At least one of the fragments' electronic long-range potential could not be properly minimized.");
345 return Action::failure;
346 }
[4f056e]347 Exitflag += vmgcontroller.getExitflag();
[e2925fd]348
349 {
350 std::map<JobId_t, VMGData> longrangedata_both;
351 // Phase Five b: create VMGJobs for nuclei charge distributions
352 const size_t near_field_cells = params.near_field_cells.get();
353 const size_t interpolation_degree = params.interpolation_degree.get();
354 if (!vmgcontroller.createLongRangeJobs(
355 shortrangedata,
356 full_sample,
357 near_field_cells,
358 interpolation_degree,
359 VMGFragmentController::DoSampleParticles,
360 VMGFragmentController::DoTreatGrid,
361 params.DoValenceOnly.get() ? MPQCData::DoSampleValenceOnly : MPQCData::DontSampleValenceOnly,
[1e5f84]362 params.DoPrintDebug.get(),
[17e4fd]363 OpenBoundaryConditions,
[666e9e]364 params.DoSmearCharges.get(),
365 params.UseImplicitCharges.get())) {
[26b4d62]366 STATUS("Could not create long-range jobs for nuclei charge distribution.");
[e2925fd]367 return Action::failure;
[26b4d62]368 }
[e2925fd]369
370 // Phase Six b: calculate result
371 vmgcontroller.waitforResults(NoJobs);
[ca09be]372 if (vmgcontroller.getExitflag() != 0)
373 return Action::failure;
[e2925fd]374 vmgcontroller.getResults(longrangedata_both);
375 ASSERT( NoJobs == longrangedata_both.size(),
376 "FragmentationFragmentationAutomationAction::performCall() - number of MPQCresults+"
377 +toString(full_sample.size())+"="+toString(NoJobs)
378 +" and second VMGresults "+toString(longrangedata_both.size())+" don't match.");
[f0dea0]379 if (!checkResults(longrangedata_both)) {
380 ELOG(1, "At least one of the fragments' nuclei long-range potential could not be properly minimized.");
[ca09be]381 return Action::failure;
[f0dea0]382 }
383 if (vmgcontroller.getExitflag() != 0) {
384 ELOG(1, "VMGFragmentController returned non-zero exit flag after getting results.");
385 return Action::failure;
386 }
[e2925fd]387 Exitflag += vmgcontroller.getExitflag();
388
389 // go through either data and replace nuclei_long with contribution from both
390 ASSERT( longrangedata.size() == longrangedata_both.size(),
391 "FragmentationFragmentationAutomationAction::performCall() - longrange results have different sizes.");
392 std::map<JobId_t, VMGData>::iterator destiter = longrangedata.begin();
[e355b31]393 std::map<JobId_t, VMGData>::const_iterator srciter = longrangedata_both.begin();
394 for (;destiter != longrangedata.end(); ++srciter, ++destiter) {
395 destiter->second.both_sampled_potential = srciter->second.sampled_potential;
[e2925fd]396 destiter->second.nuclei_long = srciter->second.nuclei_long;
[94db13]397 destiter->second.forces = srciter->second.forces;
398 destiter->second.hasForces = srciter->second.hasForces;
[e355b31]399 }
[e2925fd]400 }
[4f056e]401 }
[a2295a]402
[b6b21a]403 if (params.DoPrintDebug.get()) {
404 std::map<JobId_t, std::string> debugData;
405 {
406 if (!full_sample.empty()) {
407 // create debug jobs for each level to print the summed-up potential to vtk files
408 VMGDebugGridFragmentController debugcontroller(io_service);
409 debugcontroller.setHost(params.host.get());
410 debugcontroller.setPort(params.port.get());
411 debugcontroller.requestIds(full_sample.size());
[26b4d62]412 if (!debugcontroller.createDebugJobs(full_sample, OpenBoundaryConditions)) {
413 STATUS("Could not create debug jobs.");
[b6b21a]414 return Action::failure;
[26b4d62]415 }
[b6b21a]416 debugcontroller.waitforResults(full_sample.size());
417 debugcontroller.getResults(debugData);
418 Exitflag += debugcontroller.getExitflag();
419 }
[a2295a]420 }
[2764e0]421 }
[2ae247]422 container.clear();
[a3427f]423 container.addFullResults(keysets, forcekeysets, shortrangedata, longrangedata);
424 } else {
[2ae247]425 container.clear();
[a3427f]426 container.addShortRangeResults(keysets, forcekeysets, shortrangedata);
[69c733]427 }
[a3427f]428#else
[2ae247]429 container.clear();
[a3427f]430 container.addShortRangeResults(keysets, forcekeysets, shortrangedata);
[69c733]431#endif
[edecba]432
[bae7bc]433 // now clear all present jobs as we are done
434 FragmentJobQueue::getInstance().clear();
435
[26b4d62]436 if (Exitflag != 0)
437 STATUS("Controller has returned failure.");
[edecba]438 return (Exitflag == 0) ? Action::success : Action::failure;
439}
440
[b5b01e]441ActionState::ptr FragmentationFragmentationAutomationAction::performUndo(ActionState::ptr _state) {
[edecba]442 return Action::success;
443}
444
[b5b01e]445ActionState::ptr FragmentationFragmentationAutomationAction::performRedo(ActionState::ptr _state){
[edecba]446 return Action::success;
447}
448
449bool FragmentationFragmentationAutomationAction::canUndo() {
450 return false;
451}
452
453bool FragmentationFragmentationAutomationAction::shouldUndo() {
454 return false;
455}
456/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.