Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CloningRefactoring/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs @ 4662

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

Enabled saving of the CrossValidation (ticket #1199).

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