Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs @ 15728

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

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

File size: 14.2 KB
RevLine 
[8955]1#region License Information
2/* HeuristicLab
[15584]3 * Copyright (C) 2002-2018 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;
[15292]27using System.Threading;
[8956]28using System.Threading.Tasks;
[8955]29using HeuristicLab.Collections;
30using HeuristicLab.Common;
31using HeuristicLab.Common.Resources;
32using HeuristicLab.Core;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
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)]
[8955]41  [StorableClass]
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;
64        OnPropertyChanged("MaximumExecutionTime");
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);
[8955]79        OnPropertyChanged("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("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("Snapshots");
103      }
104    }
105
106    #region Inherited Properties
107    public ExecutionState ExecutionState {
108      get { return (Algorithm != null) ? Algorithm.ExecutionState : ExecutionState.Stopped; }
109    }
110
111    public TimeSpan ExecutionTime {
112      get { return (Algorithm != null) ? Algorithm.ExecutionTime : TimeSpan.FromSeconds(0); }
113    }
114
115    [Storable]
116    private IAlgorithm algorithm;
117    public IAlgorithm Algorithm {
118      get { return algorithm; }
119      set {
120        if (algorithm == value) return;
[8956]121        if (algorithm != null) DeregisterAlgorithmEvents();
[8955]122        algorithm = value;
123        if (algorithm != null) {
124          RegisterAlgorithmEvents();
125        }
126        OnPropertyChanged("Algorithm");
127        Prepare();
128      }
129    }
130
131    [Storable]
132    private RunCollection runs;
133    public RunCollection Runs {
134      get { return runs; }
135      private set {
136        if (value == null) throw new ArgumentNullException();
137        if (runs == value) return;
138        runs = value;
139        OnPropertyChanged("Runs");
140      }
141    }
142
143    public IEnumerable<IOptimizer> NestedOptimizers {
144      get {
145        if (Algorithm == null) yield break;
146        yield return Algorithm;
147        foreach (var opt in Algorithm.NestedOptimizers)
148          yield return opt;
149      }
150    }
151    #endregion
152
153    [StorableConstructor]
[8956]154    private TimeLimitRun(bool deserializing) : base(deserializing) { }
[8955]155    private TimeLimitRun(TimeLimitRun original, Cloner cloner)
156      : base(original, cloner) {
157      maximumExecutionTime = original.maximumExecutionTime;
[8961]158      snapshotTimes = new ObservableList<TimeSpan>(original.snapshotTimes);
[8955]159      snapshotTimesIndex = original.snapshotTimesIndex;
[8956]160      snapshots = cloner.Clone(original.snapshots);
161      storeAlgorithmInEachSnapshot = original.storeAlgorithmInEachSnapshot;
162      algorithm = cloner.Clone(original.algorithm);
163      runs = cloner.Clone(original.runs);
164
[8955]165      Initialize();
166    }
167    public TimeLimitRun()
168      : base() {
169      name = ItemName;
170      description = ItemDescription;
[8975]171      maximumExecutionTime = TimeSpan.FromMinutes(.5);
[8961]172      snapshotTimes = new ObservableList<TimeSpan>(new[] {
173          TimeSpan.FromSeconds(5),
174          TimeSpan.FromSeconds(10),
[8975]175          TimeSpan.FromSeconds(15) });
[8955]176      snapshotTimesIndex = 0;
177      snapshots = new RunCollection();
[8975]178      Runs = new RunCollection { OptimizerName = Name };
[8956]179      Initialize();
[8955]180    }
181    public TimeLimitRun(string name)
182      : base(name) {
183      description = ItemDescription;
[8975]184      maximumExecutionTime = TimeSpan.FromMinutes(.5);
[8961]185      snapshotTimes = new ObservableList<TimeSpan>(new[] {
186          TimeSpan.FromSeconds(5),
187          TimeSpan.FromSeconds(10),
[8975]188          TimeSpan.FromSeconds(15) });
[8955]189      snapshotTimesIndex = 0;
[8975]190      Runs = new RunCollection { OptimizerName = Name };
[8956]191      Initialize();
[8955]192    }
193    public TimeLimitRun(string name, string description)
194      : base(name, description) {
[8975]195      maximumExecutionTime = TimeSpan.FromMinutes(.5);
[8961]196      snapshotTimes = new ObservableList<TimeSpan>(new[] {
197          TimeSpan.FromSeconds(5),
198          TimeSpan.FromSeconds(10),
[8975]199          TimeSpan.FromSeconds(15) });
[8955]200      snapshotTimesIndex = 0;
[8975]201      Runs = new RunCollection { OptimizerName = Name };
[8956]202      Initialize();
[8955]203    }
204
205    public override IDeepCloneable Clone(Cloner cloner) {
206      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
207      return new TimeLimitRun(this, cloner);
208    }
209
210    [StorableHook(HookType.AfterDeserialization)]
211    private void AfterDeserialization() {
212      Initialize();
213    }
214
215    private void Initialize() {
216      if (algorithm != null) RegisterAlgorithmEvents();
[8956]217      snapshotTimes.ItemsAdded += snapshotTimes_Changed;
218      snapshotTimes.ItemsMoved += snapshotTimes_Changed;
219      snapshotTimes.ItemsRemoved += snapshotTimes_Changed;
220      snapshotTimes.ItemsReplaced += snapshotTimes_Changed;
221      snapshotTimes.CollectionReset += snapshotTimes_Changed;
[8955]222    }
223
[8975]224    private void snapshotTimes_Changed(object sender, CollectionItemsChangedEventArgs<IndexedItem<TimeSpan>> e) {
225      if (e.Items.Any()) snapshotTimes.Sort();
226      FindNextSnapshotTimeIndex(ExecutionTime);
[8956]227    }
228
229    public void Snapshot() {
[8975]230      if (Algorithm == null || Algorithm.ExecutionState != ExecutionState.Paused) throw new InvalidOperationException("Snapshot not allowed in execution states other than Paused");
231      Task.Factory.StartNew(MakeSnapshot);
[8956]232    }
233
[8955]234    public void Prepare() {
235      Prepare(false);
236    }
237    public void Prepare(bool clearRuns) {
238      Algorithm.Prepare(clearRuns);
239    }
240    public void Start() {
[15292]241      Start(CancellationToken.None);
[8955]242    }
[15292]243    public void Start(CancellationToken cancellationToken) {
244      Algorithm.Start(cancellationToken);
245    }
246    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
247    public async Task StartAsync(CancellationToken cancellationToken) {
248      await AsyncHelper.DoAsync(Start, cancellationToken);
249    }
[8955]250    public void Pause() {
251      Algorithm.Pause();
252    }
253    public void Stop() {
254      Algorithm.Stop();
255    }
256
257    #region Events
258    protected override void OnNameChanged() {
259      base.OnNameChanged();
[8975]260      runs.OptimizerName = Name;
[8955]261    }
262
263    public event PropertyChangedEventHandler PropertyChanged;
264    private void OnPropertyChanged(string property) {
265      var handler = PropertyChanged;
266      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
267    }
268
269    #region IExecutable Events
270    public event EventHandler ExecutionStateChanged;
271    private void OnExecutionStateChanged() {
272      var handler = ExecutionStateChanged;
273      if (handler != null) handler(this, EventArgs.Empty);
274    }
275    public event EventHandler ExecutionTimeChanged;
276    private void OnExecutionTimeChanged() {
277      var handler = ExecutionTimeChanged;
278      if (handler != null) handler(this, EventArgs.Empty);
279    }
280    public event EventHandler Prepared;
281    private void OnPrepared() {
282      var handler = Prepared;
283      if (handler != null) handler(this, EventArgs.Empty);
284    }
285    public event EventHandler Started;
286    private void OnStarted() {
287      var handler = Started;
288      if (handler != null) handler(this, EventArgs.Empty);
289    }
290    public event EventHandler Paused;
291    private void OnPaused() {
292      var handler = Paused;
293      if (handler != null) handler(this, EventArgs.Empty);
294    }
295    public event EventHandler Stopped;
296    private void OnStopped() {
297      var handler = Stopped;
298      if (handler != null) handler(this, EventArgs.Empty);
299    }
300    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
301    private void OnExceptionOccurred(Exception exception) {
302      var handler = ExceptionOccurred;
303      if (handler != null) handler(this, new EventArgs<Exception>(exception));
304    }
305    #endregion
306
307    #region Algorithm Events
308    private void RegisterAlgorithmEvents() {
309      algorithm.ExceptionOccurred += Algorithm_ExceptionOccurred;
310      algorithm.ExecutionTimeChanged += Algorithm_ExecutionTimeChanged;
311      algorithm.ExecutionStateChanged += Algorithm_ExecutionStateChanged;
312      algorithm.Paused += Algorithm_Paused;
313      algorithm.Prepared += Algorithm_Prepared;
314      algorithm.Started += Algorithm_Started;
315      algorithm.Stopped += Algorithm_Stopped;
316    }
317    private void DeregisterAlgorithmEvents() {
318      algorithm.ExceptionOccurred -= Algorithm_ExceptionOccurred;
319      algorithm.ExecutionTimeChanged -= Algorithm_ExecutionTimeChanged;
320      algorithm.ExecutionStateChanged -= Algorithm_ExecutionStateChanged;
321      algorithm.Paused -= Algorithm_Paused;
322      algorithm.Prepared -= Algorithm_Prepared;
323      algorithm.Started -= Algorithm_Started;
324      algorithm.Stopped -= Algorithm_Stopped;
325    }
326    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
327      OnExceptionOccurred(e.Value);
328    }
329    private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
[8975]330      if (snapshotTimesIndex < SnapshotTimes.Count && ExecutionTime >= SnapshotTimes[snapshotTimesIndex]
331        && !pausedForSnapshot) {
332        pausedForSnapshot = true;
333        Algorithm.Pause();
334      }
335      if (ExecutionTime >= MaximumExecutionTime && !pausedForTermination) {
336        pausedForTermination = true;
337        if (!pausedForSnapshot) Algorithm.Pause();
338      }
[8955]339      OnExecutionTimeChanged();
340    }
341    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
342      OnExecutionStateChanged();
343    }
344    private void Algorithm_Paused(object sender, EventArgs e) {
[8975]345      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
346      if (pausedForSnapshot || pausedForTermination) {
347        pausedForSnapshot = pausedForTermination = false;
348        MakeSnapshot();
[8977]349        FindNextSnapshotTimeIndex(ExecutionTime);
[8975]350      }
[8955]351      OnPaused();
[8975]352      if (action == ExecutionState.Started) Algorithm.Start();
353      else if (action == ExecutionState.Stopped) Algorithm.Stop();
[8955]354    }
355    private void Algorithm_Prepared(object sender, EventArgs e) {
356      snapshotTimesIndex = 0;
357      snapshots.Clear();
358      OnPrepared();
359    }
360    private void Algorithm_Started(object sender, EventArgs e) {
361      OnStarted();
362    }
363    private void Algorithm_Stopped(object sender, EventArgs e) {
[8956]364      var cloner = new Cloner();
365      var algRun = cloner.Clone(Algorithm.Runs.Last());
366      var clonedSnapshots = cloner.Clone(snapshots);
[9040]367      algRun.Results.Add("TimeLimitRunSnapshots", clonedSnapshots);
[8956]368      Runs.Add(algRun);
369      Algorithm.Runs.Clear();
[8955]370      OnStopped();
371    }
372    #endregion
373    #endregion
[8975]374
375    private void FindNextSnapshotTimeIndex(TimeSpan reference) {
376      var index = 0;
377      while (index < snapshotTimes.Count && snapshotTimes[index] <= reference) {
378        index++;
379      };
380      snapshotTimesIndex = index;
381    }
382
383    private void MakeSnapshot() {
384      string time = Math.Round(ExecutionTime.TotalSeconds, 1).ToString("0.0");
385      string runName = "Snapshot " + time + "s " + algorithm.Name;
[12128]386      var changed = false;
387      if (StoreAlgorithmInEachSnapshot && !Algorithm.StoreAlgorithmInEachRun) {
388        Algorithm.StoreAlgorithmInEachRun = true;
389        changed = true;
390      } else if (!StoreAlgorithmInEachSnapshot && Algorithm.StoreAlgorithmInEachRun) {
391        Algorithm.StoreAlgorithmInEachRun = false;
392        changed = true;
[8975]393      }
[12128]394      var run = new Run(runName, Algorithm);
395      if (changed)
396        Algorithm.StoreAlgorithmInEachRun = !Algorithm.StoreAlgorithmInEachRun;
397
[8975]398      snapshots.Add(run);
399    }
[8955]400  }
401}
Note: See TracBrowser for help on using the repository browser.