Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Persistence Test/HeuristicLab.Core/3.3/EngineBase.cs @ 2760

Last change on this file since 2760 was 2474, checked in by swagner, 15 years ago

Implemented generic EventArgs (#796)

File size: 10.0 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;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Common;
29
30namespace HeuristicLab.Core {
31  /// <summary>
32  /// Base class to represent an engine, which is an interpreter, holding the code, the data and
33  /// the actual state, which is the runtime stack and a pointer onto the next operation. It represents
34  /// one execution and can handle parallel executions.
35  /// </summary>
36  public abstract class EngineBase : ItemBase, IEngine {
37
38    /// <summary>
39    /// Field of the current instance that represent the operator graph.
40    /// </summary>
41    [Storable]
42    protected IOperatorGraph myOperatorGraph;
43    /// <summary>
44    /// Gets the current operator graph.
45    /// </summary>
46    public IOperatorGraph OperatorGraph {
47      get { return myOperatorGraph; }
48    }
49    /// <summary>
50    /// Field of the current instance that represent the global scope.
51    /// </summary>
52    [Storable]
53    protected IScope myGlobalScope;
54    /// <summary>
55    /// Gets the current global scope.
56    /// </summary>
57    public IScope GlobalScope {
58      get { return myGlobalScope; }
59    }
60
61    [Storable]
62    private TimeSpan myExecutionTime;
63    /// <summary>
64    /// Gets or sets the execution time.
65    /// </summary>
66    /// <remarks>Calls <see cref="OnExecutionTimeChanged"/> in the setter.</remarks>
67    public TimeSpan ExecutionTime {
68      get { return myExecutionTime; }
69      protected set {
70        myExecutionTime = value;
71        OnExecutionTimeChanged();
72      }
73    }
74
75    /// <summary>
76    /// Field of the current instance that represent the execution stack.
77    /// </summary>
78    [Storable]
79    protected Stack<IOperation> myExecutionStack;
80    /// <summary>
81    /// Gets the current execution stack.
82    /// </summary>
83    public Stack<IOperation> ExecutionStack {
84      get { return myExecutionStack; }
85    }
86
87    /// <summary>
88    /// Flag of the current instance whether it is currently running.
89    /// </summary>
90    protected bool myRunning;
91    /// <summary>
92    /// Gets information whether the instance is currently running.
93    /// </summary>
94    public bool Running {
95      get { return myRunning; }
96    }
97
98    /// <summary>
99    /// Flag of the current instance whether it is canceled.
100    /// </summary>
101    protected bool myCanceled;
102    /// <summary>
103    /// Gets information whether the instance is currently canceled.
104    /// </summary>
105    public bool Canceled {
106      get { return myCanceled; }
107    }
108    /// <summary>
109    /// Gets information whether the instance has already terminated.
110    /// </summary>
111    public virtual bool Terminated {
112      get { return ExecutionStack.Count == 0; }
113    }
114
115    /// <summary>
116    /// Initializes a new instance of <see cref="EngineBase"/> with a new global scope.
117    /// </summary>
118    /// <remarks>Calls <see cref="Reset"/>.</remarks>
119    protected EngineBase() {
120      myOperatorGraph = new OperatorGraph();
121      myGlobalScope = new Scope("Global");
122      myExecutionStack = new Stack<IOperation>();
123      Reset();
124    }
125
126    /// <summary>
127    /// Clones the current instance (deep clone).
128    /// </summary>
129    /// <remarks>Deep clone through <see cref="Auxiliary.Clone"/> method of helper class
130    /// <see cref="Auxiliary"/>.</remarks>
131    /// <param name="clonedObjects">Dictionary of all already clone objects. (Needed to avoid cycles.)</param>
132    /// <returns>The cloned object as <see cref="EngineBase"/>.</returns>
133    public override object Clone(IDictionary<Guid, object> clonedObjects) {
134      EngineBase clone = (EngineBase)base.Clone(clonedObjects);
135      clone.myOperatorGraph = (IOperatorGraph)Auxiliary.Clone(OperatorGraph, clonedObjects);
136      clone.myGlobalScope = (IScope)Auxiliary.Clone(GlobalScope, clonedObjects);
137      clone.myExecutionTime = ExecutionTime;
138      IOperation[] operations = new IOperation[ExecutionStack.Count];
139      ExecutionStack.CopyTo(operations, 0);
140      for (int i = operations.Length - 1; i >= 0; i--)
141        clone.myExecutionStack.Push((IOperation)Auxiliary.Clone(operations[i], clonedObjects));
142      clone.myRunning = Running;
143      clone.myCanceled = Canceled;
144      return clone;
145    }
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 Execute() {
151      myRunning = true;
152      myCanceled = false;
153      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
154    }
155    /// <inheritdoc/>
156    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
157    /// of class <see cref="ThreadPool"/>.</remarks>
158    public virtual void ExecuteSteps(int steps) {
159      myRunning = true;
160      myCanceled = false;
161      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), steps);
162    }
163    /// <inheritdoc/>
164    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
165    /// of class <see cref="ThreadPool"/>.</remarks>
166    public void ExecuteStep() {
167      ExecuteSteps(1);
168    }
169    /// <inheritdoc/>
170    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
171    public virtual void Abort() {
172      myCanceled = true;
173    }
174    /// <inheritdoc/>
175    /// <remarks>Sets <c>myCanceled</c> and <c>myRunning</c> to <c>false</c>. The global scope is cleared,
176    /// the execution time is reseted, the execution stack is cleared and a new <see cref="AtomicOperation"/>
177    /// with the initial operator is added. <br/>
178    /// Calls <see cref="OnInitialized"/>.</remarks>
179    public virtual void Reset() {
180      myCanceled = false;
181      myRunning = false;
182      GlobalScope.Clear();
183      ExecutionTime = new TimeSpan();
184      myExecutionStack.Clear();
185      if (OperatorGraph.InitialOperator != null)
186        myExecutionStack.Push(new AtomicOperation(OperatorGraph.InitialOperator, GlobalScope));
187      OnInitialized();
188    }
189
190    private void Run(object state) {
191      if (state == null) Run();
192      else RunSteps((int)state);
193      myRunning = false;
194      OnFinished();
195    }
196    private void Run() {
197      DateTime start = DateTime.Now;
198      DateTime end;
199      while ((!Canceled) && (!Terminated)) {
200        ProcessNextOperation();
201        end = DateTime.Now;
202        ExecutionTime += end - start;
203        start = end;
204      }
205      ExecutionTime += DateTime.Now - start;
206    }
207    private void RunSteps(int steps) {
208      DateTime start = DateTime.Now;
209      DateTime end;
210      int step = 0;
211      while ((!Canceled) && (!Terminated) && (step < steps)) {
212        ProcessNextOperation();
213        step++;
214        end = DateTime.Now;
215        ExecutionTime += end - start;
216        start = end;
217      }
218      ExecutionTime += DateTime.Now - start;
219    }
220
221    /// <summary>
222    /// Performs the next operation.
223    /// </summary>
224    protected abstract void ProcessNextOperation();
225
226    /// <summary>
227    /// Occurs when the current instance is initialized.
228    /// </summary>
229    public event EventHandler Initialized;
230    /// <summary>
231    /// Fires a new <c>Initialized</c> event.
232    /// </summary>
233    protected virtual void OnInitialized() {
234      if (Initialized != null)
235        Initialized(this, new EventArgs());
236    }
237    /// <summary>
238    /// Occurs when an operation is executed.
239    /// </summary>
240    public event EventHandler<EventArgs<IOperation>> OperationExecuted;
241    /// <summary>
242    /// Fires a new <c>OperationExecuted</c> event.
243    /// </summary>
244    /// <param name="operation">The operation that has been executed.</param>
245    protected virtual void OnOperationExecuted(IOperation operation) {
246      if (OperationExecuted != null)
247        OperationExecuted(this, new EventArgs<IOperation>(operation));
248    }
249    /// <summary>
250    /// Occurs when an exception occured during the execution.
251    /// </summary>
252    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
253    /// <summary>
254    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
255    /// </summary>
256    /// <param name="exception">The exception that was thrown.</param>
257    protected virtual void OnExceptionOccurred(Exception exception) {
258      Abort();
259      if (ExceptionOccurred != null)
260        ExceptionOccurred(this, new EventArgs<Exception>(exception));
261    }
262    /// <summary>
263    /// Occurs when the execution time changed.
264    /// </summary>
265    public event EventHandler ExecutionTimeChanged;
266    /// <summary>
267    /// Fires a new <c>ExecutionTimeChanged</c> event.
268    /// </summary>
269    protected virtual void OnExecutionTimeChanged() {
270      if (ExecutionTimeChanged != null)
271        ExecutionTimeChanged(this, new EventArgs());
272    }
273    /// <summary>
274    /// Occurs when the execution is finished.
275    /// </summary>
276    public event EventHandler Finished;
277    /// <summary>
278    /// Fires a new <c>Finished</c> event.
279    /// </summary>
280    protected virtual void OnFinished() {
281      if (Finished != null)
282        Finished(this, new EventArgs());
283    }
284  }
285}
Note: See TracBrowser for help on using the repository browser.