Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core/3.3/Engine.cs @ 3261

Last change on this file since 3261 was 3261, checked in by swagner, 14 years ago

Continued work on algorithm batch processing (#947).

File size: 8.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Drawing;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Core {
30  /// <summary>
31  /// Base class to represent an engine, which is an interpreter, holding the code, the data and
32  /// the actual state, which is the runtime stack and a pointer onto the next operation. It represents
33  /// one execution and can handle parallel executions.
34  /// </summary>
35  [Item("Engine", "A base class for engines.")]
36  [StorableClass]
37  public abstract class Engine : Item, IEngine {
38    public override Image ItemImage {
39      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Event; }
40    }
41
42    [Storable]
43    private TimeSpan executionTime;
44    /// <summary>
45    /// Gets or sets the execution time.
46    /// </summary>
47    /// <remarks>Calls <see cref="OnExecutionTimeChanged"/> in the setter.</remarks>
48    public TimeSpan ExecutionTime {
49      get { return executionTime; }
50      protected set {
51        executionTime = value;
52        OnExecutionTimeChanged();
53      }
54    }
55
56    /// <summary>
57    /// Field of the current instance that represent the execution stack.
58    /// </summary>
59    [Storable]
60    private Stack<IOperation> executionStack;
61    /// <summary>
62    /// Gets the current execution stack.
63    /// </summary>
64    protected Stack<IOperation> ExecutionStack {
65      get { return executionStack; }
66    }
67
68    /// <summary>
69    /// Flag of the current instance whether it is currently running.
70    /// </summary>
71    private bool running;
72    /// <summary>
73    /// Gets information whether the instance is currently running.
74    /// </summary>
75    public bool Running {
76      get { return running; }
77      private set {
78        if (running != value) {
79          running = value;
80          OnRunningChanged();
81        }
82      }
83    }
84
85    /// <summary>
86    /// Flag of the current instance whether it is canceled.
87    /// </summary>
88    private bool canceled;
89    /// <summary>
90    /// Gets information whether the instance is currently canceled.
91    /// </summary>
92    protected bool Canceled {
93      get { return canceled; }
94      private set {
95        if (canceled != value) {
96          canceled = value;
97          OnCanceledChanged();
98        }
99      }
100    }
101    /// <summary>
102    /// Gets information whether the instance has already terminated.
103    /// </summary>
104    public bool Finished {
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    protected Engine() {
112      executionStack = new Stack<IOperation>();
113    }
114
115    /// <summary>
116    /// Clones the current instance (deep clone).
117    /// </summary>
118    /// <remarks>Deep clone through <see cref="cloner.Clone"/> method of helper class
119    /// <see cref="Auxiliary"/>.</remarks>
120    /// <param name="clonedObjects">Dictionary of all already clone objects. (Needed to avoid cycles.)</param>
121    /// <returns>The cloned object as <see cref="EngineBase"/>.</returns>
122    public override IDeepCloneable Clone(Cloner cloner) {
123      Engine clone = (Engine)base.Clone(cloner);
124      clone.executionTime = executionTime;
125      IOperation[] contexts = executionStack.ToArray();
126      for (int i = contexts.Length - 1; i >= 0; i--)
127        clone.executionStack.Push((IOperation)cloner.Clone(contexts[i]));
128      clone.running = running;
129      clone.canceled = canceled;
130      return clone;
131    }
132
133    public void Prepare(IOperation initialOperation) {
134      ExecutionTime = new TimeSpan();
135      executionStack.Clear();
136      if (initialOperation != null)
137        executionStack.Push(initialOperation);
138      OnPrepared();
139    }
140    /// <inheritdoc/>
141    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
142    /// of class <see cref="ThreadPool"/>.</remarks>
143    public void Start() {
144      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
145    }
146    /// <inheritdoc/>
147    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
148    /// of class <see cref="ThreadPool"/>.</remarks>
149    public void Step() {
150      ThreadPool.QueueUserWorkItem(new WaitCallback(RunStep), null);
151    }
152    /// <inheritdoc/>
153    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
154    public void Stop() {
155      Canceled = true;
156    }
157
158    private void Run(object state) {
159      OnStarted();
160      Running = true;
161      Canceled = false;
162      DateTime start = DateTime.Now;
163      DateTime end;
164      while ((!Canceled) && (!Finished)) {
165        ProcessNextOperator();
166        end = DateTime.Now;
167        ExecutionTime += end - start;
168        start = end;
169      }
170      ExecutionTime += DateTime.Now - start;
171      Canceled = false;
172      Running = false;
173      OnStopped();
174    }
175    private void RunStep(object state) {
176      OnStarted();
177      Running = true;
178      Canceled = false;
179      DateTime start = DateTime.Now;
180      if ((!Canceled) && (!Finished))
181        ProcessNextOperator();
182      ExecutionTime += DateTime.Now - start;
183      Canceled = false;
184      Running = false;
185      OnStopped();
186    }
187
188    /// <summary>
189    /// Performs the next operation.
190    /// </summary>
191    protected abstract void ProcessNextOperator();
192
193    /// <summary>
194    /// Occurs when the execution time changed.
195    /// </summary>
196    public event EventHandler ExecutionTimeChanged;
197    /// <summary>
198    /// Fires a new <c>ExecutionTimeChanged</c> event.
199    /// </summary>
200    protected virtual void OnExecutionTimeChanged() {
201      if (ExecutionTimeChanged != null)
202        ExecutionTimeChanged(this, EventArgs.Empty);
203    }
204    /// <summary>
205    /// Occurs when the running flag changed.
206    /// </summary>
207    public event EventHandler RunningChanged;
208    /// <summary>
209    /// Fires a new <c>RunningChanged</c> event.
210    /// </summary>
211    protected virtual void OnRunningChanged() {
212      if (RunningChanged != null)
213        RunningChanged(this, EventArgs.Empty);
214    }
215    /// <summary>
216    /// Occurs when the execution is prepared for a new run.
217    /// </summary>
218    public event EventHandler Prepared;
219    /// <summary>
220    /// Fires a new <c>Prepared</c> event.
221    /// </summary>
222    protected virtual void OnPrepared() {
223      if (Prepared != null)
224        Prepared(this, EventArgs.Empty);
225    }
226    /// <summary>
227    /// Occurs when the execution is executed.
228    /// </summary>
229    public event EventHandler Started;
230    /// <summary>
231    /// Fires a new <c>Started</c> event.
232    /// </summary>
233    protected virtual void OnStarted() {
234      if (Started != null)
235        Started(this, EventArgs.Empty);
236    }
237    /// <summary>
238    /// Occurs when the execution is finished.
239    /// </summary>
240    public event EventHandler Stopped;
241    /// <summary>
242    /// Fires a new <c>Stopped</c> event.
243    /// </summary>
244    protected virtual void OnStopped() {
245      if (Stopped != null)
246        Stopped(this, EventArgs.Empty);
247    }
248    protected virtual void OnCanceledChanged() { }
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      if (ExceptionOccurred != null)
259        ExceptionOccurred(this, new EventArgs<Exception>(exception));
260    }
261  }
262}
Note: See TracBrowser for help on using the repository browser.