Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2875: Removed years in copyrights

File size: 15.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using System.Threading;
28using System.Threading.Tasks;
29using HEAL.Attic;
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>
39  [Item("Timelimit Run", "A run in which an optimizer is executed a certain maximum time.")]
40  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 115)]
41  [StorableType("85A1AB82-689F-4925-B888-B3886707BE88")]
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
54    private bool pausedForSnapshot = false;
55    private bool pausedForTermination = false;
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;
64        OnPropertyChanged(nameof(MaximumExecutionTime));
65      }
66    }
67
68    [Storable]
69    private int snapshotTimesIndex;
70    [Storable]
71    private ObservableList<TimeSpan> snapshotTimes;
72    public ObservableList<TimeSpan> SnapshotTimes {
73      get { return snapshotTimes; }
74      set {
75        if (snapshotTimes == value) return;
76        snapshotTimes = value;
77        snapshotTimes.Sort();
78        FindNextSnapshotTimeIndex(ExecutionTime);
79        OnPropertyChanged(nameof(SnapshotTimes));
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;
91        OnPropertyChanged(nameof(StoreAlgorithmInEachSnapshot));
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;
102        OnPropertyChanged(nameof(Snapshots));
103      }
104    }
105
106    #region Inherited Properties
107    [Storable]
108    private ExecutionState executionState;
109    public ExecutionState ExecutionState {
110      get { return executionState; }
111      private set {
112        if (executionState == value) return;
113        executionState = value;
114        OnExecutionStateChanged();
115        OnPropertyChanged(nameof(ExecutionState));
116      }
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;
129        if (ExecutionState == ExecutionState.Started || ExecutionState == ExecutionState.Paused)
130          throw new InvalidOperationException("Cannot change algorithm while the TimeLimitRun is running or paused.");
131        if (algorithm != null) DeregisterAlgorithmEvents();
132        algorithm = value;
133        if (algorithm != null) RegisterAlgorithmEvents();
134        OnPropertyChanged(nameof(Algorithm));
135        OnPropertyChanged(nameof(NestedOptimizers));
136        if (algorithm != null) {
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();
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;
153        OnPropertyChanged(nameof(Runs));
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]
168    private TimeLimitRun(StorableConstructorFlag _) : base(_) { }
169    private TimeLimitRun(TimeLimitRun original, Cloner cloner)
170      : base(original, cloner) {
171      maximumExecutionTime = original.maximumExecutionTime;
172      snapshotTimes = new ObservableList<TimeSpan>(original.snapshotTimes);
173      snapshotTimesIndex = original.snapshotTimesIndex;
174      snapshots = cloner.Clone(original.snapshots);
175      storeAlgorithmInEachSnapshot = original.storeAlgorithmInEachSnapshot;
176      executionState = original.executionState;
177      algorithm = cloner.Clone(original.algorithm);
178      runs = cloner.Clone(original.runs);
179
180      Initialize();
181    }
182    public TimeLimitRun()
183      : base() {
184      name = ItemName;
185      description = ItemDescription;
186      executionState = ExecutionState.Stopped;
187      maximumExecutionTime = TimeSpan.FromMinutes(.5);
188      snapshotTimes = new ObservableList<TimeSpan>(new[] {
189          TimeSpan.FromSeconds(5),
190          TimeSpan.FromSeconds(10),
191          TimeSpan.FromSeconds(15) });
192      snapshotTimesIndex = 0;
193      snapshots = new RunCollection();
194      Runs = new RunCollection { OptimizerName = Name };
195      Initialize();
196    }
197    public TimeLimitRun(string name)
198      : base(name) {
199      description = ItemDescription;
200      executionState = ExecutionState.Stopped;
201      maximumExecutionTime = TimeSpan.FromMinutes(.5);
202      snapshotTimes = new ObservableList<TimeSpan>(new[] {
203          TimeSpan.FromSeconds(5),
204          TimeSpan.FromSeconds(10),
205          TimeSpan.FromSeconds(15) });
206      snapshotTimesIndex = 0;
207      snapshots = new RunCollection();
208      Runs = new RunCollection { OptimizerName = Name };
209      Initialize();
210    }
211    public TimeLimitRun(string name, string description)
212      : base(name, description) {
213      executionState = ExecutionState.Stopped;
214      maximumExecutionTime = TimeSpan.FromMinutes(.5);
215      snapshotTimes = new ObservableList<TimeSpan>(new[] {
216          TimeSpan.FromSeconds(5),
217          TimeSpan.FromSeconds(10),
218          TimeSpan.FromSeconds(15) });
219      snapshotTimesIndex = 0;
220      snapshots = new RunCollection();
221      Runs = new RunCollection { OptimizerName = Name };
222      Initialize();
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();
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
239    }
240
241    private void Initialize() {
242      if (algorithm != null) RegisterAlgorithmEvents();
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;
248    }
249
250    private void snapshotTimes_Changed(object sender, CollectionItemsChangedEventArgs<IndexedItem<TimeSpan>> e) {
251      if (e.Items.Any()) snapshotTimes.Sort();
252      FindNextSnapshotTimeIndex(ExecutionTime);
253    }
254
255    public void Snapshot() {
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);
258    }
259
260    public void Prepare() {
261      Prepare(false);
262    }
263    public void Prepare(bool clearRuns) {
264      if (Algorithm == null) return;
265      Algorithm.Prepare(clearRuns);
266    }
267    public void Start() {
268      Start(CancellationToken.None);
269    }
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    }
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();
287      runs.OptimizerName = Name;
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() {
309      ExecutionState = ExecutionState.Prepared;
310      var handler = Prepared;
311      if (handler != null) handler(this, EventArgs.Empty);
312    }
313    public event EventHandler Started;
314    private void OnStarted() {
315      ExecutionState = ExecutionState.Started;
316      var handler = Started;
317      if (handler != null) handler(this, EventArgs.Empty);
318    }
319    public event EventHandler Paused;
320    private void OnPaused() {
321      ExecutionState = ExecutionState.Paused;
322      var handler = Paused;
323      if (handler != null) handler(this, EventArgs.Empty);
324    }
325    public event EventHandler Stopped;
326    private void OnStopped() {
327      ExecutionState = ExecutionState.Stopped;
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) {
333      ExecutionState = ExecutionState.Paused;
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) {
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      }
369      OnExecutionTimeChanged();
370    }
371    private void Algorithm_Paused(object sender, EventArgs e) {
372      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
373      if (pausedForSnapshot || pausedForTermination) {
374        pausedForSnapshot = pausedForTermination = false;
375        MakeSnapshot();
376        FindNextSnapshotTimeIndex(ExecutionTime);
377      } else OnPaused();
378      if (action == ExecutionState.Started) Algorithm.Start();
379      else if (action == ExecutionState.Stopped) Algorithm.Stop();
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) {
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
392    }
393    private void Algorithm_Stopped(object sender, EventArgs e) {
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(); }
402    }
403    #endregion
404    #endregion
405
406    private void FindNextSnapshotTimeIndex(TimeSpan reference) {
407      var index = 0;
408      while (index < snapshotTimes.Count && snapshotTimes[index] <= reference) {
409        index++;
410      }
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;
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;
424      }
425      var run = new Run(runName, Algorithm);
426      if (changed)
427        Algorithm.StoreAlgorithmInEachRun = !Algorithm.StoreAlgorithmInEachRun;
428
429      snapshots.Add(run);
430    }
431  }
432}
Note: See TracBrowser for help on using the repository browser.