Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RegressionBenchmarks/HeuristicLab.Algorithms.Benchmarks/3.3/Benchmark.cs @ 7255

Last change on this file since 7255 was 7255, checked in by sforsten, 12 years ago

#1708: merged r7209 from trunk

  • adjusted GUI
  • added toggle for the different series
  • X Axis labels are rounded to useful values
  • added ToolTip
File size: 20.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Drawing;
25using System.Linq;
26using System.Threading;
27using System.Threading.Tasks;
28using HeuristicLab.Collections;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Optimization;
33using HeuristicLab.Parameters;
34using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
35using HeuristicLab.PluginInfrastructure;
36
37namespace HeuristicLab.Algorithms.Benchmarks {
38  /// <summary>
39  /// A base class for benchmarks.
40  /// </summary>
41  [Item("Benchmark", "A wrapper for benchmark algorithms.")]
42  [Creatable("Algorithms")]
43  [StorableClass]
44  public class Benchmark : IAlgorithm {
45    private Random random = new Random();
46
47    [Storable]
48    private DateTime lastUpdateTime;
49
50    [Storable]
51    private IBenchmark benchmarkAlgorithm;
52    public IBenchmark BenchmarkAlgorithm {
53      get { return benchmarkAlgorithm; }
54      set {
55        if (value == null) throw new ArgumentNullException();
56        benchmarkAlgorithm = value;
57      }
58    }
59
60    private CancellationTokenSource cancellationTokenSource;
61
62    [Storable]
63    private ExecutionState executionState;
64    public ExecutionState ExecutionState {
65      get { return executionState; }
66      private set {
67        if (executionState != value) {
68          executionState = value;
69          OnExecutionStateChanged();
70          OnItemImageChanged();
71        }
72      }
73    }
74
75    [Storable]
76    private TimeSpan executionTime;
77    public TimeSpan ExecutionTime {
78      get { return executionTime; }
79      protected set {
80        executionTime = value;
81        OnExecutionTimeChanged();
82      }
83    }
84
85    [Storable]
86    private bool storeAlgorithmInEachRun;
87    public bool StoreAlgorithmInEachRun {
88      get { return storeAlgorithmInEachRun; }
89      set {
90        if (storeAlgorithmInEachRun != value) {
91          storeAlgorithmInEachRun = value;
92          OnStoreAlgorithmInEachRunChanged();
93        }
94      }
95    }
96
97    [Storable]
98    protected int runsCounter;
99
100    [Storable]
101    private RunCollection runs = new RunCollection();
102    public RunCollection Runs {
103      get { return runs; }
104      protected set {
105        if (value == null) throw new ArgumentNullException();
106        if (runs != value) {
107          if (runs != null) DeregisterRunsEvents();
108          runs = value;
109          if (runs != null) RegisterRunsEvents();
110        }
111      }
112    }
113
114    [Storable]
115    private ResultCollection results;
116    public ResultCollection Results {
117      get { return results; }
118    }
119
120    [Storable]
121    private IProblem problem;
122    public IProblem Problem {
123      get { return problem; }
124      set {
125        if (problem != value) {
126          if ((value != null) && !ProblemType.IsInstanceOfType(value)) throw new ArgumentException("Invalid problem type.");
127          if (problem != null) DeregisterProblemEvents();
128          problem = value;
129          if (problem != null) RegisterProblemEvents();
130          OnProblemChanged();
131          Prepare();
132        }
133      }
134    }
135
136    public Type ProblemType {
137      get { return typeof(IProblem); }
138    }
139
140    [Storable]
141    protected string name;
142
143    public string Name {
144      get { return name; }
145      set {
146        if (!CanChangeName) throw new NotSupportedException("Name cannot be changed.");
147        if (!(name.Equals(value) || (value == null) && (name == string.Empty))) {
148          CancelEventArgs<string> e = value == null ? new CancelEventArgs<string>(string.Empty) : new CancelEventArgs<string>(value);
149          OnNameChanging(e);
150          if (!e.Cancel) {
151            name = value == null ? string.Empty : value;
152            OnNameChanged();
153          }
154        }
155      }
156    }
157
158    public bool CanChangeName {
159      get { return false; }
160    }
161
162    [Storable]
163    protected string description;
164    public string Description {
165      get { return description; }
166      set {
167        if (!CanChangeDescription) throw new NotSupportedException("Description cannot be changed.");
168        if (!(description.Equals(value) || (value == null) && (description == string.Empty))) {
169          description = value == null ? string.Empty : value;
170          OnDescriptionChanged();
171        }
172      }
173    }
174
175    public bool CanChangeDescription {
176      get { return false; }
177    }
178
179    public string ItemName {
180      get { return ItemAttribute.GetName(this.GetType()); }
181    }
182
183    public string ItemDescription {
184      get { return ItemAttribute.GetDescription(this.GetType()); }
185    }
186
187    public Version ItemVersion {
188      get { return ItemAttribute.GetVersion(this.GetType()); }
189    }
190
191    public static Image StaticItemImage {
192      get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; }
193    }
194    public Image ItemImage {
195      get {
196        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
197        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
198        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
199        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
200        else return ItemAttribute.GetImage(this.GetType());
201      }
202    }
203
204    [Storable]
205    private ParameterCollection parameters = new ParameterCollection();
206
207    public IKeyedItemCollection<string, IParameter> Parameters {
208      get { return parameters; }
209    }
210
211    private ReadOnlyKeyedItemCollection<string, IParameter> readOnlyParameters;
212
213    IKeyedItemCollection<string, IParameter> IParameterizedItem.Parameters {
214      get {
215        if (readOnlyParameters == null) readOnlyParameters = parameters.AsReadOnly();
216        return readOnlyParameters;
217      }
218    }
219
220    public IEnumerable<IOptimizer> NestedOptimizers {
221      get { return Enumerable.Empty<IOptimizer>(); }
222    }
223
224    #region Parameter Properties
225
226    public ConstrainedValueParameter<IBenchmark> BenchmarkAlgorithmParameter {
227      get { return (ConstrainedValueParameter<IBenchmark>)Parameters["BenchmarkAlgorithm"]; }
228    }
229
230    private ValueParameter<IntValue> ChunkSizeParameter {
231      get { return (ValueParameter<IntValue>)Parameters["ChunkSize"]; }
232    }
233
234    private ValueParameter<DoubleValue> TimeLimitParameter {
235      get { return (ValueParameter<DoubleValue>)Parameters["TimeLimit"]; }
236    }
237
238    #endregion
239
240    #region Constructors
241
242    [StorableConstructor]
243    public Benchmark(bool deserializing) { }
244
245    public Benchmark() {
246      name = ItemName;
247      description = ItemDescription;
248      parameters = new ParameterCollection();
249      readOnlyParameters = null;
250      executionState = ExecutionState.Stopped;
251      executionTime = TimeSpan.Zero;
252      storeAlgorithmInEachRun = false;
253      runsCounter = 0;
254      Runs = new RunCollection();
255      results = new ResultCollection();
256      CreateParameters();
257      DiscoverBenchmarks();
258      Prepare();
259    }
260
261    public Benchmark(Benchmark original, Cloner cloner) {
262      cloner.RegisterClonedObject(original, this);
263      name = original.name;
264      description = original.description;
265      parameters = cloner.Clone(original.parameters);
266      readOnlyParameters = null;
267      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
268      executionState = original.executionState;
269      executionTime = original.executionTime;
270      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
271      runsCounter = original.runsCounter;
272      runs = cloner.Clone(original.runs);
273      Initialize();
274
275      results = cloner.Clone(original.results);
276      DiscoverBenchmarks();
277      Prepare();
278    }
279
280    #endregion
281
282    private void CreateParameters() {
283      Parameters.Add(new ValueParameter<IntValue>("ChunkSize", "The size (MB) of the chunk array that gets generated", new IntValue(0)));
284      Parameters.Add(new ValueParameter<DoubleValue>("TimeLimit", "The time limit (in minutes) for a benchmark run. Zero means a fixed number of iterations", new DoubleValue(0)));
285    }
286
287    private void DiscoverBenchmarks() {
288      var benchmarks = from t in ApplicationManager.Manager.GetTypes(typeof(IBenchmark))
289                       select t;
290      ItemSet<IBenchmark> values = new ItemSet<IBenchmark>();
291      foreach (var benchmark in benchmarks) {
292        IBenchmark b = (IBenchmark)Activator.CreateInstance(benchmark);
293        values.Add(b);
294      }
295      string paramName = "BenchmarkAlgorithm";
296      if (!Parameters.ContainsKey(paramName)) {
297        if (values.Count > 0) {
298          Parameters.Add(new ConstrainedValueParameter<IBenchmark>(paramName, values, values.First(a => a is IBenchmark)));
299        } else {
300          Parameters.Add(new ConstrainedValueParameter<IBenchmark>(paramName, values));
301        }
302      }
303    }
304
305    private void Initialize() {
306      if (problem != null) RegisterProblemEvents();
307      if (runs != null) RegisterRunsEvents();
308    }
309
310    public virtual void Prepare() {
311      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
312        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
313      results.Clear();
314      OnPrepared();
315    }
316
317    public void Prepare(bool clearRuns) {
318      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
319        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
320      if (clearRuns) runs.Clear();
321      Prepare();
322    }
323
324    public virtual void Pause() {
325      if (ExecutionState != ExecutionState.Started)
326        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
327    }
328    public virtual void Stop() {
329      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
330        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
331      cancellationTokenSource.Cancel();
332    }
333
334    public virtual void Start() {
335      cancellationTokenSource = new CancellationTokenSource();
336      OnStarted();
337      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
338      task.ContinueWith(t => {
339        try {
340          t.Wait();
341        }
342        catch (AggregateException ex) {
343          try {
344            ex.Flatten().Handle(x => x is OperationCanceledException);
345          }
346          catch (AggregateException remaining) {
347            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
348            else OnExceptionOccurred(remaining);
349          }
350        }
351
352        cancellationTokenSource.Dispose();
353        cancellationTokenSource = null;
354        OnStopped();
355      });
356    }
357
358    protected virtual void Run(object state) {
359      CancellationToken cancellationToken = (CancellationToken)state;
360      lastUpdateTime = DateTime.Now;
361      System.Timers.Timer timer = new System.Timers.Timer(250);
362      timer.AutoReset = true;
363      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
364      timer.Start();
365      try {
366        BenchmarkAlgorithm = (IBenchmark)BenchmarkAlgorithmParameter.ActualValue;
367        int chunkSize = ((IntValue)ChunkSizeParameter.ActualValue).Value;
368        if (chunkSize > 0) {
369          BenchmarkAlgorithm.ChunkData = CreateDataChuck(chunkSize);
370        } else if (chunkSize < 0) {
371          throw new ArgumentException("ChunkSize must not be negativ.");
372        }
373        TimeSpan timelimit = TimeSpan.FromMinutes(((DoubleValue)TimeLimitParameter.ActualValue).Value);
374        if (timelimit.TotalMilliseconds < 0) {
375          throw new ArgumentException("TimeLimit must not be negativ. ");
376        }
377        BenchmarkAlgorithm.TimeLimit = timelimit;
378        BenchmarkAlgorithm.Run(cancellationToken, results);
379      }
380      catch (OperationCanceledException) {
381      }
382      finally {
383        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
384        timer.Stop();
385        ExecutionTime += DateTime.Now - lastUpdateTime;
386      }
387    }
388
389    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
390      System.Timers.Timer timer = (System.Timers.Timer)sender;
391      timer.Enabled = false;
392      DateTime now = DateTime.Now;
393      ExecutionTime += now - lastUpdateTime;
394      lastUpdateTime = now;
395      timer.Enabled = true;
396    }
397
398    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
399      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
400      CollectResultsRecursively("", Results, values);
401    }
402
403    private void CollectResultsRecursively(string path, ResultCollection results, IDictionary<string, IItem> values) {
404      foreach (IResult result in results) {
405        values.Add(path + result.Name, result.Value);
406        ResultCollection childCollection = result.Value as ResultCollection;
407        if (childCollection != null) {
408          CollectResultsRecursively(path + result.Name + ".", childCollection, values);
409        }
410      }
411    }
412
413    public virtual void CollectParameterValues(IDictionary<string, IItem> values) {
414      foreach (IValueParameter param in parameters.OfType<IValueParameter>()) {
415        if (param.GetsCollected && param.Value != null) values.Add(param.Name, param.Value);
416        if (param.Value is IParameterizedItem) {
417          Dictionary<string, IItem> children = new Dictionary<string, IItem>();
418          ((IParameterizedItem)param.Value).CollectParameterValues(children);
419          foreach (string key in children.Keys)
420            values.Add(param.Name + "." + key, children[key]);
421        }
422      }
423    }
424
425    private byte[][] CreateDataChuck(int megaBytes) {
426      if (megaBytes <= 0) {
427        throw new ArgumentException("MegaBytes must be greater than zero", "megaBytes");
428      }
429      byte[][] chunk = new byte[megaBytes][];
430      for (int i = 0; i < chunk.Length; i++) {
431        chunk[i] = new byte[1024 * 1024];
432        random.NextBytes(chunk[i]);
433      }
434      return chunk;
435    }
436
437    #region Events
438
439    public event EventHandler ExecutionStateChanged;
440    protected virtual void OnExecutionStateChanged() {
441      EventHandler handler = ExecutionStateChanged;
442      if (handler != null) handler(this, EventArgs.Empty);
443    }
444    public event EventHandler ExecutionTimeChanged;
445    protected virtual void OnExecutionTimeChanged() {
446      EventHandler handler = ExecutionTimeChanged;
447      if (handler != null) handler(this, EventArgs.Empty);
448    }
449    public event EventHandler ProblemChanged;
450    protected virtual void OnProblemChanged() {
451      EventHandler handler = ProblemChanged;
452      if (handler != null) handler(this, EventArgs.Empty);
453    }
454    public event EventHandler StoreAlgorithmInEachRunChanged;
455    protected virtual void OnStoreAlgorithmInEachRunChanged() {
456      EventHandler handler = StoreAlgorithmInEachRunChanged;
457      if (handler != null) handler(this, EventArgs.Empty);
458    }
459    public event EventHandler Prepared;
460    protected virtual void OnPrepared() {
461      ExecutionState = ExecutionState.Prepared;
462      ExecutionTime = TimeSpan.Zero;
463      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects().OfType<IStatefulItem>()) {
464        statefulObject.InitializeState();
465      }
466      EventHandler handler = Prepared;
467      if (handler != null) handler(this, EventArgs.Empty);
468    }
469    public event EventHandler Started;
470    protected virtual void OnStarted() {
471      ExecutionState = ExecutionState.Started;
472      EventHandler handler = Started;
473      if (handler != null) handler(this, EventArgs.Empty);
474    }
475    public event EventHandler Paused;
476    protected virtual void OnPaused() {
477      ExecutionState = ExecutionState.Paused;
478      EventHandler handler = Paused;
479      if (handler != null) handler(this, EventArgs.Empty);
480    }
481    public event EventHandler Stopped;
482    protected virtual void OnStopped() {
483      ExecutionState = ExecutionState.Stopped;
484      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects().OfType<IStatefulItem>()) {
485        statefulObject.ClearState();
486      }
487      runsCounter++;
488      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
489      EventHandler handler = Stopped;
490      if (handler != null) handler(this, EventArgs.Empty);
491    }
492    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
493    protected virtual void OnExceptionOccurred(Exception exception) {
494      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
495      if (handler != null) handler(this, new EventArgs<Exception>(exception));
496    }
497
498    public event EventHandler<CancelEventArgs<string>> NameChanging;
499    protected virtual void OnNameChanging(CancelEventArgs<string> e) {
500      var handler = NameChanging;
501      if (handler != null) handler(this, e);
502    }
503
504    public event EventHandler NameChanged;
505    protected virtual void OnNameChanged() {
506      var handler = NameChanged;
507      if (handler != null) handler(this, EventArgs.Empty);
508      OnToStringChanged();
509    }
510
511    public event EventHandler DescriptionChanged;
512    protected virtual void OnDescriptionChanged() {
513      var handler = DescriptionChanged;
514      if (handler != null) handler(this, EventArgs.Empty);
515    }
516
517    public event EventHandler ItemImageChanged;
518    protected virtual void OnItemImageChanged() {
519      EventHandler handler = ItemImageChanged;
520      if (handler != null) handler(this, EventArgs.Empty);
521    }
522    public event EventHandler ToStringChanged;
523    protected virtual void OnToStringChanged() {
524      EventHandler handler = ToStringChanged;
525      if (handler != null) handler(this, EventArgs.Empty);
526    }
527
528    protected virtual void DeregisterProblemEvents() {
529      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
530      problem.Reset -= new EventHandler(Problem_Reset);
531    }
532    protected virtual void RegisterProblemEvents() {
533      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
534      problem.Reset += new EventHandler(Problem_Reset);
535    }
536    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
537    protected virtual void Problem_Reset(object sender, EventArgs e) {
538      Prepare();
539    }
540
541    protected virtual void DeregisterRunsEvents() {
542      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
543    }
544    protected virtual void RegisterRunsEvents() {
545      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
546    }
547    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
548      runsCounter = runs.Count;
549    }
550
551    #endregion
552
553    #region Clone
554
555    public IDeepCloneable Clone(Cloner cloner) {
556      return new Benchmark(this, cloner);
557    }
558
559    public object Clone() {
560      return Clone(new Cloner());
561    }
562
563    #endregion
564  }
565}
Note: See TracBrowser for help on using the repository browser.