source: branches/Benchmarking/sources/HeuristicLab.Algorithms.Benchmarks/3.3/Benchmark.cs @ 6987

Last change on this file since 6987 was 6987, checked in by spimming, 11 years ago

#1659:

  • removed uncommented code
  • removed ‘Benchmark Name’ and ‘Benchmark Type’ from result collection
  • placed Getters/Setters after data members
  • added input validation
  • updated parameter description
File size: 20.1 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("Benchmarks")]
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 Image ItemImage {
192      get {
193        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
194        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
195        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
196        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
197        else return HeuristicLab.Common.Resources.VSImageLibrary.Event;
198      }
199    }
200
201    [Storable]
202    private ParameterCollection parameters = new ParameterCollection();
203
204    public IKeyedItemCollection<string, IParameter> Parameters {
205      get { return parameters; }
206    }
207
208    private ReadOnlyKeyedItemCollection<string, IParameter> readOnlyParameters;
209
210    IKeyedItemCollection<string, IParameter> IParameterizedItem.Parameters {
211      get {
212        if (readOnlyParameters == null) readOnlyParameters = parameters.AsReadOnly();
213        return readOnlyParameters;
214      }
215    }
216
217    public IEnumerable<IOptimizer> NestedOptimizers {
218      get { return Enumerable.Empty<IOptimizer>(); }
219    }
220
221    #region Parameter Properties
222
223    public ConstrainedValueParameter<IBenchmark> BenchmarkAlgorithmParameter {
224      get { return (ConstrainedValueParameter<IBenchmark>)Parameters["BenchmarkAlgorithm"]; }
225    }
226
227    private ValueParameter<IntValue> ChunkSizeParameter {
228      get { return (ValueParameter<IntValue>)Parameters["ChunkSize"]; }
229    }
230
231    private ValueParameter<DoubleValue> TimeLimitParameter {
232      get { return (ValueParameter<DoubleValue>)Parameters["TimeLimit"]; }
233    }
234
235    #endregion
236
237    #region Constructors
238
239    public Benchmark() {
240      name = ItemName;
241      description = ItemDescription;
242      parameters = new ParameterCollection();
243      readOnlyParameters = null;
244      executionState = ExecutionState.Stopped;
245      executionTime = TimeSpan.Zero;
246      storeAlgorithmInEachRun = false;
247      runsCounter = 0;
248      Runs = new RunCollection();
249      results = new ResultCollection();
250      CreateParameters();
251      DiscoverBenchmarks();
252      Prepare();
253    }
254
255    public Benchmark(Benchmark original, Cloner cloner) {
256      cloner.RegisterClonedObject(original, this);
257      name = original.name;
258      description = original.description;
259      parameters = cloner.Clone(original.parameters);
260      readOnlyParameters = null;
261      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
262      executionState = original.executionState;
263      executionTime = original.executionTime;
264      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
265      runsCounter = original.runsCounter;
266      runs = cloner.Clone(original.runs);
267      Initialize();
268
269      results = cloner.Clone(original.results);
270      DiscoverBenchmarks();
271      Prepare();
272    }
273
274    #endregion
275
276    private void CreateParameters() {
277      Parameters.Add(new ValueParameter<IntValue>("ChunkSize", "The size (MB) of the chunk array that gets generated", new IntValue(0)));
278      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)));
279    }
280
281    private void DiscoverBenchmarks() {
282      var benchmarks = from t in ApplicationManager.Manager.GetTypes(typeof(IBenchmark))
283                       select t;
284      ItemSet<IBenchmark> values = new ItemSet<IBenchmark>();
285      foreach (var benchmark in benchmarks) {
286        IBenchmark b = (IBenchmark)Activator.CreateInstance(benchmark);
287        values.Add(b);
288      }
289      string paramName = "BenchmarkAlgorithm";
290      if (!Parameters.ContainsKey(paramName)) {
291        if (values.Count > 0) {
292          Parameters.Add(new ConstrainedValueParameter<IBenchmark>(paramName, values, values.First(a => a is IBenchmark)));
293        } else {
294          Parameters.Add(new ConstrainedValueParameter<IBenchmark>(paramName, values));
295        }
296      }
297    }
298
299    private void Initialize() {
300      if (problem != null) RegisterProblemEvents();
301      if (runs != null) RegisterRunsEvents();
302    }
303
304    public virtual void Prepare() {
305      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
306        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
307      results.Clear();
308      OnPrepared();
309    }
310
311    public void Prepare(bool clearRuns) {
312      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
313        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
314      if (clearRuns) runs.Clear();
315      Prepare();
316    }
317
318    public virtual void Pause() {
319      if (ExecutionState != ExecutionState.Started)
320        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
321    }
322    public virtual void Stop() {
323      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
324        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
325      cancellationTokenSource.Cancel();
326    }
327
328    public virtual void Start() {
329      cancellationTokenSource = new CancellationTokenSource();
330      OnStarted();
331      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
332      task.ContinueWith(t => {
333        try {
334          t.Wait();
335        }
336        catch (AggregateException ex) {
337          try {
338            ex.Flatten().Handle(x => x is OperationCanceledException);
339          }
340          catch (AggregateException remaining) {
341            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
342            else OnExceptionOccurred(remaining);
343          }
344        }
345
346        cancellationTokenSource.Dispose();
347        cancellationTokenSource = null;
348        OnStopped();
349      });
350    }
351
352    protected virtual void Run(object state) {
353      CancellationToken cancellationToken = (CancellationToken)state;
354      lastUpdateTime = DateTime.Now;
355      System.Timers.Timer timer = new System.Timers.Timer(250);
356      timer.AutoReset = true;
357      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
358      timer.Start();
359      try {
360        BenchmarkAlgorithm = (IBenchmark)BenchmarkAlgorithmParameter.ActualValue;
361        int chunkSize = ((IntValue)ChunkSizeParameter.ActualValue).Value;
362        if (chunkSize > 0) {
363          BenchmarkAlgorithm.ChunkData = CreateDataChuck(chunkSize);
364        } else if (chunkSize < 0) {
365          throw new ArgumentException("ChunkSize must not be negativ.");
366        }
367        TimeSpan timelimit = TimeSpan.FromMinutes(((DoubleValue)TimeLimitParameter.ActualValue).Value);
368        if (timelimit.TotalMilliseconds < 0) {
369          throw new ArgumentException("TimeLimit must not be negativ. ");
370        }
371        BenchmarkAlgorithm.TimeLimit = timelimit;
372        BenchmarkAlgorithm.Run(cancellationToken, results);
373      }
374      catch (OperationCanceledException) {
375      }
376      finally {
377        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
378        timer.Stop();
379        ExecutionTime += DateTime.Now - lastUpdateTime;
380      }
381    }
382
383    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
384      System.Timers.Timer timer = (System.Timers.Timer)sender;
385      timer.Enabled = false;
386      DateTime now = DateTime.Now;
387      ExecutionTime += now - lastUpdateTime;
388      lastUpdateTime = now;
389      timer.Enabled = true;
390    }
391
392    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
393      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
394      CollectResultsRecursively("", Results, values);
395    }
396
397    private void CollectResultsRecursively(string path, ResultCollection results, IDictionary<string, IItem> values) {
398      foreach (IResult result in results) {
399        values.Add(path + result.Name, result.Value);
400        ResultCollection childCollection = result.Value as ResultCollection;
401        if (childCollection != null) {
402          CollectResultsRecursively(path + result.Name + ".", childCollection, values);
403        }
404      }
405    }
406
407    public virtual void CollectParameterValues(IDictionary<string, IItem> values) {
408      foreach (IValueParameter param in parameters.OfType<IValueParameter>()) {
409        if (param.GetsCollected && param.Value != null) values.Add(param.Name, param.Value);
410        if (param.Value is IParameterizedItem) {
411          Dictionary<string, IItem> children = new Dictionary<string, IItem>();
412          ((IParameterizedItem)param.Value).CollectParameterValues(children);
413          foreach (string key in children.Keys)
414            values.Add(param.Name + "." + key, children[key]);
415        }
416      }
417    }
418
419    private byte[][] CreateDataChuck(int megaBytes) {
420      if (megaBytes <= 0) {
421        throw new ArgumentException("MegaBytes must be greater than zero", "megaBytes");
422      }
423      byte[][] chunk = new byte[megaBytes][];
424      for (int i = 0; i < chunk.Length; i++) {
425        chunk[i] = new byte[1024 * 1024];
426        random.NextBytes(chunk[i]);
427      }
428      return chunk;
429    }
430
431    #region Events
432
433    public event EventHandler ExecutionStateChanged;
434    protected virtual void OnExecutionStateChanged() {
435      EventHandler handler = ExecutionStateChanged;
436      if (handler != null) handler(this, EventArgs.Empty);
437    }
438    public event EventHandler ExecutionTimeChanged;
439    protected virtual void OnExecutionTimeChanged() {
440      EventHandler handler = ExecutionTimeChanged;
441      if (handler != null) handler(this, EventArgs.Empty);
442    }
443    public event EventHandler ProblemChanged;
444    protected virtual void OnProblemChanged() {
445      EventHandler handler = ProblemChanged;
446      if (handler != null) handler(this, EventArgs.Empty);
447    }
448    public event EventHandler StoreAlgorithmInEachRunChanged;
449    protected virtual void OnStoreAlgorithmInEachRunChanged() {
450      EventHandler handler = StoreAlgorithmInEachRunChanged;
451      if (handler != null) handler(this, EventArgs.Empty);
452    }
453    public event EventHandler Prepared;
454    protected virtual void OnPrepared() {
455      ExecutionState = ExecutionState.Prepared;
456      ExecutionTime = TimeSpan.Zero;
457      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects().OfType<IStatefulItem>()) {
458        statefulObject.InitializeState();
459      }
460      EventHandler handler = Prepared;
461      if (handler != null) handler(this, EventArgs.Empty);
462    }
463    public event EventHandler Started;
464    protected virtual void OnStarted() {
465      ExecutionState = ExecutionState.Started;
466      EventHandler handler = Started;
467      if (handler != null) handler(this, EventArgs.Empty);
468    }
469    public event EventHandler Paused;
470    protected virtual void OnPaused() {
471      ExecutionState = ExecutionState.Paused;
472      EventHandler handler = Paused;
473      if (handler != null) handler(this, EventArgs.Empty);
474    }
475    public event EventHandler Stopped;
476    protected virtual void OnStopped() {
477      ExecutionState = ExecutionState.Stopped;
478      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects().OfType<IStatefulItem>()) {
479        statefulObject.ClearState();
480      }
481      runsCounter++;
482      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
483      EventHandler handler = Stopped;
484      if (handler != null) handler(this, EventArgs.Empty);
485    }
486    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
487    protected virtual void OnExceptionOccurred(Exception exception) {
488      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
489      if (handler != null) handler(this, new EventArgs<Exception>(exception));
490    }
491
492    public event EventHandler<CancelEventArgs<string>> NameChanging;
493    protected virtual void OnNameChanging(CancelEventArgs<string> e) {
494      var handler = NameChanging;
495      if (handler != null) handler(this, e);
496    }
497
498    public event EventHandler NameChanged;
499    protected virtual void OnNameChanged() {
500      var handler = NameChanged;
501      if (handler != null) handler(this, EventArgs.Empty);
502      OnToStringChanged();
503    }
504
505    public event EventHandler DescriptionChanged;
506    protected virtual void OnDescriptionChanged() {
507      var handler = DescriptionChanged;
508      if (handler != null) handler(this, EventArgs.Empty);
509    }
510
511    public event EventHandler ItemImageChanged;
512    protected virtual void OnItemImageChanged() {
513      EventHandler handler = ItemImageChanged;
514      if (handler != null) handler(this, EventArgs.Empty);
515    }
516    public event EventHandler ToStringChanged;
517    protected virtual void OnToStringChanged() {
518      EventHandler handler = ToStringChanged;
519      if (handler != null) handler(this, EventArgs.Empty);
520    }
521
522    protected virtual void DeregisterProblemEvents() {
523      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
524      problem.Reset -= new EventHandler(Problem_Reset);
525    }
526    protected virtual void RegisterProblemEvents() {
527      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
528      problem.Reset += new EventHandler(Problem_Reset);
529    }
530    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
531    protected virtual void Problem_Reset(object sender, EventArgs e) {
532      Prepare();
533    }
534
535    protected virtual void DeregisterRunsEvents() {
536      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
537    }
538    protected virtual void RegisterRunsEvents() {
539      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
540    }
541    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
542      runsCounter = runs.Count;
543    }
544
545    #endregion
546
547    #region Clone
548
549    public IDeepCloneable Clone(Cloner cloner) {
550      return new Benchmark(this, cloner);
551    }
552
553    public object Clone() {
554      return Clone(new Cloner());
555    }
556
557    #endregion
558  }
559}
Note: See TracBrowser for help on using the repository browser.