Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7112 was 7112, checked in by mkommend, 12 years ago

#1694: Corrected CrossValidation to make the SupportVectorPerformance unit test pass.

File size: 32.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.TrainingPartition.Start = SamplesStart.Value;
281            problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
282            problem.ProblemData.TestPartition.Start = testStart;
283            problem.ProblemData.TestPartition.End = testEnd;
284            DataAnalysisProblemData problemData = problem.ProblemData as DataAnalysisProblemData;
285            if (problemData != null) {
286              problemData.TrainingPartitionParameter.Hidden = false;
287              problemData.TestPartitionParameter.Hidden = false;
288            }
289
290            if (symbolicProblem != null) {
291              symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
292              symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
293            }
294
295            clonedAlgorithms.Add(clonedAlgorithm);
296          }
297        }
298
299        //start prepared or paused cloned algorithms
300        int startedAlgorithms = 0;
301        foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
302          if (startedAlgorithms < NumberOfWorkers.Value) {
303            if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
304                clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
305              clonedAlgorithm.Start();
306              startedAlgorithms++;
307            }
308          }
309        }
310        OnStarted();
311      }
312    }
313
314    private bool pausePending;
315    public void Pause() {
316      if (ExecutionState != ExecutionState.Started)
317        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
318      if (!pausePending) {
319        pausePending = true;
320        if (!startPending) PauseAllClonedAlgorithms();
321      }
322    }
323    private void PauseAllClonedAlgorithms() {
324      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
325        if (clonedAlgorithm.ExecutionState == ExecutionState.Started)
326          clonedAlgorithm.Pause();
327      }
328    }
329
330    private bool stopPending;
331    public void Stop() {
332      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
333        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".",
334                                                          ExecutionState));
335      if (!stopPending) {
336        stopPending = true;
337        if (!startPending) StopAllClonedAlgorithms();
338      }
339    }
340    private void StopAllClonedAlgorithms() {
341      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
342        if (clonedAlgorithm.ExecutionState == ExecutionState.Started ||
343            clonedAlgorithm.ExecutionState == ExecutionState.Paused)
344          clonedAlgorithm.Stop();
345      }
346    }
347
348    #region collect parameters and results
349    public override void CollectParameterValues(IDictionary<string, IItem> values) {
350      values.Add("Algorithm Name", new StringValue(Name));
351      values.Add("Algorithm Type", new StringValue(GetType().GetPrettyName()));
352      values.Add("Folds", new IntValue(Folds.Value));
353
354      if (algorithm != null) {
355        values.Add("CrossValidation Algorithm Name", new StringValue(Algorithm.Name));
356        values.Add("CrossValidation Algorithm Type", new StringValue(Algorithm.GetType().GetPrettyName()));
357        base.CollectParameterValues(values);
358      }
359      if (Problem != null) {
360        values.Add("Problem Name", new StringValue(Problem.Name));
361        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
362        Problem.CollectParameterValues(values);
363      }
364    }
365
366    public void CollectResultValues(IDictionary<string, IItem> results) {
367      var clonedResults = (ResultCollection)this.results.Clone();
368      foreach (var result in clonedResults) {
369        results.Add(result.Name, result.Value);
370      }
371    }
372
373    private void AggregateResultValues(IDictionary<string, IItem> results) {
374      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
375      IEnumerable<IRun> runs = clonedAlgorithms.Select(alg => alg.Runs.FirstOrDefault()).Where(run => run != null);
376      IEnumerable<KeyValuePair<string, IItem>> resultCollections = runs.Where(x => x != null).SelectMany(x => x.Results).ToList();
377
378      foreach (IResult result in ExtractAndAggregateResults<IntValue>(resultCollections))
379        results.Add(result.Name, result.Value);
380      foreach (IResult result in ExtractAndAggregateResults<DoubleValue>(resultCollections))
381        results.Add(result.Name, result.Value);
382      foreach (IResult result in ExtractAndAggregateResults<PercentValue>(resultCollections))
383        results.Add(result.Name, result.Value);
384      foreach (IResult result in ExtractAndAggregateRegressionSolutions(resultCollections)) {
385        results.Add(result.Name, result.Value);
386      }
387      foreach (IResult result in ExtractAndAggregateClassificationSolutions(resultCollections)) {
388        results.Add(result.Name, result.Value);
389      }
390      results.Add("Execution Time", new TimeSpanValue(this.ExecutionTime));
391      results.Add("CrossValidation Folds", new RunCollection(runs));
392    }
393
394    private IEnumerable<IResult> ExtractAndAggregateRegressionSolutions(IEnumerable<KeyValuePair<string, IItem>> resultCollections) {
395      Dictionary<string, List<IRegressionSolution>> resultSolutions = new Dictionary<string, List<IRegressionSolution>>();
396      foreach (var result in resultCollections) {
397        var regressionSolution = result.Value as IRegressionSolution;
398        if (regressionSolution != null) {
399          if (resultSolutions.ContainsKey(result.Key)) {
400            resultSolutions[result.Key].Add(regressionSolution);
401          } else {
402            resultSolutions.Add(result.Key, new List<IRegressionSolution>() { regressionSolution });
403          }
404        }
405      }
406      List<IResult> aggregatedResults = new List<IResult>();
407      foreach (KeyValuePair<string, List<IRegressionSolution>> solutions in resultSolutions) {
408        // clone manually to correctly clone references between cloned root objects
409        Cloner cloner = new Cloner();
410        var problemDataClone = (IRegressionProblemData)cloner.Clone(Problem.ProblemData);
411        // set partitions of problem data clone correctly
412        problemDataClone.TrainingPartition.Start = SamplesStart.Value; problemDataClone.TrainingPartition.End = SamplesEnd.Value;
413        problemDataClone.TestPartition.Start = SamplesStart.Value; problemDataClone.TestPartition.End = SamplesEnd.Value;
414        // clone models
415        var ensembleSolution = new RegressionEnsembleSolution(
416          solutions.Value.Select(x => cloner.Clone(x.Model)),
417          problemDataClone,
418          solutions.Value.Select(x => cloner.Clone(x.ProblemData.TrainingPartition)),
419          solutions.Value.Select(x => cloner.Clone(x.ProblemData.TestPartition)));
420
421        aggregatedResults.Add(new Result(solutions.Key + " (ensemble)", ensembleSolution));
422      }
423      List<IResult> flattenedResults = new List<IResult>();
424      CollectResultsRecursively("", aggregatedResults, flattenedResults);
425      return flattenedResults;
426    }
427
428    private IEnumerable<IResult> ExtractAndAggregateClassificationSolutions(IEnumerable<KeyValuePair<string, IItem>> resultCollections) {
429      Dictionary<string, List<IClassificationSolution>> resultSolutions = new Dictionary<string, List<IClassificationSolution>>();
430      foreach (var result in resultCollections) {
431        var classificationSolution = result.Value as IClassificationSolution;
432        if (classificationSolution != null) {
433          if (resultSolutions.ContainsKey(result.Key)) {
434            resultSolutions[result.Key].Add(classificationSolution);
435          } else {
436            resultSolutions.Add(result.Key, new List<IClassificationSolution>() { classificationSolution });
437          }
438        }
439      }
440      var aggregatedResults = new List<IResult>();
441      foreach (KeyValuePair<string, List<IClassificationSolution>> solutions in resultSolutions) {
442        // clone manually to correctly clone references between cloned root objects
443        Cloner cloner = new Cloner();
444        var problemDataClone = (IClassificationProblemData)cloner.Clone(Problem.ProblemData);
445        // set partitions of problem data clone correctly
446        problemDataClone.TrainingPartition.Start = SamplesStart.Value; problemDataClone.TrainingPartition.End = SamplesEnd.Value;
447        problemDataClone.TestPartition.Start = SamplesStart.Value; problemDataClone.TestPartition.End = SamplesEnd.Value;
448        // clone models
449        var ensembleSolution = new ClassificationEnsembleSolution(
450          solutions.Value.Select(x => cloner.Clone(x.Model)),
451          problemDataClone,
452          solutions.Value.Select(x => cloner.Clone(x.ProblemData.TrainingPartition)),
453          solutions.Value.Select(x => cloner.Clone(x.ProblemData.TestPartition)));
454
455        aggregatedResults.Add(new Result(solutions.Key + " (ensemble)", ensembleSolution));
456      }
457      List<IResult> flattenedResults = new List<IResult>();
458      CollectResultsRecursively("", aggregatedResults, flattenedResults);
459      return flattenedResults;
460    }
461
462    private void CollectResultsRecursively(string path, IEnumerable<IResult> results, IList<IResult> flattenedResults) {
463      foreach (IResult result in results) {
464        flattenedResults.Add(new Result(path + result.Name, result.Value));
465        ResultCollection childCollection = result.Value as ResultCollection;
466        if (childCollection != null) {
467          CollectResultsRecursively(path + result.Name + ".", childCollection, flattenedResults);
468        }
469      }
470    }
471
472    private static IEnumerable<IResult> ExtractAndAggregateResults<T>(IEnumerable<KeyValuePair<string, IItem>> results)
473  where T : class, IItem, new() {
474      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
475      foreach (var resultValue in results.Where(r => r.Value.GetType() == typeof(T))) {
476        if (!resultValues.ContainsKey(resultValue.Key))
477          resultValues[resultValue.Key] = new List<double>();
478        resultValues[resultValue.Key].Add(ConvertToDouble(resultValue.Value));
479      }
480
481      DoubleValue doubleValue;
482      if (typeof(T) == typeof(PercentValue))
483        doubleValue = new PercentValue();
484      else if (typeof(T) == typeof(DoubleValue))
485        doubleValue = new DoubleValue();
486      else if (typeof(T) == typeof(IntValue))
487        doubleValue = new DoubleValue();
488      else
489        throw new NotSupportedException();
490
491      List<IResult> aggregatedResults = new List<IResult>();
492      foreach (KeyValuePair<string, List<double>> resultValue in resultValues) {
493        doubleValue.Value = resultValue.Value.Average();
494        aggregatedResults.Add(new Result(resultValue.Key + " (average)", (IItem)doubleValue.Clone()));
495        doubleValue.Value = resultValue.Value.StandardDeviation();
496        aggregatedResults.Add(new Result(resultValue.Key + " (std.dev.)", (IItem)doubleValue.Clone()));
497      }
498      return aggregatedResults;
499    }
500
501    private static double ConvertToDouble(IItem item) {
502      if (item is DoubleValue) return ((DoubleValue)item).Value;
503      else if (item is IntValue) return ((IntValue)item).Value;
504      else throw new NotSupportedException("Could not convert any item type to double");
505    }
506    #endregion
507
508    #region events
509    private void RegisterEvents() {
510      Folds.ValueChanged += new EventHandler(Folds_ValueChanged);
511      SamplesStart.ValueChanged += new EventHandler(SamplesStart_ValueChanged);
512      SamplesEnd.ValueChanged += new EventHandler(SamplesEnd_ValueChanged);
513      RegisterClonedAlgorithmsEvents();
514    }
515    private void Folds_ValueChanged(object sender, EventArgs e) {
516      if (ExecutionState != ExecutionState.Prepared)
517        throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
518    }
519
520    private bool samplesChanged = false;
521    private void SamplesStart_ValueChanged(object sender, EventArgs e) {
522      samplesChanged = true;
523      if (Problem != null) Problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
524      samplesChanged = false;
525    }
526    private void SamplesEnd_ValueChanged(object sender, EventArgs e) {
527      samplesChanged = true;
528      if (Problem != null) Problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
529      samplesChanged = false;
530    }
531
532    #region template algorithms events
533    public event EventHandler AlgorithmChanged;
534    private void OnAlgorithmChanged() {
535      EventHandler handler = AlgorithmChanged;
536      if (handler != null) handler(this, EventArgs.Empty);
537      OnProblemChanged();
538      if (Problem == null) ExecutionState = ExecutionState.Stopped;
539    }
540    private void RegisterAlgorithmEvents() {
541      algorithm.ProblemChanged += new EventHandler(Algorithm_ProblemChanged);
542      algorithm.ExecutionStateChanged += new EventHandler(Algorithm_ExecutionStateChanged);
543    }
544    private void DeregisterAlgorithmEvents() {
545      algorithm.ProblemChanged -= new EventHandler(Algorithm_ProblemChanged);
546      algorithm.ExecutionStateChanged -= new EventHandler(Algorithm_ExecutionStateChanged);
547    }
548    private void Algorithm_ProblemChanged(object sender, EventArgs e) {
549      if (algorithm.Problem != null && !(algorithm.Problem is IDataAnalysisProblem)) {
550        algorithm.Problem = problem;
551        throw new ArgumentException("A cross validation algorithm can only contain DataAnalysisProblems.");
552      }
553      algorithm.Problem.Reset += (x, y) => OnProblemChanged();
554      problem = (IDataAnalysisProblem)algorithm.Problem;
555      OnProblemChanged();
556    }
557    public event EventHandler ProblemChanged;
558    private void OnProblemChanged() {
559      EventHandler handler = ProblemChanged;
560      if (handler != null) handler(this, EventArgs.Empty);
561      if (samplesChanged) return;
562
563      SamplesStart.Value = 0;
564      if (Problem != null) {
565        SamplesEnd.Value = Problem.ProblemData.Dataset.Rows;
566
567        DataAnalysisProblemData problemData = Problem.ProblemData as DataAnalysisProblemData;
568        if (problemData != null) {
569          problemData.TrainingPartitionParameter.Hidden = true;
570          problemData.TestPartitionParameter.Hidden = true;
571        }
572        ISymbolicDataAnalysisProblem symbolicProblem = Problem as ISymbolicDataAnalysisProblem;
573        if (symbolicProblem != null) {
574          symbolicProblem.FitnessCalculationPartitionParameter.Hidden = true;
575          symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
576          symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
577          symbolicProblem.ValidationPartitionParameter.Hidden = true;
578          symbolicProblem.ValidationPartition.Start = 0;
579          symbolicProblem.ValidationPartition.End = 0;
580        }
581      } else
582        SamplesEnd.Value = 0;
583
584      SamplesStart_ValueChanged(this, EventArgs.Empty);
585      SamplesEnd_ValueChanged(this, EventArgs.Empty);
586    }
587
588    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
589      switch (Algorithm.ExecutionState) {
590        case ExecutionState.Prepared: OnPrepared();
591          break;
592        case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
593        case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
594        case ExecutionState.Stopped: OnStopped();
595          break;
596      }
597    }
598    #endregion
599
600    #region clonedAlgorithms events
601    private void RegisterClonedAlgorithmsEvents() {
602      clonedAlgorithms.ItemsAdded += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
603      clonedAlgorithms.ItemsRemoved += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
604      clonedAlgorithms.CollectionReset += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
605      foreach (IAlgorithm algorithm in clonedAlgorithms)
606        RegisterClonedAlgorithmEvents(algorithm);
607    }
608    private void DeregisterClonedAlgorithmsEvents() {
609      clonedAlgorithms.ItemsAdded -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
610      clonedAlgorithms.ItemsRemoved -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
611      clonedAlgorithms.CollectionReset -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
612      foreach (IAlgorithm algorithm in clonedAlgorithms)
613        DeregisterClonedAlgorithmEvents(algorithm);
614    }
615    private void ClonedAlgorithms_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
616      foreach (IAlgorithm algorithm in e.Items)
617        RegisterClonedAlgorithmEvents(algorithm);
618    }
619    private void ClonedAlgorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
620      foreach (IAlgorithm algorithm in e.Items)
621        DeregisterClonedAlgorithmEvents(algorithm);
622    }
623    private void ClonedAlgorithms_CollectionReset(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
624      foreach (IAlgorithm algorithm in e.OldItems)
625        DeregisterClonedAlgorithmEvents(algorithm);
626      foreach (IAlgorithm algorithm in e.Items)
627        RegisterClonedAlgorithmEvents(algorithm);
628    }
629    private void RegisterClonedAlgorithmEvents(IAlgorithm algorithm) {
630      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
631      algorithm.ExecutionTimeChanged += new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
632      algorithm.Started += new EventHandler(ClonedAlgorithm_Started);
633      algorithm.Paused += new EventHandler(ClonedAlgorithm_Paused);
634      algorithm.Stopped += new EventHandler(ClonedAlgorithm_Stopped);
635    }
636    private void DeregisterClonedAlgorithmEvents(IAlgorithm algorithm) {
637      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
638      algorithm.ExecutionTimeChanged -= new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
639      algorithm.Started -= new EventHandler(ClonedAlgorithm_Started);
640      algorithm.Paused -= new EventHandler(ClonedAlgorithm_Paused);
641      algorithm.Stopped -= new EventHandler(ClonedAlgorithm_Stopped);
642    }
643    private void ClonedAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
644      OnExceptionOccurred(e.Value);
645    }
646    private void ClonedAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
647      OnExecutionTimeChanged();
648    }
649
650    private readonly object locker = new object();
651    private void ClonedAlgorithm_Started(object sender, EventArgs e) {
652      lock (locker) {
653        IAlgorithm algorithm = sender as IAlgorithm;
654        if (algorithm != null && !results.ContainsKey(algorithm.Name))
655          results.Add(new Result(algorithm.Name, "Contains results for the specific fold.", algorithm.Results));
656
657        if (startPending) {
658          int startedAlgorithms = clonedAlgorithms.Count(alg => alg.ExecutionState == ExecutionState.Started);
659          if (startedAlgorithms == NumberOfWorkers.Value ||
660             clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Prepared))
661            startPending = false;
662
663          if (pausePending) PauseAllClonedAlgorithms();
664          if (stopPending) StopAllClonedAlgorithms();
665        }
666      }
667    }
668
669    private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
670      lock (locker) {
671        if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
672          OnPaused();
673      }
674    }
675
676    private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
677      lock (locker) {
678        if (!stopPending && ExecutionState == ExecutionState.Started) {
679          IAlgorithm preparedAlgorithm = clonedAlgorithms.Where(alg => alg.ExecutionState == ExecutionState.Prepared ||
680                                                                       alg.ExecutionState == ExecutionState.Paused).FirstOrDefault();
681          if (preparedAlgorithm != null) preparedAlgorithm.Start();
682        }
683        if (ExecutionState != ExecutionState.Stopped) {
684          if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
685            OnStopped();
686          else if (stopPending &&
687                   clonedAlgorithms.All(
688                     alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
689            OnStopped();
690        }
691      }
692    }
693    #endregion
694    #endregion
695
696    #region event firing
697    public event EventHandler ExecutionStateChanged;
698    private void OnExecutionStateChanged() {
699      EventHandler handler = ExecutionStateChanged;
700      if (handler != null) handler(this, EventArgs.Empty);
701    }
702    public event EventHandler ExecutionTimeChanged;
703    private void OnExecutionTimeChanged() {
704      EventHandler handler = ExecutionTimeChanged;
705      if (handler != null) handler(this, EventArgs.Empty);
706    }
707    public event EventHandler Prepared;
708    private void OnPrepared() {
709      ExecutionState = ExecutionState.Prepared;
710      EventHandler handler = Prepared;
711      if (handler != null) handler(this, EventArgs.Empty);
712      OnExecutionTimeChanged();
713    }
714    public event EventHandler Started;
715    private void OnStarted() {
716      startPending = false;
717      ExecutionState = ExecutionState.Started;
718      EventHandler handler = Started;
719      if (handler != null) handler(this, EventArgs.Empty);
720    }
721    public event EventHandler Paused;
722    private void OnPaused() {
723      pausePending = false;
724      ExecutionState = ExecutionState.Paused;
725      EventHandler handler = Paused;
726      if (handler != null) handler(this, EventArgs.Empty);
727    }
728    public event EventHandler Stopped;
729    private void OnStopped() {
730      stopPending = false;
731      Dictionary<string, IItem> collectedResults = new Dictionary<string, IItem>();
732      AggregateResultValues(collectedResults);
733      results.AddRange(collectedResults.Select(x => new Result(x.Key, x.Value)).Cast<IResult>().ToArray());
734      runsCounter++;
735      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
736      ExecutionState = ExecutionState.Stopped;
737      EventHandler handler = Stopped;
738      if (handler != null) handler(this, EventArgs.Empty);
739    }
740    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
741    private void OnExceptionOccurred(Exception exception) {
742      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
743      if (handler != null) handler(this, new EventArgs<Exception>(exception));
744    }
745    public event EventHandler StoreAlgorithmInEachRunChanged;
746    private void OnStoreAlgorithmInEachRunChanged() {
747      EventHandler handler = StoreAlgorithmInEachRunChanged;
748      if (handler != null) handler(this, EventArgs.Empty);
749    }
750    #endregion
751  }
752}
Note: See TracBrowser for help on using the repository browser.