Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Optimization/3.3/MetaOptimizers/BatchRun.cs @ 16003

Last change on this file since 16003 was 13656, checked in by ascheibe, 9 years ago

#2582 created branch for Hive Web Job Manager

File size: 18.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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  internal enum BatchRunAction { None, Prepare, Start, Pause, Stop };
33
34  /// <summary>
35  /// A run in which an optimizer is executed a given number of times.
36  /// </summary>
37  [Item("Batch Run", "A run in which an optimizer is executed a given number of times.")]
38  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 110)]
39  [StorableClass]
40  public sealed class BatchRun : NamedItem, IOptimizer, IStorableContent {
41    public string Filename { get; set; }
42
43    public static new Image StaticItemImage
44    {
45      get { return new Bitmap(25, 25); }
46    }
47    public override Image ItemImage
48    {
49      get
50      {
51        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunPrepared;
52        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunStarted;
53        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunPaused;
54        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunStopped;
55        else return base.ItemImage;
56      }
57    }
58
59    [Storable]
60    private ExecutionState executionState;
61    public ExecutionState ExecutionState
62    {
63      get { return executionState; }
64      private set
65      {
66        if (executionState != value) {
67          executionState = value;
68          OnExecutionStateChanged();
69          OnItemImageChanged();
70        }
71      }
72    }
73
74    [Storable]
75    private TimeSpan executionTime;
76    public TimeSpan ExecutionTime
77    {
78      get
79      {
80        if ((Optimizer != null) && (Optimizer.ExecutionState != ExecutionState.Stopped))
81          return executionTime + Optimizer.ExecutionTime;
82        else
83          return executionTime;
84      }
85      private set
86      {
87        executionTime = value;
88        OnExecutionTimeChanged();
89      }
90    }
91
92    [Storable]
93    private TimeSpan runsExecutionTime;
94
95    [Storable]
96    private IOptimizer optimizer;
97    public IOptimizer Optimizer
98    {
99      get { return optimizer; }
100      set
101      {
102        if (optimizer != value) {
103          if (optimizer != null) {
104            DeregisterOptimizerEvents();
105            IEnumerable<IRun> runs = optimizer.Runs;
106            optimizer = null; //necessary to avoid removing the runs from the old optimizer
107            Runs.RemoveRange(runs);
108          }
109          optimizer = value;
110          if (optimizer != null) {
111            RegisterOptimizerEvents();
112            Runs.AddRange(optimizer.Runs);
113          }
114          OnOptimizerChanged();
115          Prepare();
116        }
117      }
118    }
119    // BackwardsCompatibility3.3
120    #region Backwards compatible code (remove with 3.4)
121    [Storable(AllowOneWay = true)]
122    private IAlgorithm algorithm
123    {
124      set { optimizer = value; }
125    }
126    #endregion
127
128    [Storable]
129    private int repetitions;
130    public int Repetitions
131    {
132      get { return repetitions; }
133      set
134      {
135        if (repetitions != value) {
136          repetitions = value;
137          OnRepetitionsChanged();
138          if ((Optimizer != null) && (Optimizer.ExecutionState == ExecutionState.Stopped))
139            Prepare();
140        }
141      }
142    }
143    [Storable]
144    private int repetitionsCounter;
145    public int RepetitionsCounter
146    {
147      get { return repetitionsCounter; }
148      private set
149      {
150        if (value != repetitionsCounter) {
151          repetitionsCounter = value;
152          OnRepetitionsCounterChanged();
153        }
154      }
155    }
156
157    [Storable]
158    private RunCollection runs;
159    public RunCollection Runs
160    {
161      get { return runs; }
162      private set
163      {
164        if (value == null) throw new ArgumentNullException();
165        if (runs != value) {
166          if (runs != null) DeregisterRunsEvents();
167          runs = value;
168          if (runs != null) RegisterRunsEvents();
169        }
170      }
171    }
172
173    public IEnumerable<IOptimizer> NestedOptimizers
174    {
175      get
176      {
177        if (Optimizer == null) yield break;
178
179        yield return Optimizer;
180        foreach (IOptimizer opt in Optimizer.NestedOptimizers)
181          yield return opt;
182      }
183    }
184
185    private BatchRunAction batchRunAction = BatchRunAction.None;
186
187    public BatchRun()
188      : base() {
189      name = ItemName;
190      description = ItemDescription;
191      executionState = ExecutionState.Stopped;
192      executionTime = TimeSpan.Zero;
193      runsExecutionTime = TimeSpan.Zero;
194      repetitions = 10;
195      repetitionsCounter = 0;
196      Runs = new RunCollection { OptimizerName = Name };
197    }
198    public BatchRun(string name)
199      : base(name) {
200      description = ItemDescription;
201      executionState = ExecutionState.Stopped;
202      executionTime = TimeSpan.Zero;
203      runsExecutionTime = TimeSpan.Zero;
204      repetitions = 10;
205      repetitionsCounter = 0;
206      Runs = new RunCollection { OptimizerName = Name };
207    }
208    public BatchRun(string name, string description)
209      : base(name, description) {
210      executionState = ExecutionState.Stopped;
211      executionTime = TimeSpan.Zero;
212      runsExecutionTime = TimeSpan.Zero;
213      repetitions = 10;
214      repetitionsCounter = 0;
215      Runs = new RunCollection { OptimizerName = Name };
216    }
217    [StorableConstructor]
218    private BatchRun(bool deserializing) : base(deserializing) { }
219    [StorableHook(HookType.AfterDeserialization)]
220    private void AfterDeserialization() {
221      Initialize();
222    }
223
224    private BatchRun(BatchRun original, Cloner cloner)
225      : base(original, cloner) {
226      executionState = original.executionState;
227      executionTime = original.executionTime;
228      runsExecutionTime = original.runsExecutionTime;
229      optimizer = cloner.Clone(original.optimizer);
230      repetitions = original.repetitions;
231      repetitionsCounter = original.repetitionsCounter;
232      runs = cloner.Clone(original.runs);
233      batchRunAction = original.batchRunAction;
234      Initialize();
235    }
236    public override IDeepCloneable Clone(Cloner cloner) {
237      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
238      return new BatchRun(this, cloner);
239    }
240
241    private void Initialize() {
242      if (optimizer != null) RegisterOptimizerEvents();
243      if (runs != null) RegisterRunsEvents();
244    }
245
246    public void Prepare() {
247      Prepare(false);
248    }
249    public void Prepare(bool clearRuns) {
250      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
251        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
252      if (Optimizer != null) {
253        ExecutionTime = TimeSpan.Zero;
254        RepetitionsCounter = 0;
255        if (clearRuns) runs.Clear();
256        batchRunAction = BatchRunAction.Prepare;
257        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
258        try { Optimizer.Prepare(clearRuns); }
259        catch (InvalidOperationException) { }
260      } else {
261        ExecutionState = ExecutionState.Stopped;
262      }
263    }
264    public void Start() {
265      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
266        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
267      if (Optimizer == null) return;
268      batchRunAction = BatchRunAction.Start;
269      if (Optimizer.ExecutionState == ExecutionState.Stopped) Optimizer.Prepare();
270      // a race-condition may occur when the optimizer has changed the state by itself in the meantime
271      try { Optimizer.Start(); }
272      catch (InvalidOperationException) { }
273    }
274    public void Pause() {
275      if (ExecutionState != ExecutionState.Started)
276        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
277      if (Optimizer == null) return;
278      batchRunAction = BatchRunAction.Pause;
279      if (Optimizer.ExecutionState != ExecutionState.Started) return;
280      // a race-condition may occur when the optimizer has changed the state by itself in the meantime
281      try { Optimizer.Pause(); }
282      catch (InvalidOperationException) { }
283    }
284    public void Stop() {
285      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
286        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
287      if (Optimizer == null) return;
288      batchRunAction = BatchRunAction.Stop;
289      if (Optimizer.ExecutionState != ExecutionState.Started && Optimizer.ExecutionState != ExecutionState.Paused) {
290        OnStopped();
291        return;
292      }
293      // a race-condition may occur when the optimizer has changed the state by itself in the meantime
294      try { Optimizer.Stop(); }
295      catch (InvalidOperationException) { }
296    }
297
298    #region Events
299    protected override void OnNameChanged() {
300      base.OnNameChanged();
301      runs.OptimizerName = Name;
302    }
303
304    public event EventHandler ExecutionStateChanged;
305    private void OnExecutionStateChanged() {
306      EventHandler handler = ExecutionStateChanged;
307      if (handler != null) handler(this, EventArgs.Empty);
308    }
309    public event EventHandler ExecutionTimeChanged;
310    private void OnExecutionTimeChanged() {
311      EventHandler handler = ExecutionTimeChanged;
312      if (handler != null) handler(this, EventArgs.Empty);
313    }
314    public event EventHandler OptimizerChanged;
315    private void OnOptimizerChanged() {
316      EventHandler handler = OptimizerChanged;
317      if (handler != null) handler(this, EventArgs.Empty);
318    }
319    public event EventHandler RepetitionsChanged;
320    private void OnRepetitionsChanged() {
321      EventHandler handler = RepetitionsChanged;
322      if (handler != null) handler(this, EventArgs.Empty);
323    }
324    public event EventHandler RepetetionsCounterChanged;
325    private void OnRepetitionsCounterChanged() {
326      EventHandler handler = RepetetionsCounterChanged;
327      if (handler != null) handler(this, EventArgs.Empty);
328    }
329    public event EventHandler Prepared;
330    private void OnPrepared() {
331      batchRunAction = BatchRunAction.None;
332      ExecutionState = ExecutionState.Prepared;
333      EventHandler handler = Prepared;
334      if (handler != null) handler(this, EventArgs.Empty);
335    }
336    public event EventHandler Started;
337    private void OnStarted() {
338      // no reset of BatchRunAction.Started, because we need to differ which of the two was started by the user
339      ExecutionState = ExecutionState.Started;
340      EventHandler handler = Started;
341      if (handler != null) handler(this, EventArgs.Empty);
342    }
343    public event EventHandler Paused;
344    private void OnPaused() {
345      batchRunAction = BatchRunAction.None;
346      ExecutionState = ExecutionState.Paused;
347      EventHandler handler = Paused;
348      if (handler != null) handler(this, EventArgs.Empty);
349    }
350    public event EventHandler Stopped;
351    private void OnStopped() {
352      batchRunAction = BatchRunAction.None;
353      ExecutionState = ExecutionState.Stopped;
354      EventHandler handler = Stopped;
355      if (handler != null) handler(this, EventArgs.Empty);
356    }
357    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
358    private void OnExceptionOccurred(Exception exception) {
359      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
360      if (handler != null) handler(this, new EventArgs<Exception>(exception));
361    }
362
363    private void RegisterOptimizerEvents() {
364      optimizer.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Optimizer_ExceptionOccurred);
365      optimizer.ExecutionTimeChanged += new EventHandler(Optimizer_ExecutionTimeChanged);
366      optimizer.Paused += new EventHandler(Optimizer_Paused);
367      optimizer.Prepared += new EventHandler(Optimizer_Prepared);
368      optimizer.Started += new EventHandler(Optimizer_Started);
369      optimizer.Stopped += new EventHandler(Optimizer_Stopped);
370      optimizer.Runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_CollectionReset);
371      optimizer.Runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsAdded);
372      optimizer.Runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsRemoved);
373    }
374    private void DeregisterOptimizerEvents() {
375      optimizer.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Optimizer_ExceptionOccurred);
376      optimizer.ExecutionTimeChanged -= new EventHandler(Optimizer_ExecutionTimeChanged);
377      optimizer.Paused -= new EventHandler(Optimizer_Paused);
378      optimizer.Prepared -= new EventHandler(Optimizer_Prepared);
379      optimizer.Started -= new EventHandler(Optimizer_Started);
380      optimizer.Stopped -= new EventHandler(Optimizer_Stopped);
381      optimizer.Runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_CollectionReset);
382      optimizer.Runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsAdded);
383      optimizer.Runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Optimizer_Runs_ItemsRemoved);
384    }
385    private void Optimizer_ExceptionOccurred(object sender, EventArgs<Exception> e) {
386      OnExceptionOccurred(e.Value);
387    }
388    private void Optimizer_ExecutionTimeChanged(object sender, EventArgs e) {
389      OnExecutionTimeChanged();
390    }
391    private void Optimizer_Paused(object sender, EventArgs e) {
392      if (ExecutionState == ExecutionState.Started) {
393        OnPaused();
394      }
395    }
396    private void Optimizer_Prepared(object sender, EventArgs e) {
397      if (batchRunAction == BatchRunAction.Prepare || ExecutionState == ExecutionState.Stopped) {
398        ExecutionTime = TimeSpan.Zero;
399        runsExecutionTime = TimeSpan.Zero;
400        RepetitionsCounter = 0;
401        OnPrepared();
402      }
403    }
404    private void Optimizer_Started(object sender, EventArgs e) {
405      if (ExecutionState != ExecutionState.Started)
406        OnStarted();
407    }
408    private void Optimizer_Stopped(object sender, EventArgs e) {
409      RepetitionsCounter++;
410      ExecutionTime += runsExecutionTime;
411      runsExecutionTime = TimeSpan.Zero;
412
413      if (batchRunAction == BatchRunAction.Stop) OnStopped();
414      else if (repetitionsCounter >= repetitions) OnStopped();
415      else if (batchRunAction == BatchRunAction.Pause) OnPaused();
416      else if (batchRunAction == BatchRunAction.Start) {
417        Optimizer.Prepare();
418        Optimizer.Start();
419      } else if (executionState == ExecutionState.Started) {
420        // if the batch run hasn't been started but the inner optimizer was run then pause
421        OnPaused();
422      } else OnStopped();
423    }
424    private void Optimizer_Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
425      Runs.RemoveRange(e.OldItems);
426      Runs.AddRange(e.Items);
427    }
428    private void Optimizer_Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
429      Runs.AddRange(e.Items);
430    }
431    private void Optimizer_Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
432      Runs.RemoveRange(e.Items);
433    }
434
435    private void RegisterRunsEvents() {
436      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
437      runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
438      runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
439    }
440
441    private void DeregisterRunsEvents() {
442      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
443      runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
444      runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
445    }
446    private void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
447      if (Optimizer != null) Optimizer.Runs.RemoveRange(e.OldItems);
448      foreach (IRun run in e.Items) {
449        IItem item;
450        run.Results.TryGetValue("Execution Time", out item);
451        TimeSpanValue executionTime = item as TimeSpanValue;
452        if (executionTime != null) ExecutionTime += executionTime.Value;
453      }
454    }
455    private void Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
456      foreach (IRun run in e.Items) {
457        IItem item;
458        run.Results.TryGetValue("Execution Time", out item);
459        TimeSpanValue executionTime = item as TimeSpanValue;
460        if (executionTime != null) {
461          if (Optimizer.ExecutionState == ExecutionState.Started)
462            runsExecutionTime += executionTime.Value;
463          else
464            ExecutionTime += executionTime.Value;
465        }
466      }
467    }
468    private void Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
469      if (Optimizer != null) Optimizer.Runs.RemoveRange(e.Items);
470    }
471    #endregion
472  }
473}
Note: See TracBrowser for help on using the repository browser.