Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization/3.3/BatchRun.cs @ 3280

Last change on this file since 3280 was 3280, checked in by swagner, 12 years ago

Continued work on algorithm batch processing (#947).

File size: 11.4 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.Drawing;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.Collections;
28
29namespace HeuristicLab.Optimization {
30  /// <summary>
31  /// A run in which an algorithm is executed a given number of times.
32  /// </summary>
33  [Item("Batch Run", "A run in which an algorithm is executed a given number of times.")]
34  [Creatable("Testing & Analysis")]
35  [StorableClass]
36  public sealed class BatchRun : NamedItem, IOptimizer {
37    public override Image ItemImage {
38      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Event; }
39    }
40
41    [Storable]
42    private ExecutionState executionState;
43    public ExecutionState ExecutionState {
44      get { return executionState; }
45      private set {
46        if (executionState != value) {
47          executionState = value;
48          OnExecutionStateChanged();
49        }
50      }
51    }
52
53    [Storable]
54    private TimeSpan executionTime;
55    public TimeSpan ExecutionTime {
56      get {
57        if ((Algorithm != null) && (Algorithm.ExecutionState != ExecutionState.Stopped))
58          return executionTime + Algorithm.ExecutionTime;
59        else
60          return executionTime;
61      }
62      private set {
63        executionTime = value;
64        OnExecutionTimeChanged();
65      }
66    }
67
68    [Storable]
69    private IAlgorithm algorithm;
70    public IAlgorithm Algorithm {
71      get { return algorithm; }
72      set {
73        if (algorithm != value) {
74          if (algorithm != null) DeregisterAlgorithmEvents();
75          algorithm = value;
76          if (algorithm != null) RegisterAlgorithmEvents();
77          OnAlgorithmChanged();
78          Prepare(true);
79        }
80      }
81    }
82
83    [Storable]
84    private int repetitions;
85    public int Repetitions {
86      get { return repetitions; }
87      set {
88        if (repetitions != value) {
89          repetitions = value;
90          OnRepetitionsChanged();
91          if ((runs.Count < repetitions) && (Algorithm != null) && (Algorithm.ExecutionState == ExecutionState.Stopped))
92            Prepare();
93        }
94      }
95    }
96
97    [Storable]
98    private RunCollection runs;
99    public RunCollection Runs {
100      get { return runs; }
101    }
102
103    private bool stopPending;
104
105    public BatchRun()
106      : base() {
107      name = ItemName;
108      description = ItemDescription;
109      executionState = ExecutionState.Stopped;
110      executionTime = TimeSpan.Zero;
111      repetitions = 10;
112      runs = new RunCollection();
113      stopPending = false;
114    }
115    public BatchRun(string name)
116      : base(name) {
117      description = ItemDescription;
118      executionState = ExecutionState.Stopped;
119      executionTime = TimeSpan.Zero;
120      repetitions = 10;
121      runs = new RunCollection();
122      stopPending = false;
123    }
124    public BatchRun(string name, string description)
125      : base(name, description) {
126      executionState = ExecutionState.Stopped;
127      executionTime = TimeSpan.Zero;
128      repetitions = 10;
129      runs = new RunCollection();
130      stopPending = false;
131    }
132    [StorableConstructor]
133    private BatchRun(bool deserializing)
134      : base(deserializing) {
135      stopPending = false;
136    }
137
138    [StorableHook(HookType.AfterDeserialization)]
139    private void Initialize() {
140      if (algorithm != null) RegisterAlgorithmEvents();
141    }
142
143    public override IDeepCloneable Clone(Cloner cloner) {
144      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
145      BatchRun clone = (BatchRun)base.Clone(cloner);
146      clone.executionState = executionState;
147      clone.executionTime = executionTime;
148      clone.algorithm = (IAlgorithm)cloner.Clone(algorithm);
149      clone.repetitions = repetitions;
150      clone.runs = (RunCollection)cloner.Clone(runs);
151      clone.stopPending = stopPending;
152      clone.Initialize();
153      return clone;
154    }
155
156    public void Prepare() {
157      Prepare(false);
158    }
159    public void Prepare(bool clearRuns) {
160      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
161        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
162      if (Algorithm != null) {
163        if (clearRuns) {
164          ExecutionTime = TimeSpan.Zero;
165          runs.Clear();
166        }
167        Algorithm.Prepare(clearRuns);
168      }
169    }
170    public void Start() {
171      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
172        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
173      if (Algorithm != null) Algorithm.Start();
174    }
175    public void Pause() {
176      if (ExecutionState != ExecutionState.Started)
177        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
178      if (Algorithm != null) Algorithm.Pause();
179    }
180    public void Stop() {
181      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
182        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
183      stopPending = true;
184      if (Algorithm != null) Algorithm.Stop();
185    }
186
187    #region Events
188    public event EventHandler ExecutionStateChanged;
189    private void OnExecutionStateChanged() {
190      EventHandler handler = ExecutionStateChanged;
191      if (handler != null) handler(this, EventArgs.Empty);
192    }
193    public event EventHandler ExecutionTimeChanged;
194    private void OnExecutionTimeChanged() {
195      EventHandler handler = ExecutionTimeChanged;
196      if (handler != null) handler(this, EventArgs.Empty);
197    }
198    public event EventHandler AlgorithmChanged;
199    private void OnAlgorithmChanged() {
200      EventHandler handler = AlgorithmChanged;
201      if (handler != null) handler(this, EventArgs.Empty);
202    }
203    public event EventHandler RepetitionsChanged;
204    private void OnRepetitionsChanged() {
205      EventHandler handler = RepetitionsChanged;
206      if (handler != null) handler(this, EventArgs.Empty);
207    }
208    public event EventHandler Prepared;
209    private void OnPrepared() {
210      ExecutionState = ExecutionState.Prepared;
211      EventHandler handler = Prepared;
212      if (handler != null) handler(this, EventArgs.Empty);
213    }
214    public event EventHandler Started;
215    private void OnStarted() {
216      ExecutionState = ExecutionState.Started;
217      EventHandler handler = Started;
218      if (handler != null) handler(this, EventArgs.Empty);
219    }
220    public event EventHandler Paused;
221    private void OnPaused() {
222      ExecutionState = ExecutionState.Paused;
223      EventHandler handler = Paused;
224      if (handler != null) handler(this, EventArgs.Empty);
225    }
226    public event EventHandler Stopped;
227    private void OnStopped() {
228      ExecutionState = ExecutionState.Stopped;
229      EventHandler handler = Stopped;
230      if (handler != null) handler(this, EventArgs.Empty);
231    }
232    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
233    private void OnExceptionOccurred(Exception exception) {
234      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
235      if (handler != null) handler(this, new EventArgs<Exception>(exception));
236    }
237
238    private void RegisterAlgorithmEvents() {
239      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Algorithm_ExceptionOccurred);
240      algorithm.ExecutionTimeChanged += new EventHandler(Algorithm_ExecutionTimeChanged);
241      algorithm.Paused += new EventHandler(Algorithm_Paused);
242      algorithm.Prepared += new EventHandler(Algorithm_Prepared);
243      algorithm.Started += new EventHandler(Algorithm_Started);
244      algorithm.Stopped += new EventHandler(Algorithm_Stopped);
245      algorithm.Runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_CollectionReset);
246      algorithm.Runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_ItemsAdded);
247      algorithm.Runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_ItemsRemoved);
248    }
249    private void DeregisterAlgorithmEvents() {
250      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Algorithm_ExceptionOccurred);
251      algorithm.ExecutionTimeChanged -= new EventHandler(Algorithm_ExecutionTimeChanged);
252      algorithm.Paused -= new EventHandler(Algorithm_Paused);
253      algorithm.Prepared -= new EventHandler(Algorithm_Prepared);
254      algorithm.Started -= new EventHandler(Algorithm_Started);
255      algorithm.Stopped -= new EventHandler(Algorithm_Stopped);
256      algorithm.Runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_CollectionReset);
257      algorithm.Runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_ItemsAdded);
258      algorithm.Runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_ItemsRemoved);
259    }
260    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
261      OnExceptionOccurred(e.Value);
262    }
263    private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
264      OnExecutionTimeChanged();
265    }
266    private void Algorithm_Paused(object sender, EventArgs e) {
267      OnPaused();
268    }
269    private void Algorithm_Prepared(object sender, EventArgs e) {
270      if ((ExecutionState == ExecutionState.Paused) || (ExecutionState == ExecutionState.Stopped))
271        OnPrepared();
272    }
273    private void Algorithm_Started(object sender, EventArgs e) {
274      stopPending = false;
275      if (ExecutionState != ExecutionState.Started)
276        OnStarted();
277    }
278    private void Algorithm_Stopped(object sender, EventArgs e) {
279      ExecutionTime += Algorithm.ExecutionTime;
280
281      if (!stopPending && (runs.Count < repetitions)) {
282        Algorithm.Prepare();
283        Algorithm.Start();
284      } else {
285        OnStopped();
286      }
287    }
288    private void Algorithm_Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
289      Runs.RemoveRange(e.OldItems);
290      Runs.AddRange(e.Items);
291    }
292    private void Algorithm_Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
293      Runs.AddRange(e.Items);
294    }
295    private void Algorithm_Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
296      Runs.RemoveRange(e.Items);
297    }
298    #endregion
299  }
300}
Note: See TracBrowser for help on using the repository browser.