Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15190 was 15190, checked in by abeham, 7 years ago

#2258: fixed starting of cloned algs

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