Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs @ 15204

Last change on this file since 15204 was 15204, checked in by jkarder, 7 years ago

#2258: worked on execution of cross-validation

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