Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.Benchmarks/3.3/Benchmark.cs @ 7015

Last change on this file since 7015 was 7015, checked in by ascheibe, 12 years ago

#1659 removed .resx files and moved Benchmark to Algorithms category

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