Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2943_MOBasicProblem_MOCMAES/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs @ 17021

Last change on this file since 17021 was 16310, checked in by bwerth, 6 years ago

#2943 worked on MOBasicProblem and MOAnalyzers

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      snapshots = new RunCollection();
191      Runs = new RunCollection { OptimizerName = Name };
192      Initialize();
193    }
194    public TimeLimitRun(string name, string description)
195      : base(name, description) {
196      maximumExecutionTime = TimeSpan.FromMinutes(.5);
197      snapshotTimes = new ObservableList<TimeSpan>(new[] {
198          TimeSpan.FromSeconds(5),
199          TimeSpan.FromSeconds(10),
200          TimeSpan.FromSeconds(15) });
201      snapshotTimesIndex = 0;
202      snapshots = new RunCollection();
203      Runs = new RunCollection { OptimizerName = Name };
204      Initialize();
205    }
206
207    public override IDeepCloneable Clone(Cloner cloner) {
208      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
209      return new TimeLimitRun(this, cloner);
210    }
211
212    [StorableHook(HookType.AfterDeserialization)]
213    private void AfterDeserialization() {
214      Initialize();
215    }
216
217    private void Initialize() {
218      if (algorithm != null) RegisterAlgorithmEvents();
219      snapshotTimes.ItemsAdded += snapshotTimes_Changed;
220      snapshotTimes.ItemsMoved += snapshotTimes_Changed;
221      snapshotTimes.ItemsRemoved += snapshotTimes_Changed;
222      snapshotTimes.ItemsReplaced += snapshotTimes_Changed;
223      snapshotTimes.CollectionReset += snapshotTimes_Changed;
224    }
225
226    private void snapshotTimes_Changed(object sender, CollectionItemsChangedEventArgs<IndexedItem<TimeSpan>> e) {
227      if (e.Items.Any()) snapshotTimes.Sort();
228      FindNextSnapshotTimeIndex(ExecutionTime);
229    }
230
231    public void Snapshot() {
232      if (Algorithm == null || Algorithm.ExecutionState != ExecutionState.Paused) throw new InvalidOperationException("Snapshot not allowed in execution states other than Paused");
233      Task.Factory.StartNew(MakeSnapshot);
234    }
235
236    public void Prepare() {
237      Prepare(false);
238    }
239    public void Prepare(bool clearRuns) {
240      Algorithm.Prepare(clearRuns);
241    }
242    public void Start() {
243      Start(CancellationToken.None);
244    }
245    public void Start(CancellationToken cancellationToken) {
246      Algorithm.Start(cancellationToken);
247    }
248    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
249    public async Task StartAsync(CancellationToken cancellationToken) {
250      await AsyncHelper.DoAsync(Start, cancellationToken);
251    }
252    public void Pause() {
253      Algorithm.Pause();
254    }
255    public void Stop() {
256      Algorithm.Stop();
257    }
258
259    #region Events
260    protected override void OnNameChanged() {
261      base.OnNameChanged();
262      runs.OptimizerName = Name;
263    }
264
265    public event PropertyChangedEventHandler PropertyChanged;
266    private void OnPropertyChanged(string property) {
267      var handler = PropertyChanged;
268      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
269    }
270
271    #region IExecutable Events
272    public event EventHandler ExecutionStateChanged;
273    private void OnExecutionStateChanged() {
274      var handler = ExecutionStateChanged;
275      if (handler != null) handler(this, EventArgs.Empty);
276    }
277    public event EventHandler ExecutionTimeChanged;
278    private void OnExecutionTimeChanged() {
279      var handler = ExecutionTimeChanged;
280      if (handler != null) handler(this, EventArgs.Empty);
281    }
282    public event EventHandler Prepared;
283    private void OnPrepared() {
284      var handler = Prepared;
285      if (handler != null) handler(this, EventArgs.Empty);
286    }
287    public event EventHandler Started;
288    private void OnStarted() {
289      var handler = Started;
290      if (handler != null) handler(this, EventArgs.Empty);
291    }
292    public event EventHandler Paused;
293    private void OnPaused() {
294      var handler = Paused;
295      if (handler != null) handler(this, EventArgs.Empty);
296    }
297    public event EventHandler Stopped;
298    private void OnStopped() {
299      var handler = Stopped;
300      if (handler != null) handler(this, EventArgs.Empty);
301    }
302    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
303    private void OnExceptionOccurred(Exception exception) {
304      var handler = ExceptionOccurred;
305      if (handler != null) handler(this, new EventArgs<Exception>(exception));
306    }
307    #endregion
308
309    #region Algorithm Events
310    private void RegisterAlgorithmEvents() {
311      algorithm.ExceptionOccurred += Algorithm_ExceptionOccurred;
312      algorithm.ExecutionTimeChanged += Algorithm_ExecutionTimeChanged;
313      algorithm.ExecutionStateChanged += Algorithm_ExecutionStateChanged;
314      algorithm.Paused += Algorithm_Paused;
315      algorithm.Prepared += Algorithm_Prepared;
316      algorithm.Started += Algorithm_Started;
317      algorithm.Stopped += Algorithm_Stopped;
318    }
319    private void DeregisterAlgorithmEvents() {
320      algorithm.ExceptionOccurred -= Algorithm_ExceptionOccurred;
321      algorithm.ExecutionTimeChanged -= Algorithm_ExecutionTimeChanged;
322      algorithm.ExecutionStateChanged -= Algorithm_ExecutionStateChanged;
323      algorithm.Paused -= Algorithm_Paused;
324      algorithm.Prepared -= Algorithm_Prepared;
325      algorithm.Started -= Algorithm_Started;
326      algorithm.Stopped -= Algorithm_Stopped;
327    }
328    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
329      OnExceptionOccurred(e.Value);
330    }
331    private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
332      if (snapshotTimesIndex < SnapshotTimes.Count && ExecutionTime >= SnapshotTimes[snapshotTimesIndex]
333        && !pausedForSnapshot) {
334        pausedForSnapshot = true;
335        Algorithm.Pause();
336      }
337      if (ExecutionTime >= MaximumExecutionTime && !pausedForTermination) {
338        pausedForTermination = true;
339        if (!pausedForSnapshot) Algorithm.Pause();
340      }
341      OnExecutionTimeChanged();
342    }
343    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
344      OnExecutionStateChanged();
345    }
346    private void Algorithm_Paused(object sender, EventArgs e) {
347      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
348      if (pausedForSnapshot || pausedForTermination) {
349        pausedForSnapshot = pausedForTermination = false;
350        MakeSnapshot();
351        FindNextSnapshotTimeIndex(ExecutionTime);
352      }
353      OnPaused();
354      if (action == ExecutionState.Started) Algorithm.Start();
355      else if (action == ExecutionState.Stopped) Algorithm.Stop();
356    }
357    private void Algorithm_Prepared(object sender, EventArgs e) {
358      snapshotTimesIndex = 0;
359      snapshots.Clear();
360      OnPrepared();
361    }
362    private void Algorithm_Started(object sender, EventArgs e) {
363      OnStarted();
364    }
365    private void Algorithm_Stopped(object sender, EventArgs e) {
366      var cloner = new Cloner();
367      var algRun = cloner.Clone(Algorithm.Runs.Last());
368      var clonedSnapshots = cloner.Clone(snapshots);
369      algRun.Results.Add("TimeLimitRunSnapshots", clonedSnapshots);
370      Runs.Add(algRun);
371      Algorithm.Runs.Clear();
372      OnStopped();
373    }
374    #endregion
375    #endregion
376
377    private void FindNextSnapshotTimeIndex(TimeSpan reference) {
378      var index = 0;
379      while (index < snapshotTimes.Count && snapshotTimes[index] <= reference) {
380        index++;
381      };
382      snapshotTimesIndex = index;
383    }
384
385    private void MakeSnapshot() {
386      string time = Math.Round(ExecutionTime.TotalSeconds, 1).ToString("0.0");
387      string runName = "Snapshot " + time + "s " + algorithm.Name;
388      var changed = false;
389      if (StoreAlgorithmInEachSnapshot && !Algorithm.StoreAlgorithmInEachRun) {
390        Algorithm.StoreAlgorithmInEachRun = true;
391        changed = true;
392      } else if (!StoreAlgorithmInEachSnapshot && Algorithm.StoreAlgorithmInEachRun) {
393        Algorithm.StoreAlgorithmInEachRun = false;
394        changed = true;
395      }
396      var run = new Run(runName, Algorithm);
397      if (changed)
398        Algorithm.StoreAlgorithmInEachRun = !Algorithm.StoreAlgorithmInEachRun;
399
400      snapshots.Add(run);
401    }
402  }
403}
Note: See TracBrowser for help on using the repository browser.