Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Optimization/3.3/MetaOptimizers/BatchRun.cs @ 16225

Last change on this file since 16225 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

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