Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15002 was 15002, checked in by bburlacu, 7 years ago

#2760: Got rid of the shuffledProblemData by using a shared seed for all the folds (so that the dataset for each fold is shuffled in exactly the same way). Backwards compatibility should be restored.

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