Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs @ 4567

Last change on this file since 4567 was 4567, checked in by mkommend, 14 years ago

Filled ResultCollection in CrossValidation (ticket #1199).

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