Free cookie consent management tool by TermsFeed Policy Generator

source: branches/LearningClassifierSystems/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs @ 17842

Last change on this file since 17842 was 9411, checked in by sforsten, 12 years ago

#1980:

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