source: src/Actions/ActionQueue.cpp@ 0b6b77

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 0b6b77 was 0b6b77, checked in by Frederik Heber <heber@…>, 11 years ago

ActionQueue gives caught failure of Action and success via pushStatus().

  • Property mode set to 100644
File size: 8.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 <string>
47#include <sstream>
48#include <vector>
49
50#include "Actions/ActionExceptions.hpp"
51#include "Actions/ActionHistory.hpp"
52#include "Actions/ActionRegistry.hpp"
53#include "World.hpp"
54
55using namespace MoleCuilder;
56
57ActionQueue::ActionQueue() :
58 AR(new ActionRegistry()),
59 history(new ActionHistory),
60#ifndef HAVE_ACTION_THREAD
61 CurrentAction(0)
62#else
63 CurrentAction(0),
64 run_thread(boost::bind(&ActionQueue::run, this)),
65 run_thread_isIdle(true)
66#endif
67{}
68
69ActionQueue::~ActionQueue()
70{
71#ifdef HAVE_ACTION_THREAD
72 stop();
73#endif
74
75 // free all actions contained in actionqueue
76 for (ActionQueue_t::iterator iter = actionqueue.begin(); !actionqueue.empty(); iter = actionqueue.begin()) {
77 delete *iter;
78 actionqueue.erase(iter);
79 }
80
81 delete history;
82 delete AR;
83}
84
85void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
86{
87 queueAction(AR->getActionByName(name), state);
88}
89
90void ActionQueue::queueAction(Action *_action, enum Action::QueryOptions state)
91{
92 Action *newaction = _action->clone(state);
93 newaction->prepare(state);
94#ifdef HAVE_ACTION_THREAD
95 mtx_queue.lock();
96#endif
97 actionqueue.push_back( newaction );
98#ifndef HAVE_ACTION_THREAD
99 try {
100 newaction->call();
101 } catch(ActionFailureException &e) {
102 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
103 World::getInstance().setExitFlag(5);
104 }
105#else
106 {
107 boost::lock_guard<boost::mutex> lock(mtx_idle);
108 run_thread_isIdle = (CurrentAction == actionqueue.size());
109 }
110 mtx_queue.unlock();
111#endif
112}
113
114void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
115{
116#ifndef HAVE_ACTION_THREAD
117 queueAction(_action, state);
118#else
119 Action *newaction = _action->clone(state);
120 newaction->prepare(state);
121 mtx_queue.lock();
122 tempqueue.push_back( newaction );
123 {
124 boost::lock_guard<boost::mutex> lock(mtx_idle);
125 run_thread_isIdle = !((CurrentAction != actionqueue.size()) || !tempqueue.empty());
126 }
127 mtx_queue.unlock();
128#endif
129}
130
131#ifdef HAVE_ACTION_THREAD
132void ActionQueue::run()
133{
134 bool Interrupted = false;
135 do {
136 // sleep for some time and wait for queue to fill up again
137 try {
138#if BOOST_VERSION < 105000
139 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
140#else
141 run_thread.sleep_for(100);
142#endif
143 } catch(boost::thread_interrupted &e) {
144 LOG(2, "INFO: ActionQueue has received stop signal.");
145 Interrupted = true;
146 }
147// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
148 // call all currently present Actions
149 mtx_queue.lock();
150 insertTempQueue();
151 bool status = (CurrentAction != actionqueue.size());
152 mtx_queue.unlock();
153 while (status) {
154 // boost::this_thread::disable_interruption di;
155 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
156 try {
157 actionqueue[CurrentAction]->call();
158 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
159 } catch(ActionFailureException &e) {
160 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
161 World::getInstance().setExitFlag(5);
162 }
163 // access actionqueue, hence using mutex
164 mtx_queue.lock();
165 // step on to next action and check for end
166 CurrentAction++;
167 // insert new actions (before [CurrentAction]) if they have been spawned
168 // we must have an extra vector for this, as we cannot change actionqueue
169 // while an action instance is "in-use"
170 insertTempQueue();
171 status = (CurrentAction != actionqueue.size());
172 mtx_queue.unlock();
173 }
174 {
175 boost::lock_guard<boost::mutex> lock(mtx_idle);
176 run_thread_isIdle = !((CurrentAction != actionqueue.size()) || !tempqueue.empty());
177 }
178 cond_idle.notify_one();
179// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
180 } while (!Interrupted);
181}
182#endif
183
184void ActionQueue::insertTempQueue()
185{
186 if (!tempqueue.empty()) {
187 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
188 std::advance(InsertionIter, CurrentAction);
189 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
190 tempqueue.clear();
191 }
192}
193
194#ifdef HAVE_ACTION_THREAD
195void ActionQueue::wait()
196{
197 boost::unique_lock<boost::mutex> lock(mtx_idle);
198 while(!run_thread_isIdle)
199 {
200 cond_idle.wait(lock);
201 }
202}
203#endif
204
205#ifdef HAVE_ACTION_THREAD
206void ActionQueue::stop()
207{
208 // notify actionqueue thread that we wish to terminate
209 run_thread.interrupt();
210 // wait till it ends
211 run_thread.join();
212}
213#endif
214
215Action* ActionQueue::getActionByName(const std::string &name)
216{
217 return AR->getActionByName(name);
218}
219
220bool ActionQueue::isActionKnownByName(const std::string &name) const
221{
222 return AR->isActionPresentByName(name);
223}
224
225void ActionQueue::registerAction(Action *_action)
226{
227 AR->registerInstance(_action);
228}
229
230void ActionQueue::outputAsCLI(std::ostream &output) const
231{
232 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
233 iter != actionqueue.end();
234 ++iter) {
235 // skip store-session in printed list
236 if ( ((*iter)->getName() != std::string("store-session"))
237 && ((*iter)->getName() != std::string("load-session"))) {
238 if (iter != actionqueue.begin())
239 output << " ";
240 (*iter)->outputAsCLI(output);
241 }
242 }
243 output << std::endl;
244}
245
246void ActionQueue::outputAsPython(std::ostream &output) const
247{
248 const std::string prefix("pyMoleCuilder");
249 output << "import " << prefix << std::endl;
250 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
251 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
252 iter != actionqueue.end();
253 ++iter) {
254 // skip store-session in printed list
255 if ( ((*iter)->getName() != std::string("store-session"))
256 && ((*iter)->getName() != std::string("load-session")))
257 (*iter)->outputAsPython(output, prefix);
258 }
259 output << "# =========================== Stored Session END ===========================" << std::endl;
260}
261
262const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
263{
264 // this const_cast is just required as long as we have a non-const getActionByName
265 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
266 return action->Traits;
267}
268
269void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
270{
271 history->addElement(_Action, _state);
272}
273
274void ActionQueue::clear()
275{
276 history->clear();
277}
278
279
280const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
281{
282 ActionTokens_t returnlist;
283
284 returnlist.insert(
285 returnlist.end(),
286 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
287 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
288
289 return returnlist;
290}
291
292void ActionQueue::undoLast()
293{
294 history->undoLast();
295}
296
297void ActionQueue::redoLast()
298{
299 history->redoLast();
300}
301
302
303CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.