source: src/Actions/ActionQueue.cpp@ 8859b5

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 8859b5 was 29b52b, checked in by Frederik Heber <heber@…>, 11 years ago

Made ActionQueue observable.

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