Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs @ 5420

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

#1402 - Refactored OnClosed method of IOptimizer views.

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