source: src/Actions/ActionQueue.cpp@ 9ec4b8

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 9ec4b8 was d8255b, checked in by Frederik Heber <heber@…>, 10 years ago

FIX: ActionQueue would not set LastActionOk to false on general exception.

  • Property mode set to 100644
File size: 10.9 KB
RevLine 
[628577]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 Frederik Heber. 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 * ActionQueue.cpp
25 *
26 * Created on: Aug 16, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
[1d3563]37#include "Actions/ActionQueue.hpp"
[628577]38
[690741]39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
[46b181]41#include "CodePatterns/Log.hpp"
[628577]42#include "CodePatterns/Singleton_impl.hpp"
43
[415ddd]44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
[601ef8]46#include <iterator>
[46b181]47#include <string>
48#include <sstream>
[690741]49#include <vector>
50
[0d4168]51#include "Actions/ActionExceptions.hpp"
[6367dd]52#include "Actions/ActionHistory.hpp"
[ed3944]53#include "Actions/ActionRegistry.hpp"
[0d4168]54#include "World.hpp"
[ed3944]55
[628577]56using namespace MoleCuilder;
57
[29b52b]58const Action* ActionQueue::_lastchangedaction = NULL;
59
[ed3944]60ActionQueue::ActionQueue() :
[29b52b]61 Observable("ActionQueue"),
[6367dd]62 AR(new ActionRegistry()),
[af5384]63 history(new ActionHistory),
[f3db60]64 lastActionOk(true),
[d8255b]65#ifdef HAVE_ACTION_THREAD
[601ef8]66 CurrentAction(0),
[415ddd]67 run_thread(boost::bind(&ActionQueue::run, this)),
[f3db60]68 run_thread_isIdle(true),
[74459a]69#endif
[f3db60]70 dryrun_flag(false)
[29b52b]71{
72 // channels of observable
73 Channels *OurChannel = new Channels;
74 NotificationChannels.insert( std::make_pair(static_cast<Observable *>(this), OurChannel) );
75 // add instance for each notification type
76 for (size_t type = 0; type < NotificationType_MAX; ++type)
77 OurChannel->addChannel(type);
78}
[628577]79
80ActionQueue::~ActionQueue()
[ed3944]81{
[74459a]82#ifdef HAVE_ACTION_THREAD
[415ddd]83 stop();
[601ef8]84
85 clearTempQueue();
[74459a]86#endif
[415ddd]87
[7f1a1a]88 clearQueue();
[af5384]89
[6367dd]90 delete history;
[ed3944]91 delete AR;
92}
[628577]93
[f54cda]94void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
[05c989]95{
[7f1a1a]96 const Action * const registryaction = AR->getActionByName(name);
97 queueAction(registryaction, state);
[f54cda]98}
99
[7f1a1a]100void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
[f54cda]101{
[af5384]102 Action *newaction = _action->clone(state);
103 newaction->prepare(state);
[74459a]104#ifdef HAVE_ACTION_THREAD
[415ddd]105 mtx_queue.lock();
[74459a]106#endif
[7fc447]107 actionqueue.push_back( newaction );
[74459a]108#ifndef HAVE_ACTION_THREAD
109 try {
[f3db60]110 if (!isDryRun(newaction))
111 newaction->call();
[a61dbb]112 lastActionOk = true;
[74459a]113 } catch(ActionFailureException &e) {
114 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
115 World::getInstance().setExitFlag(5);
[601ef8]116 clearQueue(actionqueue.size()-1);
[a61dbb]117 lastActionOk = false;
[601ef8]118 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]119 } catch (std::exception &e) {
120 pushStatus("FAIL: General exception caught, aborting.");
121 World::getInstance().setExitFlag(134);
[601ef8]122 clearQueue(actionqueue.size()-1);
[11d433]123 lastActionOk = false;
[601ef8]124 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[74459a]125 }
[cfb9c5]126 if (lastActionOk) {
127 OBSERVE;
128 NOTIFY(ActionQueued);
129 _lastchangedaction = newaction;
130 }
[74459a]131#else
[601ef8]132 setRunThreadIdle(CurrentAction == actionqueue.size());
[415ddd]133 mtx_queue.unlock();
[74459a]134#endif
[05c989]135}
136
[975b83]137void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
138{
[74459a]139#ifndef HAVE_ACTION_THREAD
140 queueAction(_action, state);
141#else
[415ddd]142 Action *newaction = _action->clone(state);
143 newaction->prepare(state);
144 mtx_queue.lock();
145 tempqueue.push_back( newaction );
[601ef8]146 setRunThreadIdle( !((CurrentAction != actionqueue.size()) || !tempqueue.empty()) );
[415ddd]147 mtx_queue.unlock();
[74459a]148#endif
[415ddd]149}
150
[74459a]151#ifdef HAVE_ACTION_THREAD
[415ddd]152void ActionQueue::run()
153{
154 bool Interrupted = false;
155 do {
156 // sleep for some time and wait for queue to fill up again
157 try {
158#if BOOST_VERSION < 105000
159 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
160#else
[d93b4b3]161 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]162#endif
163 } catch(boost::thread_interrupted &e) {
164 LOG(2, "INFO: ActionQueue has received stop signal.");
165 Interrupted = true;
166 }
167// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
168 // call all currently present Actions
169 mtx_queue.lock();
170 insertTempQueue();
171 bool status = (CurrentAction != actionqueue.size());
172 mtx_queue.unlock();
173 while (status) {
174 // boost::this_thread::disable_interruption di;
175 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
176 try {
[f3db60]177 if (!isDryRun(actionqueue[CurrentAction]))
178 actionqueue[CurrentAction]->call();
[0b6b77]179 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
[a61dbb]180 lastActionOk = true;
[415ddd]181 } catch(ActionFailureException &e) {
[0b6b77]182 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]183 World::getInstance().setExitFlag(5);
[601ef8]184 clearQueue(CurrentAction);
185 clearTempQueue();
[a61dbb]186 lastActionOk = false;
[601ef8]187 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]188 } catch (std::exception &e) {
189 pushStatus("FAIL: General exception caught, aborting.");
190 World::getInstance().setExitFlag(134);
[601ef8]191 clearQueue(CurrentAction);
192 clearTempQueue();
[d8255b]193 lastActionOk = false;
[601ef8]194 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[415ddd]195 }
[cfb9c5]196 if (lastActionOk) {
197 OBSERVE;
198 NOTIFY(ActionQueued);
199 _lastchangedaction = actionqueue[CurrentAction];
[601ef8]200 mtx_queue.lock();
201 CurrentAction++;
202 mtx_queue.unlock();
[cfb9c5]203 }
[415ddd]204 // access actionqueue, hence using mutex
205 mtx_queue.lock();
206 // insert new actions (before [CurrentAction]) if they have been spawned
207 // we must have an extra vector for this, as we cannot change actionqueue
208 // while an action instance is "in-use"
209 insertTempQueue();
210 status = (CurrentAction != actionqueue.size());
211 mtx_queue.unlock();
212 }
[601ef8]213 setRunThreadIdle( !((CurrentAction != actionqueue.size()) || !tempqueue.empty()) );
[415ddd]214 cond_idle.notify_one();
215// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
216 } while (!Interrupted);
217}
218
219void ActionQueue::insertTempQueue()
220{
221 if (!tempqueue.empty()) {
222 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
223 std::advance(InsertionIter, CurrentAction);
224 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
225 tempqueue.clear();
226 }
227}
228
229void ActionQueue::wait()
230{
231 boost::unique_lock<boost::mutex> lock(mtx_idle);
232 while(!run_thread_isIdle)
233 {
234 cond_idle.wait(lock);
235 }
236}
[74459a]237#endif
[415ddd]238
[74459a]239#ifdef HAVE_ACTION_THREAD
[415ddd]240void ActionQueue::stop()
241{
242 // notify actionqueue thread that we wish to terminate
243 run_thread.interrupt();
244 // wait till it ends
245 run_thread.join();
[975b83]246}
[74459a]247#endif
[975b83]248
[a6ceab]249Action* ActionQueue::getActionByName(const std::string &name)
[1d3563]250{
[ed3944]251 return AR->getActionByName(name);
[1d3563]252}
253
[a6ceab]254bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]255{
[ed3944]256 return AR->isActionPresentByName(name);
[1d3563]257}
258
[126867]259void ActionQueue::registerAction(Action *_action)
260{
261 AR->registerInstance(_action);
262}
263
[46b181]264void ActionQueue::outputAsCLI(std::ostream &output) const
265{
[7fc447]266 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
267 iter != actionqueue.end();
[46b181]268 ++iter) {
[bad589]269 // skip store-session in printed list
[12d946]270 if ( ((*iter)->getName() != std::string("store-session"))
271 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]272 if (iter != actionqueue.begin())
[bad589]273 output << " ";
274 (*iter)->outputAsCLI(output);
275 }
[46b181]276 }
277 output << std::endl;
278}
279
[477012]280void ActionQueue::outputAsPython(std::ostream &output) const
281{
282 const std::string prefix("pyMoleCuilder");
283 output << "import " << prefix << std::endl;
[9e4655]284 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]285 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
286 iter != actionqueue.end();
[477012]287 ++iter) {
288 // skip store-session in printed list
[12d946]289 if ( ((*iter)->getName() != std::string("store-session"))
290 && ((*iter)->getName() != std::string("load-session")))
[477012]291 (*iter)->outputAsPython(output, prefix);
292 }
[9e4655]293 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]294}
295
[a6ceab]296const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]297{
298 // this const_cast is just required as long as we have a non-const getActionByName
299 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
300 return action->Traits;
301}
302
[6367dd]303void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
304{
305 history->addElement(_Action, _state);
306}
307
308void ActionQueue::clear()
309{
310 history->clear();
311}
312
[601ef8]313void ActionQueue::clearQueue(const size_t _fromAction)
[7f1a1a]314{
[601ef8]315#ifdef HAVE_ACTION_THREAD
316 mtx_queue.lock();
317#endif
318 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
319 // free all actions still to be called contained in actionqueue
320 ActionQueue_t::iterator inititer = actionqueue.begin();
321 std::advance(inititer, _fromAction);
322 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
[7f1a1a]323 delete *iter;
[601ef8]324 actionqueue.erase(inititer, actionqueue.end());
325 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
326#ifdef HAVE_ACTION_THREAD
327 CurrentAction = actionqueue.size();
328 mtx_queue.unlock();
329#endif
330}
331
332#ifdef HAVE_ACTION_THREAD
333void ActionQueue::clearTempQueue()
334{
[7f1a1a]335 // free all actions contained in tempqueue
336 for (ActionQueue_t::iterator iter = tempqueue.begin();
337 !tempqueue.empty(); iter = tempqueue.begin()) {
338 delete *iter;
339 tempqueue.erase(iter);
340 }
[601ef8]341}
342
343void ActionQueue::setRunThreadIdle(const bool _flag)
344{
[06b5df]345 {
346 boost::unique_lock<boost::mutex> lock(mtx_idle);
[601ef8]347 run_thread_isIdle = _flag;
[06b5df]348 }
[7f1a1a]349}
[601ef8]350#endif
[6367dd]351
[690741]352const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
353{
354 ActionTokens_t returnlist;
355
356 returnlist.insert(
357 returnlist.end(),
[ed3944]358 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
359 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]360
361 return returnlist;
362}
363
[6367dd]364void ActionQueue::undoLast()
365{
366 history->undoLast();
367}
368
[c01fec]369bool ActionQueue::canUndo() const
370{
371 return history->hasUndo();
372}
373
[6367dd]374void ActionQueue::redoLast()
375{
376 history->redoLast();
377}
378
[c01fec]379bool ActionQueue::canRedo() const
380{
381 return history->hasRedo();
382}
383
[f3db60]384bool ActionQueue::isDryRun(const Action *_nextaction) const
385{
386 bool status = dryrun_flag;
387 status &= (_nextaction->getName() != "no-dry-run");
388 return status;
389}
[6367dd]390
[628577]391CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.