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
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#ifdef HAVE_ACTION_THREAD
66 CurrentAction(0),
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 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}
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 * const 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 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 if (!isDryRun(actionqueue[CurrentAction]))
178 actionqueue[CurrentAction]->call();
179 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
180 lastActionOk = true;
181 } catch(ActionFailureException &e) {
182 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
183 World::getInstance().setExitFlag(5);
184 clearQueue(CurrentAction);
185 clearTempQueue();
186 lastActionOk = false;
187 std::cerr << "Remaining Actions cleared from queue." << std::endl;
188 } catch (std::exception &e) {
189 pushStatus("FAIL: General exception caught, aborting.");
190 World::getInstance().setExitFlag(134);
191 clearQueue(CurrentAction);
192 clearTempQueue();
193 lastActionOk = false;
194 std::cerr << "Remaining Actions cleared from queue." << std::endl;
195 }
196 if (lastActionOk) {
197 OBSERVE;
198 NOTIFY(ActionQueued);
199 _lastchangedaction = actionqueue[CurrentAction];
200 mtx_queue.lock();
201 CurrentAction++;
202 mtx_queue.unlock();
203 }
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 }
213 setRunThreadIdle( !((CurrentAction != actionqueue.size()) || !tempqueue.empty()) );
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}
237#endif
238
239#ifdef HAVE_ACTION_THREAD
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();
246}
247#endif
248
249Action* ActionQueue::getActionByName(const std::string &name)
250{
251 return AR->getActionByName(name);
252}
253
254bool ActionQueue::isActionKnownByName(const std::string &name) const
255{
256 return AR->isActionPresentByName(name);
257}
258
259void ActionQueue::registerAction(Action *_action)
260{
261 AR->registerInstance(_action);
262}
263
264void ActionQueue::outputAsCLI(std::ostream &output) const
265{
266 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
267 iter != actionqueue.end();
268 ++iter) {
269 // skip store-session in printed list
270 if ( ((*iter)->getName() != std::string("store-session"))
271 && ((*iter)->getName() != std::string("load-session"))) {
272 if (iter != actionqueue.begin())
273 output << " ";
274 (*iter)->outputAsCLI(output);
275 }
276 }
277 output << std::endl;
278}
279
280void ActionQueue::outputAsPython(std::ostream &output) const
281{
282 const std::string prefix("pyMoleCuilder");
283 output << "import " << prefix << std::endl;
284 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
285 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
286 iter != actionqueue.end();
287 ++iter) {
288 // skip store-session in printed list
289 if ( ((*iter)->getName() != std::string("store-session"))
290 && ((*iter)->getName() != std::string("load-session")))
291 (*iter)->outputAsPython(output, prefix);
292 }
293 output << "# =========================== Stored Session END ===========================" << std::endl;
294}
295
296const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
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
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
313void ActionQueue::clearQueue(const size_t _fromAction)
314{
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)
323 delete *iter;
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{
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 }
341}
342
343void ActionQueue::setRunThreadIdle(const bool _flag)
344{
345 {
346 boost::unique_lock<boost::mutex> lock(mtx_idle);
347 run_thread_isIdle = _flag;
348 }
349}
350#endif
351
352const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
353{
354 ActionTokens_t returnlist;
355
356 returnlist.insert(
357 returnlist.end(),
358 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
359 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
360
361 return returnlist;
362}
363
364void ActionQueue::undoLast()
365{
366 history->undoLast();
367}
368
369bool ActionQueue::canUndo() const
370{
371 return history->hasUndo();
372}
373
374void ActionQueue::redoLast()
375{
376 history->redoLast();
377}
378
379bool ActionQueue::canRedo() const
380{
381 return history->hasRedo();
382}
383
384bool ActionQueue::isDryRun(const Action *_nextaction) const
385{
386 bool status = dryrun_flag;
387 status &= (_nextaction->getName() != "no-dry-run");
388 return status;
389}
390
391CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.