Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8965 was 8965, checked in by mkommend, 11 years ago

#1917: Added missing event registration in AfterDeserialization of CrossValidation and clean up code if a problem changes in the crossvalidation. Additionally, I removed explicit calls to OnReset in the Load methods of IDataAnalysisProblems the reset event is automatically fired when the problem data is changed.

File size: 32.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Threading;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Problems.DataAnalysis;
34using HeuristicLab.Problems.DataAnalysis.Symbolic;
35
36namespace HeuristicLab.Algorithms.DataAnalysis {
37  [Item("Cross Validation", "Cross-validation wrapper for data analysis algorithms.")]
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;
47      runs = new RunCollection { OptimizerName = name };
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      if (Problem != null) Problem.Reset += (o, e) => OnProblemChanged();
76    }
77
78    private CrossValidation(CrossValidation original, Cloner cloner)
79      : base(original, cloner) {
80      executionState = original.executionState;
81      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
82      runs = cloner.Clone(original.runs);
83      runsCounter = original.runsCounter;
84      algorithm = cloner.Clone(original.algorithm);
85      clonedAlgorithms = cloner.Clone(original.clonedAlgorithms);
86      results = cloner.Clone(original.results);
87
88      folds = cloner.Clone(original.folds);
89      numberOfWorkers = cloner.Clone(original.numberOfWorkers);
90      samplesStart = cloner.Clone(original.samplesStart);
91      samplesEnd = cloner.Clone(original.samplesEnd);
92      RegisterEvents();
93      if (Algorithm != null) RegisterAlgorithmEvents();
94    }
95    public override IDeepCloneable Clone(Cloner cloner) {
96      return new CrossValidation(this, cloner);
97    }
98
99    #endregion
100
101    #region properties
102    [Storable]
103    private IAlgorithm algorithm;
104    public IAlgorithm Algorithm {
105      get { return algorithm; }
106      set {
107        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
108          throw new InvalidOperationException("Changing the algorithm is only allowed if the CrossValidation is stopped or prepared.");
109        if (algorithm != value) {
110          if (value != null && value.Problem != null && !(value.Problem is IDataAnalysisProblem))
111            throw new ArgumentException("Only algorithms with a DataAnalysisProblem could be used for the cross validation.");
112          if (algorithm != null) DeregisterAlgorithmEvents();
113          algorithm = value;
114          Parameters.Clear();
115
116          if (algorithm != null) {
117            algorithm.StoreAlgorithmInEachRun = false;
118            RegisterAlgorithmEvents();
119            algorithm.Prepare(true);
120            Parameters.AddRange(algorithm.Parameters);
121          }
122          OnAlgorithmChanged();
123          if (algorithm != null) OnProblemChanged();
124          Prepare();
125        }
126      }
127    }
128
129
130    [Storable]
131    private IDataAnalysisProblem problem;
132    public IDataAnalysisProblem Problem {
133      get {
134        if (algorithm == null)
135          return null;
136        return (IDataAnalysisProblem)algorithm.Problem;
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.");
152        Problem = (IDataAnalysisProblem)value;
153      }
154    }
155    public Type ProblemType {
156      get { return typeof(IDataAnalysisProblem); }
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    }
228    public static new Image StaticItemImage {
229      get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; }
230    }
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;
237        else return base.ItemImage;
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
250    protected override void OnNameChanged() {
251      base.OnNameChanged();
252      Runs.OptimizerName = Name;
253    }
254
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;
280
281          for (int i = 0; i < Folds.Value; i++) {
282            IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
283            clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
284            IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
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
290            problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
291            problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
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            }
304            clonedAlgorithm.Prepare();
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) {
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              }
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) {
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) {
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);
403      foreach (IResult result in ExtractAndAggregateRegressionSolutions(resultCollections)) {
404        results.Add(result.Name, result.Value);
405      }
406      foreach (IResult result in ExtractAndAggregateClassificationSolutions(resultCollections)) {
407        results.Add(result.Name, result.Value);
408      }
409      results.Add("Execution Time", new TimeSpanValue(this.ExecutionTime));
410      results.Add("CrossValidation Folds", new RunCollection(runs));
411    }
412
413    private IEnumerable<IResult> ExtractAndAggregateRegressionSolutions(IEnumerable<KeyValuePair<string, IItem>> resultCollections) {
414      Dictionary<string, List<IRegressionSolution>> resultSolutions = new Dictionary<string, List<IRegressionSolution>>();
415      foreach (var result in resultCollections) {
416        var regressionSolution = result.Value as IRegressionSolution;
417        if (regressionSolution != null) {
418          if (resultSolutions.ContainsKey(result.Key)) {
419            resultSolutions[result.Key].Add(regressionSolution);
420          } else {
421            resultSolutions.Add(result.Key, new List<IRegressionSolution>() { regressionSolution });
422          }
423        }
424      }
425      List<IResult> aggregatedResults = new List<IResult>();
426      foreach (KeyValuePair<string, List<IRegressionSolution>> solutions in resultSolutions) {
427        // clone manually to correctly clone references between cloned root objects
428        Cloner cloner = new Cloner();
429        var problemDataClone = (IRegressionProblemData)cloner.Clone(Problem.ProblemData);
430        // set partitions of problem data clone correctly
431        problemDataClone.TrainingPartition.Start = SamplesStart.Value; problemDataClone.TrainingPartition.End = SamplesEnd.Value;
432        problemDataClone.TestPartition.Start = SamplesStart.Value; problemDataClone.TestPartition.End = SamplesEnd.Value;
433        // clone models
434        var ensembleSolution = new RegressionEnsembleSolution(problemDataClone);
435        ensembleSolution.AddRegressionSolutions(solutions.Value);
436
437        aggregatedResults.Add(new Result(solutions.Key + " (ensemble)", ensembleSolution));
438      }
439      List<IResult> flattenedResults = new List<IResult>();
440      CollectResultsRecursively("", aggregatedResults, flattenedResults);
441      return flattenedResults;
442    }
443
444    private IEnumerable<IResult> ExtractAndAggregateClassificationSolutions(IEnumerable<KeyValuePair<string, IItem>> resultCollections) {
445      Dictionary<string, List<IClassificationSolution>> resultSolutions = new Dictionary<string, List<IClassificationSolution>>();
446      foreach (var result in resultCollections) {
447        var classificationSolution = result.Value as IClassificationSolution;
448        if (classificationSolution != null) {
449          if (resultSolutions.ContainsKey(result.Key)) {
450            resultSolutions[result.Key].Add(classificationSolution);
451          } else {
452            resultSolutions.Add(result.Key, new List<IClassificationSolution>() { classificationSolution });
453          }
454        }
455      }
456      var aggregatedResults = new List<IResult>();
457      foreach (KeyValuePair<string, List<IClassificationSolution>> solutions in resultSolutions) {
458        // clone manually to correctly clone references between cloned root objects
459        Cloner cloner = new Cloner();
460        var problemDataClone = (IClassificationProblemData)cloner.Clone(Problem.ProblemData);
461        // set partitions of problem data clone correctly
462        problemDataClone.TrainingPartition.Start = SamplesStart.Value; problemDataClone.TrainingPartition.End = SamplesEnd.Value;
463        problemDataClone.TestPartition.Start = SamplesStart.Value; problemDataClone.TestPartition.End = SamplesEnd.Value;
464        // clone models
465        var ensembleSolution = new ClassificationEnsembleSolution(problemDataClone);
466        ensembleSolution.AddClassificationSolutions(solutions.Value);
467
468        aggregatedResults.Add(new Result(solutions.Key + " (ensemble)", ensembleSolution));
469      }
470      List<IResult> flattenedResults = new List<IResult>();
471      CollectResultsRecursively("", aggregatedResults, flattenedResults);
472      return flattenedResults;
473    }
474
475    private void CollectResultsRecursively(string path, IEnumerable<IResult> results, IList<IResult> flattenedResults) {
476      foreach (IResult result in results) {
477        flattenedResults.Add(new Result(path + result.Name, result.Value));
478        ResultCollection childCollection = result.Value as ResultCollection;
479        if (childCollection != null) {
480          CollectResultsRecursively(path + result.Name + ".", childCollection, flattenedResults);
481        }
482      }
483    }
484
485    private static IEnumerable<IResult> ExtractAndAggregateResults<T>(IEnumerable<KeyValuePair<string, IItem>> results)
486  where T : class, IItem, new() {
487      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
488      foreach (var resultValue in results.Where(r => r.Value.GetType() == typeof(T))) {
489        if (!resultValues.ContainsKey(resultValue.Key))
490          resultValues[resultValue.Key] = new List<double>();
491        resultValues[resultValue.Key].Add(ConvertToDouble(resultValue.Value));
492      }
493
494      DoubleValue doubleValue;
495      if (typeof(T) == typeof(PercentValue))
496        doubleValue = new PercentValue();
497      else if (typeof(T) == typeof(DoubleValue))
498        doubleValue = new DoubleValue();
499      else if (typeof(T) == typeof(IntValue))
500        doubleValue = new DoubleValue();
501      else
502        throw new NotSupportedException();
503
504      List<IResult> aggregatedResults = new List<IResult>();
505      foreach (KeyValuePair<string, List<double>> resultValue in resultValues) {
506        doubleValue.Value = resultValue.Value.Average();
507        aggregatedResults.Add(new Result(resultValue.Key + " (average)", (IItem)doubleValue.Clone()));
508        doubleValue.Value = resultValue.Value.StandardDeviation();
509        aggregatedResults.Add(new Result(resultValue.Key + " (std.dev.)", (IItem)doubleValue.Clone()));
510      }
511      return aggregatedResults;
512    }
513
514    private static double ConvertToDouble(IItem item) {
515      if (item is DoubleValue) return ((DoubleValue)item).Value;
516      else if (item is IntValue) return ((IntValue)item).Value;
517      else throw new NotSupportedException("Could not convert any item type to double");
518    }
519    #endregion
520
521    #region events
522    private void RegisterEvents() {
523      Folds.ValueChanged += new EventHandler(Folds_ValueChanged);
524      RegisterClonedAlgorithmsEvents();
525    }
526    private void Folds_ValueChanged(object sender, EventArgs e) {
527      if (ExecutionState != ExecutionState.Prepared)
528        throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
529    }
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
562      SamplesStart.Value = 0;
563      if (Problem != null) {
564        SamplesEnd.Value = Problem.ProblemData.Dataset.Rows;
565
566        DataAnalysisProblemData problemData = Problem.ProblemData as DataAnalysisProblemData;
567        if (problemData != null) {
568          problemData.TrainingPartitionParameter.Hidden = true;
569          problemData.TestPartitionParameter.Hidden = true;
570        }
571        ISymbolicDataAnalysisProblem symbolicProblem = Problem as ISymbolicDataAnalysisProblem;
572        if (symbolicProblem != null) {
573          symbolicProblem.FitnessCalculationPartitionParameter.Hidden = true;
574          symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
575          symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
576          symbolicProblem.ValidationPartitionParameter.Hidden = true;
577          symbolicProblem.ValidationPartition.Start = 0;
578          symbolicProblem.ValidationPartition.End = 0;
579        }
580      } else
581        SamplesEnd.Value = 0;
582    }
583
584    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
585      switch (Algorithm.ExecutionState) {
586        case ExecutionState.Prepared: OnPrepared();
587          break;
588        case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
589        case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
590        case ExecutionState.Stopped: OnStopped();
591          break;
592      }
593    }
594    #endregion
595
596    #region clonedAlgorithms events
597    private void RegisterClonedAlgorithmsEvents() {
598      clonedAlgorithms.ItemsAdded += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
599      clonedAlgorithms.ItemsRemoved += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
600      clonedAlgorithms.CollectionReset += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
601      foreach (IAlgorithm algorithm in clonedAlgorithms)
602        RegisterClonedAlgorithmEvents(algorithm);
603    }
604    private void DeregisterClonedAlgorithmsEvents() {
605      clonedAlgorithms.ItemsAdded -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
606      clonedAlgorithms.ItemsRemoved -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
607      clonedAlgorithms.CollectionReset -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
608      foreach (IAlgorithm algorithm in clonedAlgorithms)
609        DeregisterClonedAlgorithmEvents(algorithm);
610    }
611    private void ClonedAlgorithms_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
612      foreach (IAlgorithm algorithm in e.Items)
613        RegisterClonedAlgorithmEvents(algorithm);
614    }
615    private void ClonedAlgorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
616      foreach (IAlgorithm algorithm in e.Items)
617        DeregisterClonedAlgorithmEvents(algorithm);
618    }
619    private void ClonedAlgorithms_CollectionReset(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
620      foreach (IAlgorithm algorithm in e.OldItems)
621        DeregisterClonedAlgorithmEvents(algorithm);
622      foreach (IAlgorithm algorithm in e.Items)
623        RegisterClonedAlgorithmEvents(algorithm);
624    }
625    private void RegisterClonedAlgorithmEvents(IAlgorithm algorithm) {
626      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
627      algorithm.ExecutionTimeChanged += new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
628      algorithm.Started += new EventHandler(ClonedAlgorithm_Started);
629      algorithm.Paused += new EventHandler(ClonedAlgorithm_Paused);
630      algorithm.Stopped += new EventHandler(ClonedAlgorithm_Stopped);
631    }
632    private void DeregisterClonedAlgorithmEvents(IAlgorithm algorithm) {
633      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
634      algorithm.ExecutionTimeChanged -= new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
635      algorithm.Started -= new EventHandler(ClonedAlgorithm_Started);
636      algorithm.Paused -= new EventHandler(ClonedAlgorithm_Paused);
637      algorithm.Stopped -= new EventHandler(ClonedAlgorithm_Stopped);
638    }
639    private void ClonedAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
640      OnExceptionOccurred(e.Value);
641    }
642    private void ClonedAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
643      OnExecutionTimeChanged();
644    }
645
646    private readonly object locker = new object();
647    private void ClonedAlgorithm_Started(object sender, EventArgs e) {
648      lock (locker) {
649        IAlgorithm algorithm = sender as IAlgorithm;
650        if (algorithm != null && !results.ContainsKey(algorithm.Name))
651          results.Add(new Result(algorithm.Name, "Contains results for the specific fold.", algorithm.Results));
652
653        if (startPending) {
654          int startedAlgorithms = clonedAlgorithms.Count(alg => alg.ExecutionState == ExecutionState.Started);
655          if (startedAlgorithms == NumberOfWorkers.Value ||
656             clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Prepared))
657            startPending = false;
658
659          if (pausePending) PauseAllClonedAlgorithms();
660          if (stopPending) StopAllClonedAlgorithms();
661        }
662      }
663    }
664
665    private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
666      lock (locker) {
667        if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
668          OnPaused();
669      }
670    }
671
672    private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
673      lock (locker) {
674        if (!stopPending && ExecutionState == ExecutionState.Started) {
675          IAlgorithm preparedAlgorithm = clonedAlgorithms.FirstOrDefault(alg => alg.ExecutionState == ExecutionState.Prepared ||
676                                                                                alg.ExecutionState == ExecutionState.Paused);
677          if (preparedAlgorithm != null) preparedAlgorithm.Start();
678        }
679        if (ExecutionState != ExecutionState.Stopped) {
680          if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
681            OnStopped();
682          else if (stopPending &&
683                   clonedAlgorithms.All(
684                     alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
685            OnStopped();
686        }
687      }
688    }
689    #endregion
690    #endregion
691
692    #region event firing
693    public event EventHandler ExecutionStateChanged;
694    private void OnExecutionStateChanged() {
695      EventHandler handler = ExecutionStateChanged;
696      if (handler != null) handler(this, EventArgs.Empty);
697    }
698    public event EventHandler ExecutionTimeChanged;
699    private void OnExecutionTimeChanged() {
700      EventHandler handler = ExecutionTimeChanged;
701      if (handler != null) handler(this, EventArgs.Empty);
702    }
703    public event EventHandler Prepared;
704    private void OnPrepared() {
705      ExecutionState = ExecutionState.Prepared;
706      EventHandler handler = Prepared;
707      if (handler != null) handler(this, EventArgs.Empty);
708      OnExecutionTimeChanged();
709    }
710    public event EventHandler Started;
711    private void OnStarted() {
712      startPending = false;
713      ExecutionState = ExecutionState.Started;
714      EventHandler handler = Started;
715      if (handler != null) handler(this, EventArgs.Empty);
716    }
717    public event EventHandler Paused;
718    private void OnPaused() {
719      pausePending = false;
720      ExecutionState = ExecutionState.Paused;
721      EventHandler handler = Paused;
722      if (handler != null) handler(this, EventArgs.Empty);
723    }
724    public event EventHandler Stopped;
725    private void OnStopped() {
726      stopPending = false;
727      Dictionary<string, IItem> collectedResults = new Dictionary<string, IItem>();
728      AggregateResultValues(collectedResults);
729      results.AddRange(collectedResults.Select(x => new Result(x.Key, x.Value)).Cast<IResult>().ToArray());
730      runsCounter++;
731      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
732      ExecutionState = ExecutionState.Stopped;
733      EventHandler handler = Stopped;
734      if (handler != null) handler(this, EventArgs.Empty);
735    }
736    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
737    private void OnExceptionOccurred(Exception exception) {
738      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
739      if (handler != null) handler(this, new EventArgs<Exception>(exception));
740    }
741    public event EventHandler StoreAlgorithmInEachRunChanged;
742    private void OnStoreAlgorithmInEachRunChanged() {
743      EventHandler handler = StoreAlgorithmInEachRunChanged;
744      if (handler != null) handler(this, EventArgs.Empty);
745    }
746    #endregion
747  }
748}
Note: See TracBrowser for help on using the repository browser.