Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1917: formatting

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