Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Scheduling/HeuristicLab.Optimization/3.3/BatchRun.cs @ 6824

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

Updated year of copyrights (#1406)

File size: 15.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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 HeuristicLab.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Optimization {
32  /// <summary>
33  /// A run in which an optimizer is executed a given number of times.
34  /// </summary>
35  [Item("Batch Run", "A run in which an optimizer is executed a given number of times.")]
36  [Creatable("Testing & Analysis")]
37  [StorableClass]
38  public sealed class BatchRun : NamedItem, IOptimizer, IStorableContent {
39    public string Filename { get; set; }
40
41    public override Image ItemImage {
42      get {
43        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
44        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
45        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
46        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
47        else return HeuristicLab.Common.Resources.VSImageLibrary.Event;
48      }
49    }
50
51    [Storable]
52    private ExecutionState executionState;
53    public ExecutionState ExecutionState {
54      get { return executionState; }
55      private set {
56        if (executionState != value) {
57          executionState = value;
58          OnExecutionStateChanged();
59          OnItemImageChanged();
60        }
61      }
62    }
63
64    [Storable]
65    private TimeSpan executionTime;
66    public TimeSpan ExecutionTime {
67      get {
68        if ((Optimizer != null) && (Optimizer.ExecutionState != ExecutionState.Stopped))
69          return executionTime + Optimizer.ExecutionTime;
70        else
71          return executionTime;
72      }
73      private set {
74        executionTime = value;
75        OnExecutionTimeChanged();
76      }
77    }
78
79    [Storable]
80    private IOptimizer optimizer;
81    public IOptimizer Optimizer {
82      get { return optimizer; }
83      set {
84        if (optimizer != value) {
85          if (optimizer != null) {
86            DeregisterOptimizerEvents();
87            IEnumerable<IRun> runs = optimizer.Runs;
88            optimizer = null; //necessary to avoid removing the runs from the old optimizer
89            Runs.RemoveRange(runs);
90          }
91          optimizer = value;
92          if (optimizer != null) {
93            RegisterOptimizerEvents();
94            Runs.AddRange(optimizer.Runs);
95          }
96          OnOptimizerChanged();
97          Prepare();
98        }
99      }
100    }
101    // BackwardsCompatibility3.3
102    #region Backwards compatible code (remove with 3.4)
103    [Storable(AllowOneWay = true)]
104    private IAlgorithm algorithm {
105      set { optimizer = value; }
106    }
107    #endregion
108
109    [Storable]
110    private int repetitions;
111    public int Repetitions {
112      get { return repetitions; }
113      set {
114        if (repetitions != value) {
115          repetitions = value;
116          OnRepetitionsChanged();
117          if ((Optimizer != null) && (Optimizer.ExecutionState == ExecutionState.Stopped))
118            Prepare();
119        }
120      }
121    }
122    [Storable]
123    private int repetitionsCounter;
124
125    [Storable]
126    private RunCollection runs;
127    public RunCollection Runs {
128      get { return runs; }
129      private set {
130        if (value == null) throw new ArgumentNullException();
131        if (runs != value) {
132          if (runs != null) DeregisterRunsEvents();
133          runs = value;
134          if (runs != null) RegisterRunsEvents();
135        }
136      }
137    }
138
139    public IEnumerable<IOptimizer> NestedOptimizers {
140      get {
141        if (Optimizer == null) yield break;
142
143        yield return Optimizer;
144        foreach (IOptimizer opt in Optimizer.NestedOptimizers)
145          yield return opt;
146      }
147    }
148
149    private bool stopPending;
150
151    public BatchRun()
152      : base() {
153      name = ItemName;
154      description = ItemDescription;
155      executionState = ExecutionState.Stopped;
156      executionTime = TimeSpan.Zero;
157      repetitions = 10;
158      repetitionsCounter = 0;
159      Runs = new RunCollection();
160      stopPending = false;
161    }
162    public BatchRun(string name)
163      : base(name) {
164      description = ItemDescription;
165      executionState = ExecutionState.Stopped;
166      executionTime = TimeSpan.Zero;
167      repetitions = 10;
168      repetitionsCounter = 0;
169      Runs = new RunCollection();
170      stopPending = false;
171    }
172    public BatchRun(string name, string description)
173      : base(name, description) {
174      executionState = ExecutionState.Stopped;
175      executionTime = TimeSpan.Zero;
176      repetitions = 10;
177      repetitionsCounter = 0;
178      Runs = new RunCollection();
179      stopPending = false;
180    }
181    [StorableConstructor]
182    private BatchRun(bool deserializing)
183      : base(deserializing) {
184      stopPending = false;
185    }
186    [StorableHook(HookType.AfterDeserialization)]
187    private void AfterDeserialization() {
188      Initialize();
189    }
190
191    private BatchRun(BatchRun original, Cloner cloner)
192      : base(original, cloner) {
193      executionState = original.executionState;
194      executionTime = original.executionTime;
195      optimizer = cloner.Clone(original.optimizer);
196      repetitions = original.repetitions;
197      repetitionsCounter = original.repetitionsCounter;
198      runs = cloner.Clone(original.runs);
199      stopPending = original.stopPending;
200      Initialize();
201    }
202    public override IDeepCloneable Clone(Cloner cloner) {
203      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
204      return new BatchRun(this, cloner);
205    }
206
207    private void Initialize() {
208      if (optimizer != null) RegisterOptimizerEvents();
209      if (runs != null) RegisterRunsEvents();
210    }
211
212    public void Prepare() {
213      Prepare(false);
214    }
215    public void Prepare(bool clearRuns) {
216      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
217        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
218      if (Optimizer != null) {
219        repetitionsCounter = 0;
220        if (clearRuns) runs.Clear();
221        Optimizer.Prepare(clearRuns);
222      }
223    }
224    public void Start() {
225      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
226        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
227      if (Optimizer != null) Optimizer.Start();
228    }
229    public void Pause() {
230      if (ExecutionState != ExecutionState.Started)
231        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
232      if ((Optimizer != null) && (Optimizer.ExecutionState == ExecutionState.Started))
233        Optimizer.Pause();
234    }
235    public void Stop() {
236      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
237        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
238      stopPending = true;
239      if ((Optimizer != null) &&
240          ((Optimizer.ExecutionState == ExecutionState.Started) || (Optimizer.ExecutionState == ExecutionState.Paused)))
241        Optimizer.Stop();
242    }
243
244    #region Events
245    public event EventHandler ExecutionStateChanged;
246    private void OnExecutionStateChanged() {
247      EventHandler handler = ExecutionStateChanged;
248      if (handler != null) handler(this, EventArgs.Empty);
249    }
250    public event EventHandler ExecutionTimeChanged;
251    private void OnExecutionTimeChanged() {
252      EventHandler handler = ExecutionTimeChanged;
253      if (handler != null) handler(this, EventArgs.Empty);
254    }
255    public event EventHandler OptimizerChanged;
256    private void OnOptimizerChanged() {
257      EventHandler handler = OptimizerChanged;
258      if (handler != null) handler(this, EventArgs.Empty);
259    }
260    public event EventHandler RepetitionsChanged;
261    private void OnRepetitionsChanged() {
262      EventHandler handler = RepetitionsChanged;
263      if (handler != null) handler(this, EventArgs.Empty);
264    }
265    public event EventHandler Prepared;
266    private void OnPrepared() {
267      ExecutionState = ExecutionState.Prepared;
268      EventHandler handler = Prepared;
269      if (handler != null) handler(this, EventArgs.Empty);
270    }
271    public event EventHandler Started;
272    private void OnStarted() {
273      ExecutionState = ExecutionState.Started;
274      EventHandler handler = Started;
275      if (handler != null) handler(this, EventArgs.Empty);
276    }
277    public event EventHandler Paused;
278    private void OnPaused() {
279      ExecutionState = ExecutionState.Paused;
280      EventHandler handler = Paused;
281      if (handler != null) handler(this, EventArgs.Empty);
282    }
283    public event EventHandler Stopped;
284    private void OnStopped() {
285      ExecutionState = ExecutionState.Stopped;
286      EventHandler handler = Stopped;
287      if (handler != null) handler(this, EventArgs.Empty);
288    }
289    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
290    private void OnExceptionOccurred(Exception exception) {
291      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
292      if (handler != null) handler(this, new EventArgs<Exception>(exception));
293    }
294
295    private void RegisterOptimizerEvents() {
296      optimizer.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Optimizer_ExceptionOccurred);
297      optimizer.ExecutionTimeChanged += new EventHandler(Optimizer_ExecutionTimeChanged);
298      optimizer.Paused += new EventHandler(Optimizer_Paused);
299      optimizer.Prepared += new EventHandler(Optimizer_Prepared);
300      optimizer.Started += new EventHandler(Optimizer_Started);
301      optimizer.Stopped += new EventHandler(Optimizer_Stopped);
302      optimizer.Runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_CollectionReset);
303      optimizer.Runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsAdded);
304      optimizer.Runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsRemoved);
305    }
306    private void DeregisterOptimizerEvents() {
307      optimizer.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Optimizer_ExceptionOccurred);
308      optimizer.ExecutionTimeChanged -= new EventHandler(Optimizer_ExecutionTimeChanged);
309      optimizer.Paused -= new EventHandler(Optimizer_Paused);
310      optimizer.Prepared -= new EventHandler(Optimizer_Prepared);
311      optimizer.Started -= new EventHandler(Optimizer_Started);
312      optimizer.Stopped -= new EventHandler(Optimizer_Stopped);
313      optimizer.Runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_CollectionReset);
314      optimizer.Runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsAdded);
315      optimizer.Runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsRemoved);
316    }
317    private void Optimizer_ExceptionOccurred(object sender, EventArgs<Exception> e) {
318      OnExceptionOccurred(e.Value);
319    }
320    private void Optimizer_ExecutionTimeChanged(object sender, EventArgs e) {
321      OnExecutionTimeChanged();
322    }
323    private void Optimizer_Paused(object sender, EventArgs e) {
324      OnPaused();
325    }
326    private void Optimizer_Prepared(object sender, EventArgs e) {
327      if ((ExecutionState == ExecutionState.Paused) || (ExecutionState == ExecutionState.Stopped))
328        OnPrepared();
329    }
330    private void Optimizer_Started(object sender, EventArgs e) {
331      stopPending = false;
332      if (ExecutionState != ExecutionState.Started)
333        OnStarted();
334    }
335    private void Optimizer_Stopped(object sender, EventArgs e) {
336      repetitionsCounter++;
337
338      if (!stopPending && (repetitionsCounter < repetitions)) {
339        Optimizer.Prepare();
340        Optimizer.Start();
341      } else {
342        OnStopped();
343      }
344    }
345    private void Optimizer_Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
346      Runs.RemoveRange(e.OldItems);
347      Runs.AddRange(e.Items);
348    }
349    private void Optimizer_Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
350      Runs.AddRange(e.Items);
351    }
352    private void Optimizer_Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
353      Runs.RemoveRange(e.Items);
354    }
355
356    private void RegisterRunsEvents() {
357      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
358      runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
359      runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
360    }
361
362    private void DeregisterRunsEvents() {
363      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
364      runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
365      runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
366    }
367    private void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
368      foreach (IRun run in e.OldItems) {
369        IItem item;
370        run.Results.TryGetValue("Execution Time", out item);
371        TimeSpanValue executionTime = item as TimeSpanValue;
372        if (executionTime != null) ExecutionTime -= executionTime.Value;
373      }
374      if (Optimizer != null) Optimizer.Runs.RemoveRange(e.OldItems);
375      foreach (IRun run in e.Items) {
376        IItem item;
377        run.Results.TryGetValue("Execution Time", out item);
378        TimeSpanValue executionTime = item as TimeSpanValue;
379        if (executionTime != null) ExecutionTime += executionTime.Value;
380      }
381    }
382    private void Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
383      foreach (IRun run in e.Items) {
384        IItem item;
385        run.Results.TryGetValue("Execution Time", out item);
386        TimeSpanValue executionTime = item as TimeSpanValue;
387        if (executionTime != null) ExecutionTime += executionTime.Value;
388      }
389    }
390    private void Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
391      foreach (IRun run in e.Items) {
392        IItem item;
393        run.Results.TryGetValue("Execution Time", out item);
394        TimeSpanValue executionTime = item as TimeSpanValue;
395        if (executionTime != null) ExecutionTime -= executionTime.Value;
396      }
397      if (Optimizer != null) Optimizer.Runs.RemoveRange(e.Items);
398    }
399    #endregion
400  }
401}
Note: See TracBrowser for help on using the repository browser.