source: src/Actions/ActionQueue.cpp@ 2a03b0

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 v1.4.6
Last change on this file since 2a03b0 was d8821e, checked in by Frederik Heber <heber@…>, 11 years ago

Merge branch 'Fragmentation_Automation_wo_JobMarket' into stable

Conflicts:

src/Actions/ActionQueue.cpp
src/Actions/FragmentationAction/FragmentationAction.cpp
src/Actions/PotentialAction/FitParticleChargesAction.cpp

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