Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs @ 6239

Last change on this file since 6239 was 6239, checked in by gkronber, 12 years ago

#1450: implemented support for ensemble solutions for classification.

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