Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs @ 17175

Last change on this file since 17175 was 13656, checked in by ascheibe, 9 years ago

#2582 created branch for Hive Web Job Manager

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