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

Last change on this file since 15212 was 15212, checked in by jkarder, 5 years ago

#2258: worked on execution of cross-validation

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