Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 846 was 836, checked in by gkronber, 16 years ago

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