Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3260 was 3226, checked in by swagner, 15 years ago

Implemented first version of algorithm batch processing (#947).

File size: 8.5 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      Running = true;
145      Canceled = false;
146      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
147    }
148    /// <inheritdoc/>
149    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
150    /// of class <see cref="ThreadPool"/>.</remarks>
151    public void Step() {
152      Running = true;
153      Canceled = false;
154      ThreadPool.QueueUserWorkItem(new WaitCallback(RunStep), null);
155    }
156    /// <inheritdoc/>
157    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
158    public void Stop() {
159      Canceled = true;
160    }
161
162    private void Run(object state) {
163      OnStarted();
164      DateTime start = DateTime.Now;
165      DateTime end;
166      while ((!Canceled) && (!Finished)) {
167        ProcessNextOperator();
168        end = DateTime.Now;
169        ExecutionTime += end - start;
170        start = end;
171      }
172      ExecutionTime += DateTime.Now - start;
173      OnStopped();
174    }
175    private void RunStep(object state) {
176      OnStarted();
177      DateTime start = DateTime.Now;
178      if ((!Canceled) && (!Finished))
179        ProcessNextOperator();
180      ExecutionTime += DateTime.Now - start;
181      OnStopped();
182    }
183
184    /// <summary>
185    /// Performs the next operation.
186    /// </summary>
187    protected abstract void ProcessNextOperator();
188
189    /// <summary>
190    /// Occurs when the execution time changed.
191    /// </summary>
192    public event EventHandler ExecutionTimeChanged;
193    /// <summary>
194    /// Fires a new <c>ExecutionTimeChanged</c> event.
195    /// </summary>
196    protected virtual void OnExecutionTimeChanged() {
197      if (ExecutionTimeChanged != null)
198        ExecutionTimeChanged(this, EventArgs.Empty);
199    }
200    /// <summary>
201    /// Occurs when the running flag changed.
202    /// </summary>
203    public event EventHandler RunningChanged;
204    /// <summary>
205    /// Fires a new <c>RunningChanged</c> event.
206    /// </summary>
207    protected virtual void OnRunningChanged() {
208      if (RunningChanged != null)
209        RunningChanged(this, EventArgs.Empty);
210    }
211    /// <summary>
212    /// Occurs when the execution is prepared for a new run.
213    /// </summary>
214    public event EventHandler Prepared;
215    /// <summary>
216    /// Fires a new <c>Prepared</c> event.
217    /// </summary>
218    protected virtual void OnPrepared() {
219      if (Prepared != null)
220        Prepared(this, EventArgs.Empty);
221    }
222    /// <summary>
223    /// Occurs when the execution is executed.
224    /// </summary>
225    public event EventHandler Started;
226    /// <summary>
227    /// Fires a new <c>Started</c> event.
228    /// </summary>
229    protected virtual void OnStarted() {
230      if (Started != null)
231        Started(this, EventArgs.Empty);
232    }
233    /// <summary>
234    /// Occurs when the execution is finished.
235    /// </summary>
236    public event EventHandler Stopped;
237    /// <summary>
238    /// Fires a new <c>Stopped</c> event.
239    /// </summary>
240    protected virtual void OnStopped() {
241      if (Stopped != null)
242        Stopped(this, EventArgs.Empty);
243      Canceled = false;
244      Running = false;
245    }
246    protected virtual void OnCanceledChanged() { }
247    /// <summary>
248    /// Occurs when an exception occured during the execution.
249    /// </summary>
250    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
251    /// <summary>
252    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
253    /// </summary>
254    /// <param name="exception">The exception that was thrown.</param>
255    protected virtual void OnExceptionOccurred(Exception exception) {
256      if (ExceptionOccurred != null)
257        ExceptionOccurred(this, new EventArgs<Exception>(exception));
258    }
259  }
260}
Note: See TracBrowser for help on using the repository browser.