Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core/3.2/EngineBase.cs @ 1844

Last change on this file since 1844 was 1815, checked in by swagner, 15 years ago

Added a property for the thread priority of an engine's worker thread to EngineBase (#623)

File size: 14.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Xml;
26using System.Threading;
27
28namespace HeuristicLab.Core {
29  /// <summary>
30  /// Base class to represent an engine, which is an interpreter, holding the code, the data and
31  /// the actual state, which is the runtime stack and a pointer onto the next operation. It represents
32  /// one execution and can handle parallel executions.
33  /// </summary>
34  public abstract class EngineBase : ItemBase, IEngine {
35    /// <summary>
36    /// Field of the current instance that represent the operator graph.
37    /// </summary>
38    protected IOperatorGraph myOperatorGraph;
39    /// <summary>
40    /// Gets the current operator graph.
41    /// </summary>
42    public IOperatorGraph OperatorGraph {
43      get { return myOperatorGraph; }
44    }
45    /// <summary>
46    /// Field of the current instance that represent the global scope.
47    /// </summary>
48    protected IScope myGlobalScope;
49    /// <summary>
50    /// Gets the current global scope.
51    /// </summary>
52    public IScope GlobalScope {
53      get { return myGlobalScope; }
54    }
55
56    private TimeSpan myExecutionTime;
57    /// <summary>
58    /// Gets or sets the execution time.
59    /// </summary>
60    /// <remarks>Calls <see cref="OnExecutionTimeChanged"/> in the setter.</remarks>
61    public TimeSpan ExecutionTime {
62      get { return myExecutionTime; }
63      protected set {
64        myExecutionTime = value;
65        OnExecutionTimeChanged();
66      }
67    }
68
69    private ThreadPriority myPriority;
70    /// <summary>
71    /// Gets or sets the priority of the worker thread.
72    /// </summary>
73    public ThreadPriority Priority {
74      get { return myPriority; }
75      set { myPriority = value; }
76    }
77
78    /// <summary>
79    /// Field of the current instance that represent the execution stack.
80    /// </summary>
81    protected Stack<IOperation> myExecutionStack;
82    /// <summary>
83    /// Gets the current execution stack.
84    /// </summary>
85    public Stack<IOperation> ExecutionStack {
86      get { return myExecutionStack; }
87    }
88   
89    /// <summary>
90    /// Flag of the current instance whether it is currently running.
91    /// </summary>
92    protected bool myRunning;
93    /// <summary>
94    /// Gets information whether the instance is currently running.
95    /// </summary>
96    public bool Running {
97      get { return myRunning; }
98    }
99
100    /// <summary>
101    /// Flag of the current instance whether it is canceled.
102    /// </summary>
103    protected bool myCanceled;
104    /// <summary>
105    /// Gets information whether the instance is currently canceled.
106    /// </summary>
107    public bool Canceled {
108      get { return myCanceled; }
109    }
110    /// <summary>
111    /// Gets information whether the instance has already terminated.
112    /// </summary>
113    public virtual bool Terminated {
114      get { return ExecutionStack.Count == 0; }
115    }
116
117    /// <summary>
118    /// Initializes a new instance of <see cref="EngineBase"/> with a new global scope.
119    /// </summary>
120    /// <remarks>Calls <see cref="Reset"/>.</remarks>
121    protected EngineBase() {
122      myOperatorGraph = new OperatorGraph();
123      myGlobalScope = new Scope("Global");
124      myPriority = ThreadPriority.Normal;
125      myExecutionStack = new Stack<IOperation>();
126      Reset();
127    }
128
129    /// <summary>
130    /// Clones the current instance (deep clone).
131    /// </summary>
132    /// <remarks>Deep clone through <see cref="Auxiliary.Clone"/> method of helper class
133    /// <see cref="Auxiliary"/>.</remarks>
134    /// <param name="clonedObjects">Dictionary of all already clone objects. (Needed to avoid cycles.)</param>
135    /// <returns>The cloned object as <see cref="EngineBase"/>.</returns>
136    public override object Clone(IDictionary<Guid, object> clonedObjects) {
137      EngineBase clone = (EngineBase)base.Clone(clonedObjects);
138      clone.myOperatorGraph = (IOperatorGraph)Auxiliary.Clone(OperatorGraph, clonedObjects);
139      clone.myGlobalScope = (IScope)Auxiliary.Clone(GlobalScope, clonedObjects);
140      clone.myExecutionTime = ExecutionTime;
141      IOperation[] operations = new IOperation[ExecutionStack.Count];
142      ExecutionStack.CopyTo(operations, 0);
143      for (int i = operations.Length - 1; i >= 0; i--)
144        clone.myExecutionStack.Push((IOperation)Auxiliary.Clone(operations[i], clonedObjects));
145      clone.myRunning = Running;
146      clone.myCanceled = Canceled;
147      return clone;
148     
149    }
150
151    /// <inheritdoc/>
152    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
153    /// of class <see cref="ThreadPool"/>.</remarks>
154    public virtual void Execute() {
155      myRunning = true;
156      myCanceled = false;
157      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
158    }
159    /// <inheritdoc/>
160    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
161    /// of class <see cref="ThreadPool"/>.</remarks>
162    public virtual void ExecuteSteps(int steps) {
163      myRunning = true;
164      myCanceled = false;
165      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), steps);
166    }
167    /// <inheritdoc/>
168    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
169    /// of class <see cref="ThreadPool"/>.</remarks>
170    public void ExecuteStep() {
171      ExecuteSteps(1);
172    }
173    /// <inheritdoc/>
174    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
175    public virtual void Abort() {
176      myCanceled = true;
177    }
178    /// <inheritdoc/>
179    /// <remarks>Sets <c>myCanceled</c> and <c>myRunning</c> to <c>false</c>. The global scope is cleared,
180    /// the execution time is reseted, the execution stack is cleared and a new <see cref="AtomicOperation"/>
181    /// with the initial operator is added. <br/>
182    /// Calls <see cref="OnInitialized"/>.</remarks>
183    public virtual void Reset() {
184      myCanceled = false;
185      myRunning = false;
186      GlobalScope.Clear();
187      ExecutionTime = new TimeSpan();
188      myExecutionStack.Clear();
189      if (OperatorGraph.InitialOperator != null)
190        myExecutionStack.Push(new AtomicOperation(OperatorGraph.InitialOperator, GlobalScope));
191      OnInitialized();
192    }
193
194    private void Run(object state) {
195      Thread.CurrentThread.Priority = Priority;
196      if (state == null) Run();
197      else RunSteps((int)state);
198      myRunning = false;
199      Thread.CurrentThread.Priority = ThreadPriority.Normal;
200      OnFinished();
201    }
202    private void Run() {
203      DateTime start = DateTime.Now;
204      DateTime end;
205      while ((!Canceled) && (!Terminated)) {
206        ProcessNextOperation();
207        end = DateTime.Now;
208        ExecutionTime += end - start;
209        start = end;
210      }
211      ExecutionTime += DateTime.Now - start;
212    }
213    private void RunSteps(int steps) {
214      DateTime start = DateTime.Now;
215      DateTime end;
216      int step = 0;
217      while ((!Canceled) && (!Terminated) && (step < steps)) {
218        ProcessNextOperation();
219        step++;
220        end = DateTime.Now;
221        ExecutionTime += end - start;
222        start = end;
223      }
224      ExecutionTime += DateTime.Now - start;
225    }
226
227    /// <summary>
228    /// Performs the next operation.
229    /// </summary>
230    protected abstract void ProcessNextOperation();
231
232    /// <summary>
233    /// Occurs when the current instance is initialized.
234    /// </summary>
235    public event EventHandler Initialized;
236    /// <summary>
237    /// Fires a new <c>Initialized</c> event.
238    /// </summary>
239    protected virtual void OnInitialized() {
240      if (Initialized != null)
241        Initialized(this, new EventArgs());
242    }
243    /// <summary>
244    /// Occurs when an operation is executed.
245    /// </summary>
246    public event EventHandler<OperationEventArgs> OperationExecuted;
247    /// <summary>
248    /// Fires a new <c>OperationExecuted</c> event.
249    /// </summary>
250    /// <param name="operation">The operation that has been executed.</param>
251    protected virtual void OnOperationExecuted(IOperation operation) {
252      if (OperationExecuted != null)
253        OperationExecuted(this, new OperationEventArgs(operation));
254    }
255    /// <summary>
256    /// Occurs when an exception occured during the execution.
257    /// </summary>
258    public event EventHandler<ExceptionEventArgs> ExceptionOccurred;
259    /// <summary>
260    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
261    /// </summary>
262    /// <param name="exception">The exception that was thrown.</param>
263    protected virtual void OnExceptionOccurred(Exception exception) {
264      Abort();
265      if (ExceptionOccurred != null)
266        ExceptionOccurred(this, new ExceptionEventArgs(exception));
267    }
268    /// <summary>
269    /// Occurs when the execution time changed.
270    /// </summary>
271    public event EventHandler ExecutionTimeChanged;
272    /// <summary>
273    /// Fires a new <c>ExecutionTimeChanged</c> event.
274    /// </summary>
275    protected virtual void OnExecutionTimeChanged() {
276      if (ExecutionTimeChanged != null)
277        ExecutionTimeChanged(this, new EventArgs());
278    }
279    /// <summary>
280    /// Occurs when the execution is finished.
281    /// </summary>
282    public event EventHandler Finished;
283    /// <summary>
284    /// Fires a new <c>Finished</c> event.
285    /// </summary>
286    protected virtual void OnFinished() {
287      if (Finished != null)
288        Finished(this, new EventArgs());
289    }
290
291    #region Persistence Methods
292    /// <summary>
293    /// Saves the current instance as <see cref="XmlNode"/> in the specified <paramref name="document"/>.
294    /// </summary>
295    /// <remarks>Calls <see cref="StorableBase.GetXmlNode"/> of base class <see cref="ItemBase"/>.<br/>
296    /// A quick overview how the single elements of the current instance are saved:
297    /// <list type="bullet">
298    /// <item>
299    /// <term>Operator graph: </term>
300    /// <description>Saved as a child node with the tag name <c>OperatorGraph</c>.</description>
301    /// </item>
302    /// <item>
303    /// <term>Global scope: </term>
304    /// <description>Saved as a child node with the tag name <c>GlobalScope</c>.</description>
305    /// </item>
306    /// <item>
307    /// <term>Execution stack: </term>
308    /// <description>A child node is created with the tag name <c>ExecutionStack</c>. Beyond this child node
309    /// all operations of the execution stack are saved as child nodes.</description>
310    /// </item>
311    /// <item>
312    /// <term>Execution time: </term>
313    /// <description>Saved as a child node with the tag name <c>ExecutionTime</c>, where the execution
314    /// time is saved as string in the node's inner text.</description>
315    /// </item>
316    /// <item>
317    /// <term>Priority: </term>
318    /// <description>Saved as a child node with the tag name <c>Priority</c>, where the thread priority
319    /// is saved as string in the node's inner text.</description>
320    /// </item>
321    /// </list></remarks>
322    /// <param name="name">The (tag)name of the <see cref="XmlNode"/>.</param>
323    /// <param name="document">The <see cref="XmlDocument"/> where to save the data.</param>
324    /// <param name="persistedObjects">The dictionary of all already persisted objects. (Needed to avoid cycles.)</param>
325    /// <returns>The saved <see cref="XmlNode"/>.</returns>
326    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid,IStorable> persistedObjects) {
327      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
328
329      node.AppendChild(PersistenceManager.Persist("OperatorGraph", OperatorGraph, document, persistedObjects));
330      node.AppendChild(PersistenceManager.Persist("GlobalScope", GlobalScope, document, persistedObjects));
331
332      XmlNode stackNode = document.CreateNode(XmlNodeType.Element, "ExecutionStack", null);
333      IOperation[] operations = new IOperation[ExecutionStack.Count];
334      ExecutionStack.CopyTo(operations, 0);
335      for (int i = 0; i < operations.Length; i++)
336        stackNode.AppendChild(PersistenceManager.Persist(operations[i], document, persistedObjects));
337      node.AppendChild(stackNode);
338
339      XmlNode timeNode = document.CreateNode(XmlNodeType.Element, "ExecutionTime", null);
340      timeNode.InnerText = ExecutionTime.ToString();
341      node.AppendChild(timeNode);
342      XmlNode priorityNode = document.CreateNode(XmlNodeType.Element, "Priority", null);
343      priorityNode.InnerText = Priority.ToString();
344      node.AppendChild(priorityNode);
345      return node;
346    }
347    /// <summary>
348    ///  Loads the persisted instance from the specified <paramref name="node"/>.
349    /// </summary>
350    /// <remarks>See <see cref="GetXmlNode"/> to get information on how the instance must be saved. <br/>
351    /// Calls <see cref="StorableBase.Populate"/> of base class <see cref="ItemBase"/>.</remarks>
352    /// <param name="node">The <see cref="XmlNode"/> where the engine is saved.</param>
353    /// <param name="restoredObjects">The dictionary of all already restored objects.
354    /// (Needed to avoid cycles.)</param>
355    public override void Populate(XmlNode node, IDictionary<Guid,IStorable> restoredObjects) {
356      base.Populate(node, restoredObjects);
357      myOperatorGraph = (IOperatorGraph)PersistenceManager.Restore(node.SelectSingleNode("OperatorGraph"), restoredObjects);
358      myGlobalScope = (IScope)PersistenceManager.Restore(node.SelectSingleNode("GlobalScope"), restoredObjects);
359
360      XmlNode stackNode = node.SelectSingleNode("ExecutionStack");
361      for (int i = stackNode.ChildNodes.Count - 1; i >= 0; i--)
362        myExecutionStack.Push((IOperation)PersistenceManager.Restore(stackNode.ChildNodes[i], restoredObjects));
363
364      XmlNode timeNode = node.SelectSingleNode("ExecutionTime");
365      myExecutionTime = TimeSpan.Parse(timeNode.InnerText);
366      XmlNode priorityNode = node.SelectSingleNode("Priority");
367      if (priorityNode != null)
368        myPriority = (ThreadPriority) Enum.Parse(typeof(ThreadPriority), priorityNode.InnerText);
369    }
370    #endregion
371  }
372}
Note: See TracBrowser for help on using the repository browser.