source: src/Actions/ActionQueue.cpp@ fae462

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

Added DryRun and NoDryRun actions.

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