Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP.Grammar.Editor/HeuristicLab.Optimization/3.3/BatchRun.cs @ 6784

Last change on this file since 6784 was 6784, checked in by mkommend, 13 years ago

#1479: Integrated trunk changes.

File size: 16.4 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.BatchRunPrepared;
44        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunStarted;
45        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunPaused;
46        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunStopped;
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 batchRunStarted = false;
150    private bool batchRunPaused = false;
151    private bool batchRunStopped = false;
152
153    public BatchRun()
154      : base() {
155      name = ItemName;
156      description = ItemDescription;
157      executionState = ExecutionState.Stopped;
158      executionTime = TimeSpan.Zero;
159      repetitions = 10;
160      repetitionsCounter = 0;
161      Runs = new RunCollection();
162    }
163    public BatchRun(string name)
164      : base(name) {
165      description = ItemDescription;
166      executionState = ExecutionState.Stopped;
167      executionTime = TimeSpan.Zero;
168      repetitions = 10;
169      repetitionsCounter = 0;
170      Runs = new RunCollection();
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    }
180    [StorableConstructor]
181    private BatchRun(bool deserializing) : base(deserializing) { }
182    [StorableHook(HookType.AfterDeserialization)]
183    private void AfterDeserialization() {
184      Initialize();
185    }
186
187    private BatchRun(BatchRun original, Cloner cloner)
188      : base(original, cloner) {
189      executionState = original.executionState;
190      executionTime = original.executionTime;
191      optimizer = cloner.Clone(original.optimizer);
192      repetitions = original.repetitions;
193      repetitionsCounter = original.repetitionsCounter;
194      runs = cloner.Clone(original.runs);
195      batchRunStarted = original.batchRunStarted;
196      batchRunPaused = original.batchRunPaused;
197      batchRunStopped = original.batchRunStopped;
198      Initialize();
199    }
200    public override IDeepCloneable Clone(Cloner cloner) {
201      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
202      return new BatchRun(this, cloner);
203    }
204
205    private void Initialize() {
206      if (optimizer != null) RegisterOptimizerEvents();
207      if (runs != null) RegisterRunsEvents();
208    }
209
210    public void Prepare() {
211      Prepare(false);
212    }
213    public void Prepare(bool clearRuns) {
214      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
215        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
216      if (Optimizer != null) {
217        repetitionsCounter = 0;
218        if (clearRuns) runs.Clear();
219        Optimizer.Prepare(clearRuns);
220      } else {
221        ExecutionState = ExecutionState.Stopped;
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) return;
228
229      batchRunStarted = true;
230      batchRunPaused = false;
231      batchRunStopped = false;
232      if (Optimizer.ExecutionState != ExecutionState.Prepared) Optimizer.Prepare();
233      Optimizer.Start();
234    }
235    public void Pause() {
236      if (ExecutionState != ExecutionState.Started)
237        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
238      if (Optimizer == null) return;
239      if (Optimizer.ExecutionState != ExecutionState.Started) return;
240
241      batchRunStarted = false;
242      batchRunPaused = true;
243      batchRunStopped = false;
244      Optimizer.Pause();
245    }
246    public void Stop() {
247      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
248        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
249      if (Optimizer == null) return;
250      if (Optimizer.ExecutionState != ExecutionState.Started && Optimizer.ExecutionState != ExecutionState.Paused) return;
251      batchRunStarted = false;
252      batchRunPaused = false;
253      batchRunStopped = true;
254      Optimizer.Stop();
255    }
256
257    #region Events
258    public event EventHandler ExecutionStateChanged;
259    private void OnExecutionStateChanged() {
260      EventHandler handler = ExecutionStateChanged;
261      if (handler != null) handler(this, EventArgs.Empty);
262    }
263    public event EventHandler ExecutionTimeChanged;
264    private void OnExecutionTimeChanged() {
265      EventHandler handler = ExecutionTimeChanged;
266      if (handler != null) handler(this, EventArgs.Empty);
267    }
268    public event EventHandler OptimizerChanged;
269    private void OnOptimizerChanged() {
270      EventHandler handler = OptimizerChanged;
271      if (handler != null) handler(this, EventArgs.Empty);
272    }
273    public event EventHandler RepetitionsChanged;
274    private void OnRepetitionsChanged() {
275      EventHandler handler = RepetitionsChanged;
276      if (handler != null) handler(this, EventArgs.Empty);
277    }
278    public event EventHandler Prepared;
279    private void OnPrepared() {
280      ExecutionState = ExecutionState.Prepared;
281      EventHandler handler = Prepared;
282      if (handler != null) handler(this, EventArgs.Empty);
283    }
284    public event EventHandler Started;
285    private void OnStarted() {
286      ExecutionState = ExecutionState.Started;
287      EventHandler handler = Started;
288      if (handler != null) handler(this, EventArgs.Empty);
289    }
290    public event EventHandler Paused;
291    private void OnPaused() {
292      ExecutionState = ExecutionState.Paused;
293      EventHandler handler = Paused;
294      if (handler != null) handler(this, EventArgs.Empty);
295    }
296    public event EventHandler Stopped;
297    private void OnStopped() {
298      ExecutionState = ExecutionState.Stopped;
299      EventHandler handler = Stopped;
300      if (handler != null) handler(this, EventArgs.Empty);
301    }
302    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
303    private void OnExceptionOccurred(Exception exception) {
304      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
305      if (handler != null) handler(this, new EventArgs<Exception>(exception));
306    }
307
308    private void RegisterOptimizerEvents() {
309      optimizer.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Optimizer_ExceptionOccurred);
310      optimizer.ExecutionTimeChanged += new EventHandler(Optimizer_ExecutionTimeChanged);
311      optimizer.Paused += new EventHandler(Optimizer_Paused);
312      optimizer.Prepared += new EventHandler(Optimizer_Prepared);
313      optimizer.Started += new EventHandler(Optimizer_Started);
314      optimizer.Stopped += new EventHandler(Optimizer_Stopped);
315      optimizer.Runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_CollectionReset);
316      optimizer.Runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsAdded);
317      optimizer.Runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsRemoved);
318    }
319    private void DeregisterOptimizerEvents() {
320      optimizer.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Optimizer_ExceptionOccurred);
321      optimizer.ExecutionTimeChanged -= new EventHandler(Optimizer_ExecutionTimeChanged);
322      optimizer.Paused -= new EventHandler(Optimizer_Paused);
323      optimizer.Prepared -= new EventHandler(Optimizer_Prepared);
324      optimizer.Started -= new EventHandler(Optimizer_Started);
325      optimizer.Stopped -= new EventHandler(Optimizer_Stopped);
326      optimizer.Runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_CollectionReset);
327      optimizer.Runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsAdded);
328      optimizer.Runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsRemoved);
329    }
330    private void Optimizer_ExceptionOccurred(object sender, EventArgs<Exception> e) {
331      OnExceptionOccurred(e.Value);
332    }
333    private void Optimizer_ExecutionTimeChanged(object sender, EventArgs e) {
334      OnExecutionTimeChanged();
335    }
336    private void Optimizer_Paused(object sender, EventArgs e) {
337      if (ExecutionState == ExecutionState.Started) {
338        batchRunStarted = false;
339        batchRunPaused = true;
340        batchRunStopped = false;
341        OnPaused();
342      }
343    }
344    private void Optimizer_Prepared(object sender, EventArgs e) {
345      if (ExecutionState == ExecutionState.Stopped || !batchRunStarted) {
346        OnPrepared();
347      }
348    }
349    private void Optimizer_Started(object sender, EventArgs e) {
350      if (ExecutionState != ExecutionState.Started)
351        OnStarted();
352    }
353    private void Optimizer_Stopped(object sender, EventArgs e) {
354      repetitionsCounter++;
355
356      if (batchRunStopped) OnStopped();
357      else if (repetitionsCounter >= repetitions) OnStopped();
358      else if (batchRunPaused) OnPaused();
359      else if (batchRunStarted) {
360        Optimizer.Prepare();
361        Optimizer.Start();
362      } else OnStopped();
363    }
364    private void Optimizer_Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
365      Runs.RemoveRange(e.OldItems);
366      Runs.AddRange(e.Items);
367    }
368    private void Optimizer_Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
369      Runs.AddRange(e.Items);
370    }
371    private void Optimizer_Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
372      Runs.RemoveRange(e.Items);
373    }
374
375    private void RegisterRunsEvents() {
376      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
377      runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
378      runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
379    }
380
381    private void DeregisterRunsEvents() {
382      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
383      runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
384      runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
385    }
386    private void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
387      foreach (IRun run in e.OldItems) {
388        IItem item;
389        run.Results.TryGetValue("Execution Time", out item);
390        TimeSpanValue executionTime = item as TimeSpanValue;
391        if (executionTime != null) ExecutionTime -= executionTime.Value;
392      }
393      if (Optimizer != null) Optimizer.Runs.RemoveRange(e.OldItems);
394      foreach (IRun run in e.Items) {
395        IItem item;
396        run.Results.TryGetValue("Execution Time", out item);
397        TimeSpanValue executionTime = item as TimeSpanValue;
398        if (executionTime != null) ExecutionTime += executionTime.Value;
399      }
400    }
401    private void Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
402      foreach (IRun run in e.Items) {
403        IItem item;
404        run.Results.TryGetValue("Execution Time", out item);
405        TimeSpanValue executionTime = item as TimeSpanValue;
406        if (executionTime != null) ExecutionTime += executionTime.Value;
407      }
408    }
409    private void Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
410      foreach (IRun run in e.Items) {
411        IItem item;
412        run.Results.TryGetValue("Execution Time", out item);
413        TimeSpanValue executionTime = item as TimeSpanValue;
414        if (executionTime != null) ExecutionTime -= executionTime.Value;
415      }
416      if (Optimizer != null) Optimizer.Runs.RemoveRange(e.Items);
417    }
418    #endregion
419  }
420}
Note: See TracBrowser for help on using the repository browser.