Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core/EngineBase.cs @ 797

Last change on this file since 797 was 776, checked in by vdorfer, 16 years ago

Created API documentation for HeuristicLab.Core namespace (#331)

File size: 13.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    /// <summary>
70    /// Field of the current instance that represent the execution stack.
71    /// </summary>
72    protected Stack<IOperation> myExecutionStack;
73    /// <summary>
74    /// Gets the current execution stack.
75    /// </summary>
76    public Stack<IOperation> ExecutionStack {
77      get { return myExecutionStack; }
78    }
79   
80    /// <summary>
81    /// Flag of the current instance whether it is currently running.
82    /// </summary>
83    protected bool myRunning;
84    /// <summary>
85    /// Gets information whether the instance is currently running.
86    /// </summary>
87    public bool Running {
88      get { return myRunning; }
89    }
90
91    /// <summary>
92    /// Flag of the current instance whether it is canceled.
93    /// </summary>
94    protected bool myCanceled;
95    /// <summary>
96    /// Gets information whether the instance is currently canceled.
97    /// </summary>
98    public bool Canceled {
99      get { return myCanceled; }
100    }
101    /// <summary>
102    /// Gets information whether the instance has already terminated.
103    /// </summary>
104    public virtual bool Terminated {
105      get { return ExecutionStack.Count == 0; }
106    }
107
108    /// <summary>
109    /// Initializes a new instance of <see cref="EngineBase"/> with a new global scope.
110    /// </summary>
111    /// <remarks>Calls <see cref="Reset"/>.</remarks>
112    protected EngineBase() {
113      myOperatorGraph = new OperatorGraph();
114      myGlobalScope = new Scope("Global");
115      myExecutionStack = new Stack<IOperation>();
116      Reset();
117    }
118
119    /// <summary>
120    /// Clones the current instance (deep clone).
121    /// </summary>
122    /// <remarks>Deep clone through <see cref="Auxiliary.Clone"/> method of helper class
123    /// <see cref="Auxiliary"/>.</remarks>
124    /// <param name="clonedObjects">Dictionary of all already clone objects. (Needed to avoid cycles.)</param>
125    /// <returns>The cloned object as <see cref="EngineBase"/>.</returns>
126    public override object Clone(IDictionary<Guid, object> clonedObjects) {
127      EngineBase clone = (EngineBase)base.Clone(clonedObjects);
128      clone.myOperatorGraph = (IOperatorGraph)Auxiliary.Clone(OperatorGraph, clonedObjects);
129      clone.myGlobalScope = (IScope)Auxiliary.Clone(GlobalScope, clonedObjects);
130      clone.myExecutionTime = ExecutionTime;
131      IOperation[] operations = new IOperation[ExecutionStack.Count];
132      ExecutionStack.CopyTo(operations, 0);
133      for (int i = operations.Length - 1; i >= 0; i--)
134        clone.myExecutionStack.Push((IOperation)Auxiliary.Clone(operations[i], clonedObjects));
135      clone.myRunning = Running;
136      clone.myCanceled = Canceled;
137      return clone;
138     
139    }
140
141    /// <inheritdoc/>
142    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
143    /// of class <see cref="ThreadPool"/>.</remarks>
144    public virtual void Execute() {
145      myRunning = true;
146      myCanceled = false;
147      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
148    }
149    /// <inheritdoc/>
150    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
151    /// of class <see cref="ThreadPool"/>.</remarks>
152    public virtual void ExecuteSteps(int steps) {
153      myRunning = true;
154      myCanceled = false;
155      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), steps);
156    }
157    /// <inheritdoc/>
158    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
159    /// of class <see cref="ThreadPool"/>.</remarks>
160    public void ExecuteStep() {
161      ExecuteSteps(1);
162    }
163    /// <inheritdoc/>
164    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
165    public virtual void Abort() {
166      myCanceled = true;
167    }
168    /// <inheritdoc/>
169    /// <remarks>Sets <c>myCanceled</c> and <c>myRunning</c> to <c>false</c>. The global scope is cleared,
170    /// the execution time is reseted, the execution stack is cleared and a new <see cref="AtomicOperation"/>
171    /// with the initial operator is added. <br/>
172    /// Calls <see cref="OnInitialized"/>.</remarks>
173    public virtual void Reset() {
174      myCanceled = false;
175      myRunning = false;
176      GlobalScope.Clear();
177      ExecutionTime = new TimeSpan();
178      myExecutionStack.Clear();
179      if (OperatorGraph.InitialOperator != null)
180        myExecutionStack.Push(new AtomicOperation(OperatorGraph.InitialOperator, GlobalScope));
181      OnInitialized();
182    }
183
184    private void Run(object state) {
185      if (state == null) Run();
186      else RunSteps((int)state);
187      myRunning = false;
188      OnFinished();
189    }
190    private void Run() {
191      DateTime start = DateTime.Now;
192      DateTime end;
193      while ((!Canceled) && (!Terminated)) {
194        ProcessNextOperation();
195        end = DateTime.Now;
196        ExecutionTime += end - start;
197        start = end;
198      }
199      ExecutionTime += DateTime.Now - start;
200    }
201    private void RunSteps(int steps) {
202      DateTime start = DateTime.Now;
203      DateTime end;
204      int step = 0;
205      while ((!Canceled) && (!Terminated) && (step < steps)) {
206        ProcessNextOperation();
207        step++;
208        end = DateTime.Now;
209        ExecutionTime += end - start;
210        start = end;
211      }
212      ExecutionTime += DateTime.Now - start;
213    }
214
215    /// <summary>
216    /// Performs the next operation.
217    /// </summary>
218    protected abstract void ProcessNextOperation();
219
220    /// <summary>
221    /// Occurs when the current instance is initialized.
222    /// </summary>
223    public event EventHandler Initialized;
224    /// <summary>
225    /// Fires a new <c>Initialized</c> event.
226    /// </summary>
227    protected virtual void OnInitialized() {
228      if (Initialized != null)
229        Initialized(this, new EventArgs());
230    }
231    /// <summary>
232    /// Occurs when an operation is executed.
233    /// </summary>
234    public event EventHandler<OperationEventArgs> OperationExecuted;
235    /// <summary>
236    /// Fires a new <c>OperationExecuted</c> event.
237    /// </summary>
238    /// <param name="operation">The operation that has been executed.</param>
239    protected virtual void OnOperationExecuted(IOperation operation) {
240      if (OperationExecuted != null)
241        OperationExecuted(this, new OperationEventArgs(operation));
242    }
243    /// <summary>
244    /// Occurs when an exception occured during the execution.
245    /// </summary>
246    public event EventHandler<ExceptionEventArgs> ExceptionOccurred;
247    /// <summary>
248    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
249    /// </summary>
250    /// <param name="exception">The exception that was thrown.</param>
251    protected virtual void OnExceptionOccurred(Exception exception) {
252      Abort();
253      if (ExceptionOccurred != null)
254        ExceptionOccurred(this, new ExceptionEventArgs(exception));
255    }
256    /// <summary>
257    /// Occurs when the execution time changed.
258    /// </summary>
259    public event EventHandler ExecutionTimeChanged;
260    /// <summary>
261    /// Fires a new <c>ExecutionTimeChanged</c> event.
262    /// </summary>
263    protected virtual void OnExecutionTimeChanged() {
264      if (ExecutionTimeChanged != null)
265        ExecutionTimeChanged(this, new EventArgs());
266    }
267    /// <summary>
268    /// Occurs when the execution is finished.
269    /// </summary>
270    public event EventHandler Finished;
271    /// <summary>
272    /// Fires a new <c>Finished</c> event.
273    /// </summary>
274    protected virtual void OnFinished() {
275      if (Finished != null)
276        Finished(this, new EventArgs());
277    }
278
279    #region Persistence Methods
280    /// <summary>
281    /// Saves the current instance as <see cref="XmlNode"/> in the specified <paramref name="document"/>.
282    /// </summary>
283    /// <remarks>Calls <see cref="StorableBase.GetXmlNode"/> of base class <see cref="ItemBase"/>.<br/>
284    /// A quick overview how the single elements of the current instance are saved:
285    /// <list type="bullet">
286    /// <item>
287    /// <term>Operator graph: </term>
288    /// <description>Saved as a child node with the tag name <c>OperatorGraph</c>.</description>
289    /// </item>
290    /// <item>
291    /// <term>Global scope: </term>
292    /// <description>Saved as a child node with the tag name <c>GlobalScope</c>.</description>
293    /// </item>
294    /// <item>
295    /// <term>Execution stack: </term>
296    /// <description>A child node is created with the tag name <c>ExecutionStack</c>. Beyond this child node
297    /// all operations of the execution stack are saved as child nodes.</description>
298    /// </item>
299    /// <item>
300    /// <term>Execution time: </term>
301    /// <description>Saved as a child node with the tag name <c>ExecutionTime</c>, where the execution
302    /// time is saved as string in the node's inner text.</description>
303    /// </item>
304    /// </list></remarks>
305    /// <param name="name">The (tag)name of the <see cref="XmlNode"/>.</param>
306    /// <param name="document">The <see cref="XmlDocument"/> where to save the data.</param>
307    /// <param name="persistedObjects">The dictionary of all already persisted objects. (Needed to avoid cycles.)</param>
308    /// <returns>The saved <see cref="XmlNode"/>.</returns>
309    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid,IStorable> persistedObjects) {
310      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
311
312      node.AppendChild(PersistenceManager.Persist("OperatorGraph", OperatorGraph, document, persistedObjects));
313      node.AppendChild(PersistenceManager.Persist("GlobalScope", GlobalScope, document, persistedObjects));
314
315      XmlNode stackNode = document.CreateNode(XmlNodeType.Element, "ExecutionStack", null);
316      IOperation[] operations = new IOperation[ExecutionStack.Count];
317      ExecutionStack.CopyTo(operations, 0);
318      for (int i = 0; i < operations.Length; i++)
319        stackNode.AppendChild(PersistenceManager.Persist(operations[i], document, persistedObjects));
320      node.AppendChild(stackNode);
321
322      XmlNode timeNode = document.CreateNode(XmlNodeType.Element, "ExecutionTime", null);
323      timeNode.InnerText = ExecutionTime.ToString();
324      node.AppendChild(timeNode);
325      return node;
326    }
327    /// <summary>
328    ///  Loads the persisted instance from the specified <paramref name="node"/>.
329    /// </summary>
330    /// <remarks>See <see cref="GetXmlNode"/> to get information on how the instance must be saved. <br/>
331    /// Calls <see cref="StorableBase.Populate"/> of base class <see cref="ItemBase"/>.</remarks>
332    /// <param name="node">The <see cref="XmlNode"/> where the engine is saved.</param>
333    /// <param name="restoredObjects">The dictionary of all already restored objects.
334    /// (Needed to avoid cycles.)</param>
335    public override void Populate(XmlNode node, IDictionary<Guid,IStorable> restoredObjects) {
336      base.Populate(node, restoredObjects);
337      myOperatorGraph = (IOperatorGraph)PersistenceManager.Restore(node.SelectSingleNode("OperatorGraph"), restoredObjects);
338      myGlobalScope = (IScope)PersistenceManager.Restore(node.SelectSingleNode("GlobalScope"), restoredObjects);
339
340      XmlNode stackNode = node.SelectSingleNode("ExecutionStack");
341      for (int i = stackNode.ChildNodes.Count - 1; i >= 0; i--)
342        myExecutionStack.Push((IOperation)PersistenceManager.Restore(stackNode.ChildNodes[i], restoredObjects));
343
344      XmlNode timeNode = node.SelectSingleNode("ExecutionTime");
345      myExecutionTime = TimeSpan.Parse(timeNode.InnerText);
346    }
347    #endregion
348  }
349}
Note: See TracBrowser for help on using the repository browser.