Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2258: refactored async methods

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