source: src/Actions/ActionQueue.cpp@ 4464ef

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures 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_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChronosMutex 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_IntegrationTest 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_levmar Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 4464ef was 574d377, checked in by Frederik Heber <heber@…>, 9 years ago

Using static Observable::..NotificationsChannel() functions.

  • Property mode set to 100644
File size: 11.2 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 lastActionOk(true),
65 CurrentAction(0),
66#ifdef HAVE_ACTION_THREAD
67 run_thread(boost::bind(&ActionQueue::run, this)),
68 run_thread_isIdle(true),
69#endif
70 dryrun_flag(false)
71{
72 // channels of observable
73 Channels *OurChannel = new Channels;
74 Observable::insertNotificationChannel( 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}
79
80ActionQueue::~ActionQueue()
81{
82#ifdef HAVE_ACTION_THREAD
83 stop();
84
85 clearTempQueue();
86#endif
87
88 clearQueue();
89
90 delete history;
91 delete AR;
92}
93
94void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
95{
96 const Action & registryaction = AR->getActionByName(name);
97 queueAction(&registryaction, state);
98}
99
100void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
101{
102 Action *newaction = _action->clone(state);
103 newaction->prepare(state);
104#ifdef HAVE_ACTION_THREAD
105 mtx_queue.lock();
106#endif
107 actionqueue.push_back( newaction );
108#ifndef HAVE_ACTION_THREAD
109 try {
110 if (!isDryRun(newaction)) {
111 CurrentAction = actionqueue.size()-1;
112 newaction->call();
113 CurrentAction = actionqueue.size();
114 }
115 lastActionOk = true;
116 } catch(ActionFailureException &e) {
117 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
118 World::getInstance().setExitFlag(5);
119 clearQueue(actionqueue.size()-1);
120 lastActionOk = false;
121 std::cerr << "Remaining Actions cleared from queue." << std::endl;
122 } catch (std::exception &e) {
123 pushStatus("FAIL: General exception caught, aborting.");
124 World::getInstance().setExitFlag(134);
125 clearQueue(actionqueue.size()-1);
126 lastActionOk = false;
127 std::cerr << "Remaining Actions cleared from queue." << std::endl;
128 }
129 if (lastActionOk) {
130 OBSERVE;
131 NOTIFY(ActionQueued);
132 _lastchangedaction = newaction;
133 }
134#else
135 mtx_queue.unlock();
136 setRunThreadIdle(isIdle());
137#endif
138}
139
140void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
141{
142#ifndef HAVE_ACTION_THREAD
143 queueAction(_action, state);
144#else
145 Action *newaction = _action->clone(state);
146 newaction->prepare(state);
147 mtx_queue.lock();
148 tempqueue.push_back( newaction );
149 const bool tempqueue_notempty = !tempqueue.empty();
150 mtx_queue.unlock();
151 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
152#endif
153}
154
155bool ActionQueue::isIdle() const
156{
157#ifdef HAVE_ACTION_THREAD
158 boost::unique_lock<boost::mutex> lock(mtx_queue);
159#endif
160 bool status = (CurrentAction == actionqueue.size());
161 return status;
162}
163
164#ifdef HAVE_ACTION_THREAD
165void ActionQueue::run()
166{
167 bool Interrupted = false;
168 do {
169 // sleep for some time and wait for queue to fill up again
170 try {
171#if BOOST_VERSION < 105000
172 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
173#else
174 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
175#endif
176 } catch(boost::thread_interrupted &e) {
177 LOG(2, "INFO: ActionQueue has received stop signal.");
178 Interrupted = true;
179 }
180// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
181 // call all currently present Actions
182 mtx_queue.lock();
183 insertTempQueue();
184 mtx_queue.unlock();
185 bool status = !isIdle();
186 while (status) {
187 // boost::this_thread::disable_interruption di;
188 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
189 try {
190 if (!isDryRun(actionqueue[CurrentAction]))
191 actionqueue[CurrentAction]->call();
192 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
193 lastActionOk = true;
194 } catch(ActionFailureException &e) {
195 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
196 World::getInstance().setExitFlag(5);
197 clearQueue(CurrentAction);
198 clearTempQueue();
199 lastActionOk = false;
200 std::cerr << "Remaining Actions cleared from queue." << std::endl;
201 } catch (std::exception &e) {
202 pushStatus("FAIL: General exception caught, aborting.");
203 World::getInstance().setExitFlag(134);
204 clearQueue(CurrentAction);
205 clearTempQueue();
206 lastActionOk = false;
207 std::cerr << "Remaining Actions cleared from queue." << std::endl;
208 }
209 if (lastActionOk) {
210 OBSERVE;
211 NOTIFY(ActionQueued);
212 _lastchangedaction = actionqueue[CurrentAction];
213 mtx_queue.lock();
214 CurrentAction++;
215 mtx_queue.unlock();
216 }
217 // access actionqueue, hence using mutex
218 mtx_queue.lock();
219 // insert new actions (before [CurrentAction]) if they have been spawned
220 // we must have an extra vector for this, as we cannot change actionqueue
221 // while an action instance is "in-use"
222 insertTempQueue();
223 mtx_queue.unlock();
224 status = !isIdle();
225 }
226 mtx_queue.lock();
227 const bool tempqueue_notempty = !tempqueue.empty();
228 mtx_queue.unlock();
229 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
230 cond_idle.notify_one();
231// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
232 } while (!Interrupted);
233}
234
235void ActionQueue::insertTempQueue()
236{
237 if (!tempqueue.empty()) {
238 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
239 std::advance(InsertionIter, CurrentAction);
240 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
241 tempqueue.clear();
242 }
243}
244
245void ActionQueue::wait()
246{
247 boost::unique_lock<boost::mutex> lock(mtx_idle);
248 while(!run_thread_isIdle)
249 {
250 cond_idle.wait(lock);
251 }
252}
253#endif
254
255#ifdef HAVE_ACTION_THREAD
256void ActionQueue::stop()
257{
258 // notify actionqueue thread that we wish to terminate
259 run_thread.interrupt();
260 // wait till it ends
261 run_thread.join();
262}
263#endif
264
265const Action& ActionQueue::getActionByName(const std::string &name)
266{
267 return AR->getActionByName(name);
268}
269
270bool ActionQueue::isActionKnownByName(const std::string &name) const
271{
272 return AR->isActionPresentByName(name);
273}
274
275void ActionQueue::registerAction(Action *_action)
276{
277 AR->registerInstance(_action);
278}
279
280void ActionQueue::outputAsCLI(std::ostream &output) const
281{
282 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
283 iter != actionqueue.end();
284 ++iter) {
285 // skip store-session in printed list
286 if ( ((*iter)->getName() != std::string("store-session"))
287 && ((*iter)->getName() != std::string("load-session"))) {
288 if (iter != actionqueue.begin())
289 output << " ";
290 (*iter)->outputAsCLI(output);
291 }
292 }
293 output << std::endl;
294}
295
296void ActionQueue::outputAsPython(std::ostream &output) const
297{
298 const std::string prefix("pyMoleCuilder");
299 output << "import " << prefix << std::endl;
300 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
301 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
302 iter != actionqueue.end();
303 ++iter) {
304 // skip store-session in printed list
305 if ( ((*iter)->getName() != std::string("store-session"))
306 && ((*iter)->getName() != std::string("load-session")))
307 (*iter)->outputAsPython(output, prefix);
308 }
309 output << "# =========================== Stored Session END ===========================" << std::endl;
310}
311
312const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
313{
314 // this const_cast is just required as long as we have a non-const getActionByName
315 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
316 return action.Traits;
317}
318
319void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
320{
321 history->addElement(_Action, _state);
322}
323
324void ActionQueue::clear()
325{
326 history->clear();
327}
328
329void ActionQueue::clearQueue(const size_t _fromAction)
330{
331#ifdef HAVE_ACTION_THREAD
332 mtx_queue.lock();
333#endif
334 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
335 // free all actions still to be called contained in actionqueue
336 ActionQueue_t::iterator inititer = actionqueue.begin();
337 std::advance(inititer, _fromAction);
338 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
339 delete *iter;
340 actionqueue.erase(inititer, actionqueue.end());
341 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
342#ifdef HAVE_ACTION_THREAD
343 CurrentAction = actionqueue.size();
344 mtx_queue.unlock();
345#endif
346}
347
348#ifdef HAVE_ACTION_THREAD
349void ActionQueue::clearTempQueue()
350{
351 // free all actions contained in tempqueue
352 for (ActionQueue_t::iterator iter = tempqueue.begin();
353 !tempqueue.empty(); iter = tempqueue.begin()) {
354 delete *iter;
355 tempqueue.erase(iter);
356 }
357}
358
359void ActionQueue::setRunThreadIdle(const bool _flag)
360{
361 {
362 boost::unique_lock<boost::mutex> lock(mtx_idle);
363 run_thread_isIdle = _flag;
364 }
365}
366#endif
367
368const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
369{
370 ActionTokens_t returnlist;
371
372 returnlist.insert(
373 returnlist.end(),
374 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
375 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
376
377 return returnlist;
378}
379
380void ActionQueue::undoLast()
381{
382 history->undoLast();
383}
384
385bool ActionQueue::canUndo() const
386{
387 return history->hasUndo();
388}
389
390void ActionQueue::redoLast()
391{
392 history->redoLast();
393}
394
395bool ActionQueue::canRedo() const
396{
397 return history->hasRedo();
398}
399
400bool ActionQueue::isDryRun(const Action *_nextaction) const
401{
402 bool status = dryrun_flag;
403 status &= (_nextaction->getName() != "no-dry-run");
404 return status;
405}
406
407CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.