source: src/Actions/ActionQueue.cpp@ d93d2c

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 d93d2c 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
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),
[601ef8]65 CurrentAction(0),
[a87d1e2]66#ifdef HAVE_ACTION_THREAD
[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;
[574d377]74 Observable::insertNotificationChannel( std::make_pair(static_cast<Observable *>(this), OurChannel) );
[29b52b]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{
[10aee4]96 const Action & 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 {
[a87d1e2]110 if (!isDryRun(newaction)) {
111 CurrentAction = actionqueue.size()-1;
[f3db60]112 newaction->call();
[a87d1e2]113 CurrentAction = actionqueue.size();
114 }
[a61dbb]115 lastActionOk = true;
[74459a]116 } catch(ActionFailureException &e) {
117 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
118 World::getInstance().setExitFlag(5);
[601ef8]119 clearQueue(actionqueue.size()-1);
[a61dbb]120 lastActionOk = false;
[601ef8]121 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]122 } catch (std::exception &e) {
123 pushStatus("FAIL: General exception caught, aborting.");
124 World::getInstance().setExitFlag(134);
[601ef8]125 clearQueue(actionqueue.size()-1);
[11d433]126 lastActionOk = false;
[601ef8]127 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[74459a]128 }
[cfb9c5]129 if (lastActionOk) {
130 OBSERVE;
131 NOTIFY(ActionQueued);
132 _lastchangedaction = newaction;
133 }
[74459a]134#else
[415ddd]135 mtx_queue.unlock();
[a87d1e2]136 setRunThreadIdle(isIdle());
[74459a]137#endif
[05c989]138}
139
[975b83]140void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
141{
[74459a]142#ifndef HAVE_ACTION_THREAD
143 queueAction(_action, state);
144#else
[415ddd]145 Action *newaction = _action->clone(state);
146 newaction->prepare(state);
147 mtx_queue.lock();
148 tempqueue.push_back( newaction );
[a87d1e2]149 const bool tempqueue_notempty = !tempqueue.empty();
[415ddd]150 mtx_queue.unlock();
[a87d1e2]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);
[74459a]159#endif
[a87d1e2]160 bool status = (CurrentAction == actionqueue.size());
161 return status;
[415ddd]162}
163
[74459a]164#ifdef HAVE_ACTION_THREAD
[415ddd]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
[d93b4b3]174 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]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();
[a87d1e2]185 bool status = !isIdle();
[415ddd]186 while (status) {
187 // boost::this_thread::disable_interruption di;
188 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
189 try {
[f3db60]190 if (!isDryRun(actionqueue[CurrentAction]))
191 actionqueue[CurrentAction]->call();
[0b6b77]192 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
[a61dbb]193 lastActionOk = true;
[415ddd]194 } catch(ActionFailureException &e) {
[0b6b77]195 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]196 World::getInstance().setExitFlag(5);
[601ef8]197 clearQueue(CurrentAction);
198 clearTempQueue();
[a61dbb]199 lastActionOk = false;
[601ef8]200 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]201 } catch (std::exception &e) {
202 pushStatus("FAIL: General exception caught, aborting.");
203 World::getInstance().setExitFlag(134);
[601ef8]204 clearQueue(CurrentAction);
205 clearTempQueue();
[d8255b]206 lastActionOk = false;
[601ef8]207 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[415ddd]208 }
[cfb9c5]209 if (lastActionOk) {
210 OBSERVE;
211 NOTIFY(ActionQueued);
212 _lastchangedaction = actionqueue[CurrentAction];
[601ef8]213 mtx_queue.lock();
214 CurrentAction++;
215 mtx_queue.unlock();
[cfb9c5]216 }
[415ddd]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();
[a87d1e2]224 status = !isIdle();
[415ddd]225 }
[a87d1e2]226 mtx_queue.lock();
227 const bool tempqueue_notempty = !tempqueue.empty();
228 mtx_queue.unlock();
229 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
[415ddd]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}
[74459a]253#endif
[415ddd]254
[74459a]255#ifdef HAVE_ACTION_THREAD
[415ddd]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();
[975b83]262}
[74459a]263#endif
[975b83]264
[10aee4]265const Action& ActionQueue::getActionByName(const std::string &name)
[1d3563]266{
[ed3944]267 return AR->getActionByName(name);
[1d3563]268}
269
[a6ceab]270bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]271{
[ed3944]272 return AR->isActionPresentByName(name);
[1d3563]273}
274
[126867]275void ActionQueue::registerAction(Action *_action)
276{
277 AR->registerInstance(_action);
278}
279
[46b181]280void ActionQueue::outputAsCLI(std::ostream &output) const
281{
[7fc447]282 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
283 iter != actionqueue.end();
[46b181]284 ++iter) {
[bad589]285 // skip store-session in printed list
[12d946]286 if ( ((*iter)->getName() != std::string("store-session"))
287 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]288 if (iter != actionqueue.begin())
[bad589]289 output << " ";
290 (*iter)->outputAsCLI(output);
291 }
[46b181]292 }
293 output << std::endl;
294}
295
[477012]296void ActionQueue::outputAsPython(std::ostream &output) const
297{
298 const std::string prefix("pyMoleCuilder");
299 output << "import " << prefix << std::endl;
[9e4655]300 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]301 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
302 iter != actionqueue.end();
[477012]303 ++iter) {
304 // skip store-session in printed list
[12d946]305 if ( ((*iter)->getName() != std::string("store-session"))
306 && ((*iter)->getName() != std::string("load-session")))
[477012]307 (*iter)->outputAsPython(output, prefix);
308 }
[9e4655]309 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]310}
311
[a6ceab]312const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]313{
314 // this const_cast is just required as long as we have a non-const getActionByName
[10aee4]315 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
316 return action.Traits;
[690741]317}
318
[6367dd]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
[601ef8]329void ActionQueue::clearQueue(const size_t _fromAction)
[7f1a1a]330{
[601ef8]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)
[7f1a1a]339 delete *iter;
[601ef8]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{
[7f1a1a]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 }
[601ef8]357}
358
359void ActionQueue::setRunThreadIdle(const bool _flag)
360{
[06b5df]361 {
362 boost::unique_lock<boost::mutex> lock(mtx_idle);
[601ef8]363 run_thread_isIdle = _flag;
[06b5df]364 }
[7f1a1a]365}
[601ef8]366#endif
[6367dd]367
[690741]368const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
369{
370 ActionTokens_t returnlist;
371
372 returnlist.insert(
373 returnlist.end(),
[ed3944]374 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
375 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]376
377 return returnlist;
378}
379
[6367dd]380void ActionQueue::undoLast()
381{
382 history->undoLast();
383}
384
[c01fec]385bool ActionQueue::canUndo() const
386{
387 return history->hasUndo();
388}
389
[6367dd]390void ActionQueue::redoLast()
391{
392 history->redoLast();
393}
394
[c01fec]395bool ActionQueue::canRedo() const
396{
397 return history->hasRedo();
398}
399
[f3db60]400bool ActionQueue::isDryRun(const Action *_nextaction) const
401{
402 bool status = dryrun_flag;
403 status &= (_nextaction->getName() != "no-dry-run");
404 return status;
405}
[6367dd]406
[628577]407CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.