Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs @ 17717

Last change on this file since 17717 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 15.9 KB
RevLine 
[8955]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[8955]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.ComponentModel;
25using System.Drawing;
26using System.Linq;
[15287]27using System.Threading;
[8956]28using System.Threading.Tasks;
[16651]29using HEAL.Attic;
[8955]30using HeuristicLab.Collections;
31using HeuristicLab.Common;
32using HeuristicLab.Common.Resources;
33using HeuristicLab.Core;
34
35namespace HeuristicLab.Optimization {
36  /// <summary>
37  /// A run in which an algorithm is executed for a certain maximum time only.
38  /// </summary>
[12625]39  [Item("Timelimit Run", "A run in which an optimizer is executed a certain maximum time.")]
40  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 115)]
[16565]41  [StorableType("85A1AB82-689F-4925-B888-B3886707BE88")]
[8955]42  public sealed class TimeLimitRun : NamedItem, IOptimizer, IStorableContent, INotifyPropertyChanged {
43    public string Filename { get; set; }
44
45    #region ItemImage
46    public static new Image StaticItemImage {
47      get { return VSImageLibrary.Event; }
48    }
49    public override Image ItemImage {
50      get { return (Algorithm != null) ? Algorithm.ItemImage : VSImageLibrary.ExecutableStopped; }
51    }
52    #endregion
53
[8975]54    private bool pausedForSnapshot = false;
55    private bool pausedForTermination = false;
[8955]56
57    [Storable]
58    private TimeSpan maximumExecutionTime;
59    public TimeSpan MaximumExecutionTime {
60      get { return maximumExecutionTime; }
61      set {
62        if (maximumExecutionTime == value) return;
63        maximumExecutionTime = value;
[16651]64        OnPropertyChanged(nameof(MaximumExecutionTime));
[8955]65      }
66    }
67
68    [Storable]
69    private int snapshotTimesIndex;
70    [Storable]
[8961]71    private ObservableList<TimeSpan> snapshotTimes;
72    public ObservableList<TimeSpan> SnapshotTimes {
[8955]73      get { return snapshotTimes; }
74      set {
75        if (snapshotTimes == value) return;
76        snapshotTimes = value;
[8975]77        snapshotTimes.Sort();
78        FindNextSnapshotTimeIndex(ExecutionTime);
[16651]79        OnPropertyChanged(nameof(SnapshotTimes));
[8955]80      }
81    }
82
83    [Storable]
84    private bool storeAlgorithmInEachSnapshot;
85    [Storable]
86    public bool StoreAlgorithmInEachSnapshot {
87      get { return storeAlgorithmInEachSnapshot; }
88      set {
89        if (storeAlgorithmInEachSnapshot == value) return;
90        storeAlgorithmInEachSnapshot = value;
[16651]91        OnPropertyChanged(nameof(StoreAlgorithmInEachSnapshot));
[8955]92      }
93    }
94
95    [Storable]
96    private RunCollection snapshots;
97    public RunCollection Snapshots {
98      get { return snapshots; }
99      set {
100        if (snapshots == value) return;
101        snapshots = value;
[16651]102        OnPropertyChanged(nameof(Snapshots));
[8955]103      }
104    }
105
106    #region Inherited Properties
[16651]107    [Storable]
108    private ExecutionState executionState;
[8955]109    public ExecutionState ExecutionState {
[16651]110      get { return executionState; }
111      private set {
112        if (executionState == value) return;
113        executionState = value;
114        OnExecutionStateChanged();
115        OnPropertyChanged(nameof(ExecutionState));
116      }
[8955]117    }
118
119    public TimeSpan ExecutionTime {
120      get { return (Algorithm != null) ? Algorithm.ExecutionTime : TimeSpan.FromSeconds(0); }
121    }
122
123    [Storable]
124    private IAlgorithm algorithm;
125    public IAlgorithm Algorithm {
126      get { return algorithm; }
127      set {
128        if (algorithm == value) return;
[16651]129        if (ExecutionState == ExecutionState.Started || ExecutionState == ExecutionState.Paused)
130          throw new InvalidOperationException("Cannot change algorithm while the TimeLimitRun is running or paused.");
[8956]131        if (algorithm != null) DeregisterAlgorithmEvents();
[8955]132        algorithm = value;
[16651]133        if (algorithm != null) RegisterAlgorithmEvents();
134        OnPropertyChanged(nameof(Algorithm));
135        OnPropertyChanged(nameof(NestedOptimizers));
[8955]136        if (algorithm != null) {
[16651]137          if (algorithm.ExecutionState == ExecutionState.Started || algorithm.ExecutionState == ExecutionState.Paused)
138            throw new InvalidOperationException("Cannot assign a running or paused algorithm to a TimeLimitRun.");
139          Prepare();
140          if (algorithm.ExecutionState == ExecutionState.Stopped) OnStopped();
141        } else OnStopped();
[8955]142      }
143    }
144
145    [Storable]
146    private RunCollection runs;
147    public RunCollection Runs {
148      get { return runs; }
149      private set {
150        if (value == null) throw new ArgumentNullException();
151        if (runs == value) return;
152        runs = value;
[16651]153        OnPropertyChanged(nameof(Runs));
[8955]154      }
155    }
156
157    public IEnumerable<IOptimizer> NestedOptimizers {
158      get {
159        if (Algorithm == null) yield break;
160        yield return Algorithm;
161        foreach (var opt in Algorithm.NestedOptimizers)
162          yield return opt;
163      }
164    }
165    #endregion
166
167    [StorableConstructor]
[16565]168    private TimeLimitRun(StorableConstructorFlag _) : base(_) { }
[8955]169    private TimeLimitRun(TimeLimitRun original, Cloner cloner)
170      : base(original, cloner) {
171      maximumExecutionTime = original.maximumExecutionTime;
[8961]172      snapshotTimes = new ObservableList<TimeSpan>(original.snapshotTimes);
[8955]173      snapshotTimesIndex = original.snapshotTimesIndex;
[8956]174      snapshots = cloner.Clone(original.snapshots);
175      storeAlgorithmInEachSnapshot = original.storeAlgorithmInEachSnapshot;
[16651]176      executionState = original.executionState;
[8956]177      algorithm = cloner.Clone(original.algorithm);
178      runs = cloner.Clone(original.runs);
179
[8955]180      Initialize();
181    }
182    public TimeLimitRun()
183      : base() {
184      name = ItemName;
185      description = ItemDescription;
[16651]186      executionState = ExecutionState.Stopped;
[8975]187      maximumExecutionTime = TimeSpan.FromMinutes(.5);
[8961]188      snapshotTimes = new ObservableList<TimeSpan>(new[] {
189          TimeSpan.FromSeconds(5),
190          TimeSpan.FromSeconds(10),
[8975]191          TimeSpan.FromSeconds(15) });
[8955]192      snapshotTimesIndex = 0;
193      snapshots = new RunCollection();
[8975]194      Runs = new RunCollection { OptimizerName = Name };
[8956]195      Initialize();
[8955]196    }
197    public TimeLimitRun(string name)
198      : base(name) {
199      description = ItemDescription;
[16651]200      executionState = ExecutionState.Stopped;
[8975]201      maximumExecutionTime = TimeSpan.FromMinutes(.5);
[8961]202      snapshotTimes = new ObservableList<TimeSpan>(new[] {
203          TimeSpan.FromSeconds(5),
204          TimeSpan.FromSeconds(10),
[8975]205          TimeSpan.FromSeconds(15) });
[8955]206      snapshotTimesIndex = 0;
[16179]207      snapshots = new RunCollection();
[8975]208      Runs = new RunCollection { OptimizerName = Name };
[8956]209      Initialize();
[8955]210    }
211    public TimeLimitRun(string name, string description)
212      : base(name, description) {
[16651]213      executionState = ExecutionState.Stopped;
[8975]214      maximumExecutionTime = TimeSpan.FromMinutes(.5);
[8961]215      snapshotTimes = new ObservableList<TimeSpan>(new[] {
216          TimeSpan.FromSeconds(5),
217          TimeSpan.FromSeconds(10),
[8975]218          TimeSpan.FromSeconds(15) });
[8955]219      snapshotTimesIndex = 0;
[16179]220      snapshots = new RunCollection();
[8975]221      Runs = new RunCollection { OptimizerName = Name };
[8956]222      Initialize();
[8955]223    }
224
225    public override IDeepCloneable Clone(Cloner cloner) {
226      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
227      return new TimeLimitRun(this, cloner);
228    }
229
230    [StorableHook(HookType.AfterDeserialization)]
231    private void AfterDeserialization() {
232      Initialize();
[16651]233      // BackwardsCompatibility3.3
234      #region Backwards compatible code, remove with 3.4
235      if (Algorithm != null && executionState != Algorithm.ExecutionState) {
236        executionState = Algorithm.ExecutionState;
237      } else if (Algorithm == null) executionState = ExecutionState.Stopped;
238      #endregion
[8955]239    }
240
241    private void Initialize() {
242      if (algorithm != null) RegisterAlgorithmEvents();
[8956]243      snapshotTimes.ItemsAdded += snapshotTimes_Changed;
244      snapshotTimes.ItemsMoved += snapshotTimes_Changed;
245      snapshotTimes.ItemsRemoved += snapshotTimes_Changed;
246      snapshotTimes.ItemsReplaced += snapshotTimes_Changed;
247      snapshotTimes.CollectionReset += snapshotTimes_Changed;
[8955]248    }
249
[8975]250    private void snapshotTimes_Changed(object sender, CollectionItemsChangedEventArgs<IndexedItem<TimeSpan>> e) {
251      if (e.Items.Any()) snapshotTimes.Sort();
252      FindNextSnapshotTimeIndex(ExecutionTime);
[8956]253    }
254
255    public void Snapshot() {
[8975]256      if (Algorithm == null || Algorithm.ExecutionState != ExecutionState.Paused) throw new InvalidOperationException("Snapshot not allowed in execution states other than Paused");
257      Task.Factory.StartNew(MakeSnapshot);
[8956]258    }
259
[8955]260    public void Prepare() {
261      Prepare(false);
262    }
263    public void Prepare(bool clearRuns) {
[16651]264      if (Algorithm == null) return;
[8955]265      Algorithm.Prepare(clearRuns);
266    }
267    public void Start() {
[15287]268      Start(CancellationToken.None);
[8955]269    }
[15287]270    public void Start(CancellationToken cancellationToken) {
271      Algorithm.Start(cancellationToken);
272    }
273    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
274    public async Task StartAsync(CancellationToken cancellationToken) {
275      await AsyncHelper.DoAsync(Start, cancellationToken);
276    }
[8955]277    public void Pause() {
278      Algorithm.Pause();
279    }
280    public void Stop() {
281      Algorithm.Stop();
282    }
283
284    #region Events
285    protected override void OnNameChanged() {
286      base.OnNameChanged();
[8975]287      runs.OptimizerName = Name;
[8955]288    }
289
290    public event PropertyChangedEventHandler PropertyChanged;
291    private void OnPropertyChanged(string property) {
292      var handler = PropertyChanged;
293      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
294    }
295
296    #region IExecutable Events
297    public event EventHandler ExecutionStateChanged;
298    private void OnExecutionStateChanged() {
299      var handler = ExecutionStateChanged;
300      if (handler != null) handler(this, EventArgs.Empty);
301    }
302    public event EventHandler ExecutionTimeChanged;
303    private void OnExecutionTimeChanged() {
304      var handler = ExecutionTimeChanged;
305      if (handler != null) handler(this, EventArgs.Empty);
306    }
307    public event EventHandler Prepared;
308    private void OnPrepared() {
[16651]309      ExecutionState = ExecutionState.Prepared;
[8955]310      var handler = Prepared;
311      if (handler != null) handler(this, EventArgs.Empty);
312    }
313    public event EventHandler Started;
314    private void OnStarted() {
[16651]315      ExecutionState = ExecutionState.Started;
[8955]316      var handler = Started;
317      if (handler != null) handler(this, EventArgs.Empty);
318    }
319    public event EventHandler Paused;
320    private void OnPaused() {
[16651]321      ExecutionState = ExecutionState.Paused;
[8955]322      var handler = Paused;
323      if (handler != null) handler(this, EventArgs.Empty);
324    }
325    public event EventHandler Stopped;
326    private void OnStopped() {
[16651]327      ExecutionState = ExecutionState.Stopped;
[8955]328      var handler = Stopped;
329      if (handler != null) handler(this, EventArgs.Empty);
330    }
331    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
332    private void OnExceptionOccurred(Exception exception) {
[16651]333      ExecutionState = ExecutionState.Paused;
[8955]334      var handler = ExceptionOccurred;
335      if (handler != null) handler(this, new EventArgs<Exception>(exception));
336    }
337    #endregion
338
339    #region Algorithm Events
340    private void RegisterAlgorithmEvents() {
341      algorithm.ExceptionOccurred += Algorithm_ExceptionOccurred;
342      algorithm.ExecutionTimeChanged += Algorithm_ExecutionTimeChanged;
343      algorithm.Paused += Algorithm_Paused;
344      algorithm.Prepared += Algorithm_Prepared;
345      algorithm.Started += Algorithm_Started;
346      algorithm.Stopped += Algorithm_Stopped;
347    }
348    private void DeregisterAlgorithmEvents() {
349      algorithm.ExceptionOccurred -= Algorithm_ExceptionOccurred;
350      algorithm.ExecutionTimeChanged -= Algorithm_ExecutionTimeChanged;
351      algorithm.Paused -= Algorithm_Paused;
352      algorithm.Prepared -= Algorithm_Prepared;
353      algorithm.Started -= Algorithm_Started;
354      algorithm.Stopped -= Algorithm_Stopped;
355    }
356    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
357      OnExceptionOccurred(e.Value);
358    }
359    private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
[8975]360      if (snapshotTimesIndex < SnapshotTimes.Count && ExecutionTime >= SnapshotTimes[snapshotTimesIndex]
361        && !pausedForSnapshot) {
362        pausedForSnapshot = true;
363        Algorithm.Pause();
364      }
365      if (ExecutionTime >= MaximumExecutionTime && !pausedForTermination) {
366        pausedForTermination = true;
367        if (!pausedForSnapshot) Algorithm.Pause();
368      }
[8955]369      OnExecutionTimeChanged();
370    }
371    private void Algorithm_Paused(object sender, EventArgs e) {
[8975]372      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
373      if (pausedForSnapshot || pausedForTermination) {
374        pausedForSnapshot = pausedForTermination = false;
375        MakeSnapshot();
[8977]376        FindNextSnapshotTimeIndex(ExecutionTime);
[16651]377      } else OnPaused();
[8975]378      if (action == ExecutionState.Started) Algorithm.Start();
379      else if (action == ExecutionState.Stopped) Algorithm.Stop();
[8955]380    }
381    private void Algorithm_Prepared(object sender, EventArgs e) {
382      snapshotTimesIndex = 0;
383      snapshots.Clear();
384      OnPrepared();
385    }
386    private void Algorithm_Started(object sender, EventArgs e) {
[16651]387      if (ExecutionState == ExecutionState.Prepared || ExecutionState == ExecutionState.Paused)
388        OnStarted();
389      if (ExecutionState == ExecutionState.Stopped)
390        throw new InvalidOperationException("Algorithm was started although TimeLimitRun was in state Stopped.");
391      // otherwise the algorithm was just started after being snapshotted
[8955]392    }
393    private void Algorithm_Stopped(object sender, EventArgs e) {
[16651]394      try {
395        var cloner = new Cloner();
396        var algRun = cloner.Clone(Algorithm.Runs.Last());
397        var clonedSnapshots = cloner.Clone(snapshots);
398        algRun.Results.Add("TimeLimitRunSnapshots", clonedSnapshots);
399        Runs.Add(algRun);
400        Algorithm.Runs.Clear();
401      } finally { OnStopped(); }
[8955]402    }
403    #endregion
404    #endregion
[8975]405
406    private void FindNextSnapshotTimeIndex(TimeSpan reference) {
407      var index = 0;
408      while (index < snapshotTimes.Count && snapshotTimes[index] <= reference) {
409        index++;
[16651]410      }
[8975]411      snapshotTimesIndex = index;
412    }
413
414    private void MakeSnapshot() {
415      string time = Math.Round(ExecutionTime.TotalSeconds, 1).ToString("0.0");
416      string runName = "Snapshot " + time + "s " + algorithm.Name;
[12128]417      var changed = false;
418      if (StoreAlgorithmInEachSnapshot && !Algorithm.StoreAlgorithmInEachRun) {
419        Algorithm.StoreAlgorithmInEachRun = true;
420        changed = true;
421      } else if (!StoreAlgorithmInEachSnapshot && Algorithm.StoreAlgorithmInEachRun) {
422        Algorithm.StoreAlgorithmInEachRun = false;
423        changed = true;
[8975]424      }
[12128]425      var run = new Run(runName, Algorithm);
426      if (changed)
427        Algorithm.StoreAlgorithmInEachRun = !Algorithm.StoreAlgorithmInEachRun;
428
[8975]429      snapshots.Add(run);
430    }
[8955]431  }
432}
Note: See TracBrowser for help on using the repository browser.