Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CloningRefactorBranch/HeuristicLab.Core/EngineBase.cs @ 885

Last change on this file since 885 was 885, checked in by gkronber, 15 years ago

Refactored cloning in HL.Core, HL.Data and HL.Constraints

#285 (Cloning could be improved by creating objects at the bottom of the cloning chain with 'new' instead of the top with Activator.CreateInstance())

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