Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2898_GeneralizedAdditiveModels/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs @ 15774

Last change on this file since 15774 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 14.2 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.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using System.Threading;
28using System.Threading.Tasks;
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>
39  [Item("Timelimit Run", "A run in which an optimizer is executed a certain maximum time.")]
40  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 115)]
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
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("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("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;
121        if (algorithm != null) DeregisterAlgorithmEvents();
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]
154    private TimeLimitRun(bool deserializing) : base(deserializing) { }
155    private TimeLimitRun(TimeLimitRun original, Cloner cloner)
156      : base(original, cloner) {
157      maximumExecutionTime = original.maximumExecutionTime;
158      snapshotTimes = new ObservableList<TimeSpan>(original.snapshotTimes);
159      snapshotTimesIndex = original.snapshotTimesIndex;
160      snapshots = cloner.Clone(original.snapshots);
161      storeAlgorithmInEachSnapshot = original.storeAlgorithmInEachSnapshot;
162      algorithm = cloner.Clone(original.algorithm);
163      runs = cloner.Clone(original.runs);
164
165      Initialize();
166    }
167    public TimeLimitRun()
168      : base() {
169      name = ItemName;
170      description = ItemDescription;
171      maximumExecutionTime = TimeSpan.FromMinutes(.5);
172      snapshotTimes = new ObservableList<TimeSpan>(new[] {
173          TimeSpan.FromSeconds(5),
174          TimeSpan.FromSeconds(10),
175          TimeSpan.FromSeconds(15) });
176      snapshotTimesIndex = 0;
177      snapshots = new RunCollection();
178      Runs = new RunCollection { OptimizerName = Name };
179      Initialize();
180    }
181    public TimeLimitRun(string name)
182      : base(name) {
183      description = ItemDescription;
184      maximumExecutionTime = TimeSpan.FromMinutes(.5);
185      snapshotTimes = new ObservableList<TimeSpan>(new[] {
186          TimeSpan.FromSeconds(5),
187          TimeSpan.FromSeconds(10),
188          TimeSpan.FromSeconds(15) });
189      snapshotTimesIndex = 0;
190      Runs = new RunCollection { OptimizerName = Name };
191      Initialize();
192    }
193    public TimeLimitRun(string name, string description)
194      : base(name, description) {
195      maximumExecutionTime = TimeSpan.FromMinutes(.5);
196      snapshotTimes = new ObservableList<TimeSpan>(new[] {
197          TimeSpan.FromSeconds(5),
198          TimeSpan.FromSeconds(10),
199          TimeSpan.FromSeconds(15) });
200      snapshotTimesIndex = 0;
201      Runs = new RunCollection { OptimizerName = Name };
202      Initialize();
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();
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;
222    }
223
224    private void snapshotTimes_Changed(object sender, CollectionItemsChangedEventArgs<IndexedItem<TimeSpan>> e) {
225      if (e.Items.Any()) snapshotTimes.Sort();
226      FindNextSnapshotTimeIndex(ExecutionTime);
227    }
228
229    public void Snapshot() {
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);
232    }
233
234    public void Prepare() {
235      Prepare(false);
236    }
237    public void Prepare(bool clearRuns) {
238      Algorithm.Prepare(clearRuns);
239    }
240    public void Start() {
241      Start(CancellationToken.None);
242    }
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    }
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();
260      runs.OptimizerName = Name;
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) {
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      }
339      OnExecutionTimeChanged();
340    }
341    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
342      OnExecutionStateChanged();
343    }
344    private void Algorithm_Paused(object sender, EventArgs e) {
345      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
346      if (pausedForSnapshot || pausedForTermination) {
347        pausedForSnapshot = pausedForTermination = false;
348        MakeSnapshot();
349        FindNextSnapshotTimeIndex(ExecutionTime);
350      }
351      OnPaused();
352      if (action == ExecutionState.Started) Algorithm.Start();
353      else if (action == ExecutionState.Stopped) Algorithm.Stop();
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) {
364      var cloner = new Cloner();
365      var algRun = cloner.Clone(Algorithm.Runs.Last());
366      var clonedSnapshots = cloner.Clone(snapshots);
367      algRun.Results.Add("TimeLimitRunSnapshots", clonedSnapshots);
368      Runs.Add(algRun);
369      Algorithm.Runs.Clear();
370      OnStopped();
371    }
372    #endregion
373    #endregion
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;
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;
393      }
394      var run = new Run(runName, Algorithm);
395      if (changed)
396        Algorithm.StoreAlgorithmInEachRun = !Algorithm.StoreAlgorithmInEachRun;
397
398      snapshots.Add(run);
399    }
400  }
401}
Note: See TracBrowser for help on using the repository browser.