Free cookie consent management tool by TermsFeed Policy Generator

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

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

Operator architecture refactoring (#95)

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