source: src/Actions/ActionQueue.cpp@ c26617

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 c26617 was 601ef8, checked in by Frederik Heber <heber@…>, 10 years ago

FIX: ActionQueue is no longer cleared when Action fails.

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