Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs @ 5649

Last change on this file since 5649 was 5625, checked in by mkommend, 13 years ago

#1418: Reorganized branch and removed CreateAble-Attribute from outdated classes.

File size: 25.7 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 HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  [Item("Cross Validation", "Cross Validation wrapper for data analysis algorithms.")]
36  [StorableClass]
37  public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm, IStorableContent {
38    public CrossValidation()
39      : base() {
40      name = ItemName;
41      description = ItemDescription;
42
43      executionState = ExecutionState.Stopped;
44      runs = new RunCollection();
45      runsCounter = 0;
46
47      algorithm = null;
48      clonedAlgorithms = new ItemCollection<IAlgorithm>();
49      results = new ResultCollection();
50
51      folds = new IntValue(2);
52      numberOfWorkers = new IntValue(1);
53      samplesStart = new IntValue(0);
54      samplesEnd = new IntValue(0);
55      storeAlgorithmInEachRun = false;
56
57      RegisterEvents();
58      if (Algorithm != null) RegisterAlgorithmEvents();
59    }
60
61    public string Filename { get; set; }
62
63    #region persistence and cloning
64    [StorableConstructor]
65    private CrossValidation(bool deserializing)
66      : base(deserializing) {
67    }
68    [StorableHook(HookType.AfterDeserialization)]
69    private void AfterDeserialization() {
70      RegisterEvents();
71      if (Algorithm != null) RegisterAlgorithmEvents();
72    }
73
74    private CrossValidation(CrossValidation original, Cloner cloner)
75      : base(original, cloner) {
76      executionState = original.executionState;
77      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
78      runs = cloner.Clone(original.runs);
79      runsCounter = original.runsCounter;
80      algorithm = cloner.Clone(original.algorithm);
81      clonedAlgorithms = cloner.Clone(original.clonedAlgorithms);
82      results = cloner.Clone(original.results);
83
84      folds = cloner.Clone(original.folds);
85      numberOfWorkers = cloner.Clone(original.numberOfWorkers);
86      samplesStart = cloner.Clone(original.samplesStart);
87      samplesEnd = cloner.Clone(original.samplesEnd);
88      RegisterEvents();
89      if (Algorithm != null) RegisterAlgorithmEvents();
90    }
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new CrossValidation(this, cloner);
93    }
94
95    #endregion
96
97    #region properties
98    [Storable]
99    private IAlgorithm algorithm;
100    public IAlgorithm Algorithm {
101      get { return algorithm; }
102      set {
103        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
104          throw new InvalidOperationException("Changing the algorithm is only allowed if the CrossValidation is stopped or prepared.");
105        if (algorithm != value) {
106          if (value != null && value.Problem != null && !(value.Problem is IDataAnalysisProblem))
107            throw new ArgumentException("Only algorithms with a DataAnalysisProblem could be used for the cross validation.");
108          if (algorithm != null) DeregisterAlgorithmEvents();
109          algorithm = value;
110          Parameters.Clear();
111
112          if (algorithm != null) {
113            algorithm.StoreAlgorithmInEachRun = false;
114            RegisterAlgorithmEvents();
115            algorithm.Prepare(true);
116            Parameters.AddRange(algorithm.Parameters);
117          }
118          OnAlgorithmChanged();
119          if (algorithm != null) OnProblemChanged();
120          Prepare();
121        }
122      }
123    }
124
125
126    [Storable]
127    private ISingleObjectiveDataAnalysisProblem problem;
128    public ISingleObjectiveDataAnalysisProblem Problem {
129      get {
130        if (algorithm == null)
131          return null;
132        return (ISingleObjectiveDataAnalysisProblem)algorithm.Problem;
133      }
134      set {
135        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
136          throw new InvalidOperationException("Changing the problem is only allowed if the CrossValidation is stopped or prepared.");
137        if (algorithm == null) throw new ArgumentNullException("Could not set a problem before an algorithm was set.");
138        algorithm.Problem = value;
139        problem = value;
140      }
141    }
142
143    IProblem IAlgorithm.Problem {
144      get { return Problem; }
145      set {
146        if (value != null && !ProblemType.IsInstanceOfType(value))
147          throw new ArgumentException("Only DataAnalysisProblems could be used for the cross validation.");
148        Problem = (ISingleObjectiveDataAnalysisProblem)value;
149      }
150    }
151    public Type ProblemType {
152      get { return typeof(ISingleObjectiveDataAnalysisProblem); }
153    }
154
155    [Storable]
156    private ItemCollection<IAlgorithm> clonedAlgorithms;
157
158    public IEnumerable<IOptimizer> NestedOptimizers {
159      get {
160        if (Algorithm == null) yield break;
161        yield return Algorithm;
162      }
163    }
164
165    [Storable]
166    private ResultCollection results;
167    public ResultCollection Results {
168      get { return results; }
169    }
170
171    [Storable]
172    private IntValue folds;
173    public IntValue Folds {
174      get { return folds; }
175    }
176    [Storable]
177    private IntValue samplesStart;
178    public IntValue SamplesStart {
179      get { return samplesStart; }
180    }
181    [Storable]
182    private IntValue samplesEnd;
183    public IntValue SamplesEnd {
184      get { return samplesEnd; }
185    }
186    [Storable]
187    private IntValue numberOfWorkers;
188    public IntValue NumberOfWorkers {
189      get { return numberOfWorkers; }
190    }
191
192    [Storable]
193    private bool storeAlgorithmInEachRun;
194    public bool StoreAlgorithmInEachRun {
195      get { return storeAlgorithmInEachRun; }
196      set {
197        if (storeAlgorithmInEachRun != value) {
198          storeAlgorithmInEachRun = value;
199          OnStoreAlgorithmInEachRunChanged();
200        }
201      }
202    }
203
204    [Storable]
205    private int runsCounter;
206    [Storable]
207    private RunCollection runs;
208    public RunCollection Runs {
209      get { return runs; }
210    }
211
212    [Storable]
213    private ExecutionState executionState;
214    public ExecutionState ExecutionState {
215      get { return executionState; }
216      private set {
217        if (executionState != value) {
218          executionState = value;
219          OnExecutionStateChanged();
220          OnItemImageChanged();
221        }
222      }
223    }
224    public override Image ItemImage {
225      get {
226        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
227        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
228        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
229        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
230        else return HeuristicLab.Common.Resources.VSImageLibrary.Event;
231      }
232    }
233
234    public TimeSpan ExecutionTime {
235      get {
236        if (ExecutionState != ExecutionState.Prepared)
237          return TimeSpan.FromMilliseconds(clonedAlgorithms.Select(x => x.ExecutionTime.TotalMilliseconds).Sum());
238        return TimeSpan.Zero;
239      }
240    }
241    #endregion
242
243    public void Prepare() {
244      if (ExecutionState == ExecutionState.Started)
245        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
246      results.Clear();
247      clonedAlgorithms.Clear();
248      if (Algorithm != null) {
249        Algorithm.Prepare();
250        if (Algorithm.ExecutionState == ExecutionState.Prepared) OnPrepared();
251      }
252    }
253    public void Prepare(bool clearRuns) {
254      if (clearRuns) runs.Clear();
255      Prepare();
256    }
257
258    private bool startPending;
259    public void Start() {
260      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
261        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
262
263      if (Algorithm != null && !startPending) {
264        startPending = true;
265        //create cloned algorithms
266        if (clonedAlgorithms.Count == 0) {
267          int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
268          for (int i = 0; i < Folds.Value; i++) {
269            IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
270            clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
271            IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
272            problem.DataAnalysisProblemData.TestSamplesEnd.Value = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
273            problem.DataAnalysisProblemData.TestSamplesStart.Value = (i * testSamplesCount) + SamplesStart.Value;
274            clonedAlgorithms.Add(clonedAlgorithm);
275          }
276        }
277
278        //start prepared or paused cloned algorithms
279        int startedAlgorithms = 0;
280        foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
281          if (startedAlgorithms < NumberOfWorkers.Value) {
282            if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
283                clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
284              clonedAlgorithm.Start();
285              startedAlgorithms++;
286            }
287          }
288        }
289        OnStarted();
290      }
291    }
292
293    private bool pausePending;
294    public void Pause() {
295      if (ExecutionState != ExecutionState.Started)
296        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
297      if (!pausePending) {
298        pausePending = true;
299        if (!startPending) PauseAllClonedAlgorithms();
300      }
301    }
302    private void PauseAllClonedAlgorithms() {
303      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
304        if (clonedAlgorithm.ExecutionState == ExecutionState.Started)
305          clonedAlgorithm.Pause();
306      }
307    }
308
309    private bool stopPending;
310    public void Stop() {
311      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
312        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".",
313                                                          ExecutionState));
314      if (!stopPending) {
315        stopPending = true;
316        if (!startPending) StopAllClonedAlgorithms();
317      }
318    }
319    private void StopAllClonedAlgorithms() {
320      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
321        if (clonedAlgorithm.ExecutionState == ExecutionState.Started ||
322            clonedAlgorithm.ExecutionState == ExecutionState.Paused)
323          clonedAlgorithm.Stop();
324      }
325    }
326
327    #region collect parameters and results
328    public override void CollectParameterValues(IDictionary<string, IItem> values) {
329      values.Add("Algorithm Name", new StringValue(Name));
330      values.Add("Algorithm Type", new StringValue(GetType().GetPrettyName()));
331      values.Add("Folds", new IntValue(Folds.Value));
332
333      if (algorithm != null) {
334        values.Add("CrossValidation Algorithm Name", new StringValue(Algorithm.Name));
335        values.Add("CrossValidation Algorithm Type", new StringValue(Algorithm.GetType().GetPrettyName()));
336        base.CollectParameterValues(values);
337      }
338      if (Problem != null) {
339        values.Add("Problem Name", new StringValue(Problem.Name));
340        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
341        Problem.CollectParameterValues(values);
342      }
343    }
344
345    public void CollectResultValues(IDictionary<string, IItem> results) {
346      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
347      IEnumerable<IRun> runs = clonedAlgorithms.Select(alg => alg.Runs.FirstOrDefault()).Where(run => run != null);
348      IEnumerable<KeyValuePair<string, IItem>> resultCollections = runs.Where(x => x != null).SelectMany(x => x.Results).ToList();
349
350      foreach (IResult result in ExtractAndAggregateResults<IntValue>(resultCollections))
351        results.Add(result.Name, result.Value);
352      foreach (IResult result in ExtractAndAggregateResults<DoubleValue>(resultCollections))
353        results.Add(result.Name, result.Value);
354      foreach (IResult result in ExtractAndAggregateResults<PercentValue>(resultCollections))
355        results.Add(result.Name, result.Value);
356
357      results.Add("Execution Time", new TimeSpanValue(this.ExecutionTime));
358      results.Add("CrossValidation Folds", new RunCollection(runs));
359    }
360
361    private static IEnumerable<IResult> ExtractAndAggregateResults<T>(IEnumerable<KeyValuePair<string, IItem>> results)
362  where T : class, IItem, new() {
363      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
364      foreach (var resultValue in results.Where(r => r.Value.GetType() == typeof(T))) {
365        if (!resultValues.ContainsKey(resultValue.Key))
366          resultValues[resultValue.Key] = new List<double>();
367        resultValues[resultValue.Key].Add(ConvertToDouble(resultValue.Value));
368      }
369
370      DoubleValue doubleValue;
371      if (typeof(T) == typeof(PercentValue))
372        doubleValue = new PercentValue();
373      else if (typeof(T) == typeof(DoubleValue))
374        doubleValue = new DoubleValue();
375      else if (typeof(T) == typeof(IntValue))
376        doubleValue = new DoubleValue();
377      else
378        throw new NotSupportedException();
379
380      List<IResult> aggregatedResults = new List<IResult>();
381      foreach (KeyValuePair<string, List<double>> resultValue in resultValues) {
382        doubleValue.Value = resultValue.Value.Average();
383        aggregatedResults.Add(new Result(resultValue.Key, (IItem)doubleValue.Clone()));
384        doubleValue.Value = resultValue.Value.StandardDeviation();
385        aggregatedResults.Add(new Result(resultValue.Key + " StdDev", (IItem)doubleValue.Clone()));
386      }
387      return aggregatedResults;
388    }
389
390    private static double ConvertToDouble(IItem item) {
391      if (item is DoubleValue) return ((DoubleValue)item).Value;
392      else if (item is IntValue) return ((IntValue)item).Value;
393      else throw new NotSupportedException("Could not convert any item type to double");
394    }
395    #endregion
396
397    #region events
398    private void RegisterEvents() {
399      Folds.ValueChanged += new EventHandler(Folds_ValueChanged);
400      SamplesStart.ValueChanged += new EventHandler(SamplesStart_ValueChanged);
401      SamplesEnd.ValueChanged += new EventHandler(SamplesEnd_ValueChanged);
402      RegisterClonedAlgorithmsEvents();
403    }
404    private void Folds_ValueChanged(object sender, EventArgs e) {
405      if (ExecutionState != ExecutionState.Prepared)
406        throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
407    }
408    private void SamplesStart_ValueChanged(object sender, EventArgs e) {
409      if (Problem != null) Problem.DataAnalysisProblemData.TrainingSamplesStart.Value = SamplesStart.Value;
410    }
411    private void SamplesEnd_ValueChanged(object sender, EventArgs e) {
412      if (Problem != null) Problem.DataAnalysisProblemData.TrainingSamplesEnd.Value = SamplesEnd.Value;
413    }
414
415    #region template algorithms events
416    public event EventHandler AlgorithmChanged;
417    private void OnAlgorithmChanged() {
418      EventHandler handler = AlgorithmChanged;
419      if (handler != null) handler(this, EventArgs.Empty);
420      OnProblemChanged();
421      if (Problem == null) ExecutionState = ExecutionState.Stopped;
422    }
423    private void RegisterAlgorithmEvents() {
424      algorithm.ProblemChanged += new EventHandler(Algorithm_ProblemChanged);
425      algorithm.ExecutionStateChanged += new EventHandler(Algorithm_ExecutionStateChanged);
426    }
427    private void DeregisterAlgorithmEvents() {
428      algorithm.ProblemChanged -= new EventHandler(Algorithm_ProblemChanged);
429      algorithm.ExecutionStateChanged -= new EventHandler(Algorithm_ExecutionStateChanged);
430    }
431    private void Algorithm_ProblemChanged(object sender, EventArgs e) {
432      if (algorithm.Problem != null && !(algorithm.Problem is ISingleObjectiveDataAnalysisProblem)) {
433        algorithm.Problem = problem;
434        throw new ArgumentException("A cross validation algorithm can only contain DataAnalysisProblems.");
435      }
436      problem = (ISingleObjectiveDataAnalysisProblem)algorithm.Problem;
437      OnProblemChanged();
438    }
439    public event EventHandler ProblemChanged;
440    private void OnProblemChanged() {
441      EventHandler handler = ProblemChanged;
442      if (handler != null) handler(this, EventArgs.Empty);
443
444      SamplesStart.Value = 0;
445      if (Problem != null)
446        SamplesEnd.Value = Problem.DataAnalysisProblemData.Dataset.Rows;
447      else
448        SamplesEnd.Value = 0;
449    }
450
451    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
452      switch (Algorithm.ExecutionState) {
453        case ExecutionState.Prepared: OnPrepared();
454          break;
455        case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
456        case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
457        case ExecutionState.Stopped: OnStopped();
458          break;
459      }
460    }
461    #endregion
462
463    #region clonedAlgorithms events
464    private void RegisterClonedAlgorithmsEvents() {
465      clonedAlgorithms.ItemsAdded += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
466      clonedAlgorithms.ItemsRemoved += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
467      clonedAlgorithms.CollectionReset += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
468      foreach (IAlgorithm algorithm in clonedAlgorithms)
469        RegisterClonedAlgorithmEvents(algorithm);
470    }
471    private void DeregisterClonedAlgorithmsEvents() {
472      clonedAlgorithms.ItemsAdded -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
473      clonedAlgorithms.ItemsRemoved -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
474      clonedAlgorithms.CollectionReset -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
475      foreach (IAlgorithm algorithm in clonedAlgorithms)
476        DeregisterClonedAlgorithmEvents(algorithm);
477    }
478    private void ClonedAlgorithms_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
479      foreach (IAlgorithm algorithm in e.Items)
480        RegisterClonedAlgorithmEvents(algorithm);
481    }
482    private void ClonedAlgorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
483      foreach (IAlgorithm algorithm in e.Items)
484        DeregisterClonedAlgorithmEvents(algorithm);
485    }
486    private void ClonedAlgorithms_CollectionReset(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
487      foreach (IAlgorithm algorithm in e.OldItems)
488        DeregisterClonedAlgorithmEvents(algorithm);
489      foreach (IAlgorithm algorithm in e.Items)
490        RegisterClonedAlgorithmEvents(algorithm);
491    }
492    private void RegisterClonedAlgorithmEvents(IAlgorithm algorithm) {
493      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
494      algorithm.ExecutionTimeChanged += new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
495      algorithm.Started += new EventHandler(ClonedAlgorithm_Started);
496      algorithm.Paused += new EventHandler(ClonedAlgorithm_Paused);
497      algorithm.Stopped += new EventHandler(ClonedAlgorithm_Stopped);
498    }
499    private void DeregisterClonedAlgorithmEvents(IAlgorithm algorithm) {
500      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
501      algorithm.ExecutionTimeChanged -= new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
502      algorithm.Started -= new EventHandler(ClonedAlgorithm_Started);
503      algorithm.Paused -= new EventHandler(ClonedAlgorithm_Paused);
504      algorithm.Stopped -= new EventHandler(ClonedAlgorithm_Stopped);
505    }
506    private void ClonedAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
507      OnExceptionOccurred(e.Value);
508    }
509    private void ClonedAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
510      OnExecutionTimeChanged();
511    }
512
513    private readonly object locker = new object();
514    private void ClonedAlgorithm_Started(object sender, EventArgs e) {
515      lock (locker) {
516        IAlgorithm algorithm = sender as IAlgorithm;
517        if (algorithm != null && !results.ContainsKey(algorithm.Name))
518          results.Add(new Result(algorithm.Name, "Contains results for the specific fold.", algorithm.Results));
519
520        if (startPending) {
521          int startedAlgorithms = clonedAlgorithms.Count(alg => alg.ExecutionState == ExecutionState.Started);
522          if (startedAlgorithms == NumberOfWorkers.Value ||
523             clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Prepared))
524            startPending = false;
525
526          if (pausePending) PauseAllClonedAlgorithms();
527          if (stopPending) StopAllClonedAlgorithms();
528        }
529      }
530    }
531
532    private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
533      lock (locker) {
534        if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
535          OnPaused();
536      }
537    }
538
539    private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
540      lock (locker) {
541        if (!stopPending && ExecutionState == ExecutionState.Started) {
542          IAlgorithm preparedAlgorithm = clonedAlgorithms.Where(alg => alg.ExecutionState == ExecutionState.Prepared ||
543                                                                       alg.ExecutionState == ExecutionState.Paused).FirstOrDefault();
544          if (preparedAlgorithm != null) preparedAlgorithm.Start();
545        }
546        if (ExecutionState != ExecutionState.Stopped) {
547          if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
548            OnStopped();
549          else if (stopPending &&
550                   clonedAlgorithms.All(
551                     alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
552            OnStopped();
553        }
554      }
555    }
556    #endregion
557    #endregion
558
559    #region event firing
560    public event EventHandler ExecutionStateChanged;
561    private void OnExecutionStateChanged() {
562      EventHandler handler = ExecutionStateChanged;
563      if (handler != null) handler(this, EventArgs.Empty);
564    }
565    public event EventHandler ExecutionTimeChanged;
566    private void OnExecutionTimeChanged() {
567      EventHandler handler = ExecutionTimeChanged;
568      if (handler != null) handler(this, EventArgs.Empty);
569    }
570    public event EventHandler Prepared;
571    private void OnPrepared() {
572      ExecutionState = ExecutionState.Prepared;
573      EventHandler handler = Prepared;
574      if (handler != null) handler(this, EventArgs.Empty);
575      OnExecutionTimeChanged();
576    }
577    public event EventHandler Started;
578    private void OnStarted() {
579      startPending = false;
580      ExecutionState = ExecutionState.Started;
581      EventHandler handler = Started;
582      if (handler != null) handler(this, EventArgs.Empty);
583    }
584    public event EventHandler Paused;
585    private void OnPaused() {
586      pausePending = false;
587      ExecutionState = ExecutionState.Paused;
588      EventHandler handler = Paused;
589      if (handler != null) handler(this, EventArgs.Empty);
590    }
591    public event EventHandler Stopped;
592    private void OnStopped() {
593      stopPending = false;
594      Dictionary<string, IItem> collectedResults = new Dictionary<string, IItem>();
595      CollectResultValues(collectedResults);
596      results.AddRange(collectedResults.Select(x => new Result(x.Key, x.Value)).Cast<IResult>().ToArray());
597      runsCounter++;
598      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
599      ExecutionState = ExecutionState.Stopped;
600      EventHandler handler = Stopped;
601      if (handler != null) handler(this, EventArgs.Empty);
602    }
603    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
604    private void OnExceptionOccurred(Exception exception) {
605      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
606      if (handler != null) handler(this, new EventArgs<Exception>(exception));
607    }
608    public event EventHandler StoreAlgorithmInEachRunChanged;
609    private void OnStoreAlgorithmInEachRunChanged() {
610      EventHandler handler = StoreAlgorithmInEachRunChanged;
611      if (handler != null) handler(this, EventArgs.Empty);
612    }
613    #endregion
614  }
615}
Note: See TracBrowser for help on using the repository browser.