Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs @ 5594

Last change on this file since 5594 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 25.7 KB
RevLine 
[4472]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4472]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;
[4561]23using System.Collections.Generic;
[4536]24using System.Drawing;
25using System.Linq;
[4472]26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  [Item("Cross Validation", "Cross Validation wrapper for data analysis algorithms.")]
36  [Creatable("Data Analysis")]
37  [StorableClass]
[4617]38  public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm, IStorableContent {
[4472]39    public CrossValidation()
40      : base() {
41      name = ItemName;
42      description = ItemDescription;
43
44      executionState = ExecutionState.Stopped;
[4542]45      runs = new RunCollection();
[4561]46      runsCounter = 0;
[4472]47
[4536]48      algorithm = null;
[4472]49      clonedAlgorithms = new ItemCollection<IAlgorithm>();
[4561]50      results = new ResultCollection();
[4472]51
[4561]52      folds = new IntValue(2);
[4542]53      numberOfWorkers = new IntValue(1);
[4472]54      samplesStart = new IntValue(0);
55      samplesEnd = new IntValue(0);
[4561]56      storeAlgorithmInEachRun = false;
[4542]57
58      RegisterEvents();
[5125]59      if (Algorithm != null) RegisterAlgorithmEvents();
[4472]60    }
61
[4617]62    public string Filename { get; set; }
63
[4542]64    #region persistence and cloning
65    [StorableConstructor]
66    private CrossValidation(bool deserializing)
67      : base(deserializing) {
68    }
69    [StorableHook(HookType.AfterDeserialization)]
70    private void AfterDeserialization() {
71      RegisterEvents();
[5125]72      if (Algorithm != null) RegisterAlgorithmEvents();
[4542]73    }
74
[4722]75    private CrossValidation(CrossValidation original, Cloner cloner)
76      : base(original, cloner) {
77      executionState = original.executionState;
78      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
79      runs = cloner.Clone(original.runs);
80      runsCounter = original.runsCounter;
81      algorithm = cloner.Clone(original.algorithm);
82      clonedAlgorithms = cloner.Clone(original.clonedAlgorithms);
[4735]83      results = cloner.Clone(original.results);
84
[4722]85      folds = cloner.Clone(original.folds);
86      numberOfWorkers = cloner.Clone(original.numberOfWorkers);
87      samplesStart = cloner.Clone(original.samplesStart);
88      samplesEnd = cloner.Clone(original.samplesEnd);
89      RegisterEvents();
[5125]90      if (Algorithm != null) RegisterAlgorithmEvents();
[4722]91    }
[4542]92    public override IDeepCloneable Clone(Cloner cloner) {
[4722]93      return new CrossValidation(this, cloner);
[4542]94    }
[4722]95
[4542]96    #endregion
97
[4472]98    #region properties
[4542]99    [Storable]
[4536]100    private IAlgorithm algorithm;
101    public IAlgorithm Algorithm {
102      get { return algorithm; }
[4472]103      set {
[4542]104        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
105          throw new InvalidOperationException("Changing the algorithm is only allowed if the CrossValidation is stopped or prepared.");
[4536]106        if (algorithm != value) {
[4472]107          if (value != null && value.Problem != null && !(value.Problem is IDataAnalysisProblem))
108            throw new ArgumentException("Only algorithms with a DataAnalysisProblem could be used for the cross validation.");
[4536]109          if (algorithm != null) DeregisterAlgorithmEvents();
110          algorithm = value;
[4561]111          Parameters.Clear();
[4542]112
113          if (algorithm != null) {
[4563]114            algorithm.StoreAlgorithmInEachRun = false;
[4542]115            RegisterAlgorithmEvents();
116            algorithm.Prepare(true);
[4561]117            Parameters.AddRange(algorithm.Parameters);
[4542]118          }
[4536]119          OnAlgorithmChanged();
[4561]120          if (algorithm != null) OnProblemChanged();
[4542]121          Prepare();
[4472]122        }
123      }
124    }
[4542]125
[4561]126
[4542]127    [Storable]
[4563]128    private ISingleObjectiveDataAnalysisProblem problem;
129    public ISingleObjectiveDataAnalysisProblem Problem {
[4472]130      get {
[4536]131        if (algorithm == null)
[4472]132          return null;
[4563]133        return (ISingleObjectiveDataAnalysisProblem)algorithm.Problem;
[4472]134      }
[4536]135      set {
[4542]136        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
137          throw new InvalidOperationException("Changing the problem is only allowed if the CrossValidation is stopped or prepared.");
[4536]138        if (algorithm == null) throw new ArgumentNullException("Could not set a problem before an algorithm was set.");
139        algorithm.Problem = value;
[4563]140        problem = value;
[4536]141      }
[4472]142    }
[4536]143
[4561]144    IProblem IAlgorithm.Problem {
145      get { return Problem; }
146      set {
147        if (value != null && !ProblemType.IsInstanceOfType(value))
148          throw new ArgumentException("Only DataAnalysisProblems could be used for the cross validation.");
[4563]149        Problem = (ISingleObjectiveDataAnalysisProblem)value;
[4561]150      }
151    }
152    public Type ProblemType {
[4563]153      get { return typeof(ISingleObjectiveDataAnalysisProblem); }
[4561]154    }
155
[4542]156    [Storable]
[4472]157    private ItemCollection<IAlgorithm> clonedAlgorithms;
158
[5419]159    public IEnumerable<IOptimizer> NestedOptimizers {
[5430]160      get {
161        if (Algorithm == null) yield break;
162        yield return Algorithm;
163      }
[5419]164    }
165
[4542]166    [Storable]
[4561]167    private ResultCollection results;
168    public ResultCollection Results {
169      get { return results; }
170    }
171
172    [Storable]
[4472]173    private IntValue folds;
174    public IntValue Folds {
175      get { return folds; }
176    }
[4542]177    [Storable]
[4472]178    private IntValue samplesStart;
179    public IntValue SamplesStart {
[4536]180      get { return samplesStart; }
[4472]181    }
[4542]182    [Storable]
[4472]183    private IntValue samplesEnd;
184    public IntValue SamplesEnd {
[4536]185      get { return samplesEnd; }
[4472]186    }
[4542]187    [Storable]
[4472]188    private IntValue numberOfWorkers;
189    public IntValue NumberOfWorkers {
190      get { return numberOfWorkers; }
191    }
192
[4542]193    [Storable]
[4561]194    private bool storeAlgorithmInEachRun;
195    public bool StoreAlgorithmInEachRun {
196      get { return storeAlgorithmInEachRun; }
197      set {
198        if (storeAlgorithmInEachRun != value) {
199          storeAlgorithmInEachRun = value;
200          OnStoreAlgorithmInEachRunChanged();
201        }
202      }
203    }
204
205    [Storable]
206    private int runsCounter;
207    [Storable]
[4472]208    private RunCollection runs;
209    public RunCollection Runs {
210      get { return runs; }
211    }
[4561]212
[4542]213    [Storable]
[4472]214    private ExecutionState executionState;
215    public ExecutionState ExecutionState {
216      get { return executionState; }
217      private set {
218        if (executionState != value) {
219          executionState = value;
220          OnExecutionStateChanged();
221          OnItemImageChanged();
222        }
223      }
224    }
[4536]225    public override Image ItemImage {
226      get {
[5287]227        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
228        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
229        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
230        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
231        else return HeuristicLab.Common.Resources.VSImageLibrary.Event;
[4536]232      }
233    }
234
[4472]235    public TimeSpan ExecutionTime {
[4536]236      get {
[4567]237        if (ExecutionState != ExecutionState.Prepared)
238          return TimeSpan.FromMilliseconds(clonedAlgorithms.Select(x => x.ExecutionTime.TotalMilliseconds).Sum());
239        return TimeSpan.Zero;
[4536]240      }
[4472]241    }
242    #endregion
243
244    public void Prepare() {
[4563]245      if (ExecutionState == ExecutionState.Started)
[4542]246        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
[4567]247      results.Clear();
[4536]248      clonedAlgorithms.Clear();
[4542]249      if (Algorithm != null) {
250        Algorithm.Prepare();
251        if (Algorithm.ExecutionState == ExecutionState.Prepared) OnPrepared();
252      }
[4472]253    }
254    public void Prepare(bool clearRuns) {
255      if (clearRuns) runs.Clear();
256      Prepare();
257    }
[4542]258
259    private bool startPending;
[4472]260    public void Start() {
[4542]261      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
262        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
263
264      if (Algorithm != null && !startPending) {
265        startPending = true;
266        //create cloned algorithms
267        if (clonedAlgorithms.Count == 0) {
[4561]268          int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
[4542]269          for (int i = 0; i < Folds.Value; i++) {
270            IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
271            clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
[4561]272            IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
273            problem.DataAnalysisProblemData.TestSamplesEnd.Value = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
274            problem.DataAnalysisProblemData.TestSamplesStart.Value = (i * testSamplesCount) + SamplesStart.Value;
[4542]275            clonedAlgorithms.Add(clonedAlgorithm);
276          }
277        }
278
279        //start prepared or paused cloned algorithms
280        int startedAlgorithms = 0;
281        foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
282          if (startedAlgorithms < NumberOfWorkers.Value) {
283            if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
284                clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
285              clonedAlgorithm.Start();
286              startedAlgorithms++;
287            }
288          }
289        }
290        OnStarted();
[4536]291      }
[4472]292    }
[4542]293
294    private bool pausePending;
[4472]295    public void Pause() {
[4542]296      if (ExecutionState != ExecutionState.Started)
297        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
298      if (!pausePending) {
299        pausePending = true;
300        if (!startPending) PauseAllClonedAlgorithms();
301      }
[4472]302    }
[4542]303    private void PauseAllClonedAlgorithms() {
[5420]304      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
[4542]305        if (clonedAlgorithm.ExecutionState == ExecutionState.Started)
306          clonedAlgorithm.Pause();
307      }
308    }
309
310    private bool stopPending;
[4472]311    public void Stop() {
[4542]312      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
313        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".",
314                                                          ExecutionState));
315      if (!stopPending) {
316        stopPending = true;
317        if (!startPending) StopAllClonedAlgorithms();
318      }
[4472]319    }
[4542]320    private void StopAllClonedAlgorithms() {
[5420]321      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
[4542]322        if (clonedAlgorithm.ExecutionState == ExecutionState.Started ||
323            clonedAlgorithm.ExecutionState == ExecutionState.Paused)
324          clonedAlgorithm.Stop();
325      }
326    }
[4472]327
[4561]328    #region collect parameters and results
329    public override void CollectParameterValues(IDictionary<string, IItem> values) {
330      values.Add("Algorithm Name", new StringValue(Name));
331      values.Add("Algorithm Type", new StringValue(GetType().GetPrettyName()));
332      values.Add("Folds", new IntValue(Folds.Value));
333
334      if (algorithm != null) {
335        values.Add("CrossValidation Algorithm Name", new StringValue(Algorithm.Name));
336        values.Add("CrossValidation Algorithm Type", new StringValue(Algorithm.GetType().GetPrettyName()));
337        base.CollectParameterValues(values);
338      }
339      if (Problem != null) {
340        values.Add("Problem Name", new StringValue(Problem.Name));
341        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
342        Problem.CollectParameterValues(values);
343      }
344    }
345
346    public void CollectResultValues(IDictionary<string, IItem> results) {
347      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
[5420]348      IEnumerable<IRun> runs = clonedAlgorithms.Select(alg => alg.Runs.FirstOrDefault()).Where(run => run != null);
[4561]349      IEnumerable<KeyValuePair<string, IItem>> resultCollections = runs.Where(x => x != null).SelectMany(x => x.Results).ToList();
350
351      foreach (IResult result in ExtractAndAggregateResults<IntValue>(resultCollections))
352        results.Add(result.Name, result.Value);
353      foreach (IResult result in ExtractAndAggregateResults<DoubleValue>(resultCollections))
354        results.Add(result.Name, result.Value);
355      foreach (IResult result in ExtractAndAggregateResults<PercentValue>(resultCollections))
356        results.Add(result.Name, result.Value);
357
[4567]358      results.Add("Execution Time", new TimeSpanValue(this.ExecutionTime));
[4561]359      results.Add("CrossValidation Folds", new RunCollection(runs));
360    }
361
362    private static IEnumerable<IResult> ExtractAndAggregateResults<T>(IEnumerable<KeyValuePair<string, IItem>> results)
363  where T : class, IItem, new() {
364      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
365      foreach (var resultValue in results.Where(r => r.Value.GetType() == typeof(T))) {
366        if (!resultValues.ContainsKey(resultValue.Key))
367          resultValues[resultValue.Key] = new List<double>();
368        resultValues[resultValue.Key].Add(ConvertToDouble(resultValue.Value));
369      }
370
371      DoubleValue doubleValue;
372      if (typeof(T) == typeof(PercentValue))
373        doubleValue = new PercentValue();
374      else if (typeof(T) == typeof(DoubleValue))
375        doubleValue = new DoubleValue();
376      else if (typeof(T) == typeof(IntValue))
377        doubleValue = new DoubleValue();
378      else
379        throw new NotSupportedException();
380
381      List<IResult> aggregatedResults = new List<IResult>();
382      foreach (KeyValuePair<string, List<double>> resultValue in resultValues) {
383        doubleValue.Value = resultValue.Value.Average();
384        aggregatedResults.Add(new Result(resultValue.Key, (IItem)doubleValue.Clone()));
385        doubleValue.Value = resultValue.Value.StandardDeviation();
386        aggregatedResults.Add(new Result(resultValue.Key + " StdDev", (IItem)doubleValue.Clone()));
387      }
388      return aggregatedResults;
389    }
390
391    private static double ConvertToDouble(IItem item) {
392      if (item is DoubleValue) return ((DoubleValue)item).Value;
393      else if (item is IntValue) return ((IntValue)item).Value;
394      else throw new NotSupportedException("Could not convert any item type to double");
395    }
396    #endregion
397
[4472]398    #region events
[4542]399    private void RegisterEvents() {
400      Folds.ValueChanged += new EventHandler(Folds_ValueChanged);
[4561]401      SamplesStart.ValueChanged += new EventHandler(SamplesStart_ValueChanged);
402      SamplesEnd.ValueChanged += new EventHandler(SamplesEnd_ValueChanged);
[4542]403      RegisterClonedAlgorithmsEvents();
404    }
405    private void Folds_ValueChanged(object sender, EventArgs e) {
406      if (ExecutionState != ExecutionState.Prepared)
407        throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
408    }
[4561]409    private void SamplesStart_ValueChanged(object sender, EventArgs e) {
410      if (Problem != null) Problem.DataAnalysisProblemData.TrainingSamplesStart.Value = SamplesStart.Value;
[4542]411    }
[4561]412    private void SamplesEnd_ValueChanged(object sender, EventArgs e) {
413      if (Problem != null) Problem.DataAnalysisProblemData.TrainingSamplesEnd.Value = SamplesEnd.Value;
414    }
[4542]415
416    #region template algorithms events
[4536]417    public event EventHandler AlgorithmChanged;
418    private void OnAlgorithmChanged() {
419      EventHandler handler = AlgorithmChanged;
[4472]420      if (handler != null) handler(this, EventArgs.Empty);
[4536]421      OnProblemChanged();
[4542]422      if (Problem == null) ExecutionState = ExecutionState.Stopped;
[4472]423    }
[4536]424    private void RegisterAlgorithmEvents() {
425      algorithm.ProblemChanged += new EventHandler(Algorithm_ProblemChanged);
[4542]426      algorithm.ExecutionStateChanged += new EventHandler(Algorithm_ExecutionStateChanged);
[4472]427    }
[4536]428    private void DeregisterAlgorithmEvents() {
429      algorithm.ProblemChanged -= new EventHandler(Algorithm_ProblemChanged);
[4542]430      algorithm.ExecutionStateChanged -= new EventHandler(Algorithm_ExecutionStateChanged);
[4472]431    }
[4536]432    private void Algorithm_ProblemChanged(object sender, EventArgs e) {
[4563]433      if (algorithm.Problem != null && !(algorithm.Problem is ISingleObjectiveDataAnalysisProblem)) {
434        algorithm.Problem = problem;
[4536]435        throw new ArgumentException("A cross validation algorithm can only contain DataAnalysisProblems.");
436      }
[4563]437      problem = (ISingleObjectiveDataAnalysisProblem)algorithm.Problem;
[4536]438      OnProblemChanged();
[4472]439    }
[4536]440    public event EventHandler ProblemChanged;
441    private void OnProblemChanged() {
442      EventHandler handler = ProblemChanged;
443      if (handler != null) handler(this, EventArgs.Empty);
[4561]444
445      SamplesStart.Value = 0;
446      if (Problem != null)
447        SamplesEnd.Value = Problem.DataAnalysisProblemData.Dataset.Rows;
448      else
449        SamplesEnd.Value = 0;
[4536]450    }
[4472]451
[4542]452    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
453      switch (Algorithm.ExecutionState) {
454        case ExecutionState.Prepared: OnPrepared();
455          break;
456        case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
457        case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
458        case ExecutionState.Stopped: OnStopped();
459          break;
460      }
461    }
462    #endregion
463
464    #region clonedAlgorithms events
465    private void RegisterClonedAlgorithmsEvents() {
[4472]466      clonedAlgorithms.ItemsAdded += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
467      clonedAlgorithms.ItemsRemoved += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
468      clonedAlgorithms.CollectionReset += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
[4542]469      foreach (IAlgorithm algorithm in clonedAlgorithms)
470        RegisterClonedAlgorithmEvents(algorithm);
[4472]471    }
[4561]472    private void DeregisterClonedAlgorithmsEvents() {
473      clonedAlgorithms.ItemsAdded -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
474      clonedAlgorithms.ItemsRemoved -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
475      clonedAlgorithms.CollectionReset -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
476      foreach (IAlgorithm algorithm in clonedAlgorithms)
477        DeregisterClonedAlgorithmEvents(algorithm);
478    }
[4472]479    private void ClonedAlgorithms_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
480      foreach (IAlgorithm algorithm in e.Items)
481        RegisterClonedAlgorithmEvents(algorithm);
482    }
483    private void ClonedAlgorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
484      foreach (IAlgorithm algorithm in e.Items)
485        DeregisterClonedAlgorithmEvents(algorithm);
486    }
487    private void ClonedAlgorithms_CollectionReset(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
[4542]488      foreach (IAlgorithm algorithm in e.OldItems)
489        DeregisterClonedAlgorithmEvents(algorithm);
[4472]490      foreach (IAlgorithm algorithm in e.Items)
491        RegisterClonedAlgorithmEvents(algorithm);
492    }
493    private void RegisterClonedAlgorithmEvents(IAlgorithm algorithm) {
[4542]494      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
495      algorithm.ExecutionTimeChanged += new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
496      algorithm.Started += new EventHandler(ClonedAlgorithm_Started);
497      algorithm.Paused += new EventHandler(ClonedAlgorithm_Paused);
498      algorithm.Stopped += new EventHandler(ClonedAlgorithm_Stopped);
[4472]499    }
500    private void DeregisterClonedAlgorithmEvents(IAlgorithm algorithm) {
[4542]501      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
502      algorithm.ExecutionTimeChanged -= new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
503      algorithm.Started -= new EventHandler(ClonedAlgorithm_Started);
504      algorithm.Paused -= new EventHandler(ClonedAlgorithm_Paused);
505      algorithm.Stopped -= new EventHandler(ClonedAlgorithm_Stopped);
[4472]506    }
[4542]507    private void ClonedAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
[4536]508      OnExceptionOccurred(e.Value);
509    }
[4542]510    private void ClonedAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
[4536]511      OnExecutionTimeChanged();
512    }
[4542]513
514    private readonly object locker = new object();
515    private void ClonedAlgorithm_Started(object sender, EventArgs e) {
516      lock (locker) {
[4567]517        IAlgorithm algorithm = sender as IAlgorithm;
518        if (algorithm != null && !results.ContainsKey(algorithm.Name))
519          results.Add(new Result(algorithm.Name, "Contains results for the specific fold.", algorithm.Results));
520
[4542]521        if (startPending) {
522          int startedAlgorithms = clonedAlgorithms.Count(alg => alg.ExecutionState == ExecutionState.Started);
523          if (startedAlgorithms == NumberOfWorkers.Value ||
524             clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Prepared))
525            startPending = false;
526
527          if (pausePending) PauseAllClonedAlgorithms();
528          if (stopPending) StopAllClonedAlgorithms();
529        }
530      }
[4472]531    }
[4542]532
533    private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
534      lock (locker) {
535        if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
536          OnPaused();
537      }
[4472]538    }
[4542]539
540    private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
541      lock (locker) {
542        if (!stopPending && ExecutionState == ExecutionState.Started) {
543          IAlgorithm preparedAlgorithm = clonedAlgorithms.Where(alg => alg.ExecutionState == ExecutionState.Prepared ||
544                                                                       alg.ExecutionState == ExecutionState.Paused).FirstOrDefault();
545          if (preparedAlgorithm != null) preparedAlgorithm.Start();
546        }
[4561]547        if (ExecutionState != ExecutionState.Stopped) {
548          if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
549            OnStopped();
550          else if (stopPending &&
551                   clonedAlgorithms.All(
552                     alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
553            OnStopped();
554        }
[4542]555      }
[4472]556    }
[4542]557    #endregion
558    #endregion
559
560    #region event firing
[4472]561    public event EventHandler ExecutionStateChanged;
562    private void OnExecutionStateChanged() {
563      EventHandler handler = ExecutionStateChanged;
564      if (handler != null) handler(this, EventArgs.Empty);
565    }
566    public event EventHandler ExecutionTimeChanged;
567    private void OnExecutionTimeChanged() {
568      EventHandler handler = ExecutionTimeChanged;
569      if (handler != null) handler(this, EventArgs.Empty);
570    }
571    public event EventHandler Prepared;
572    private void OnPrepared() {
573      ExecutionState = ExecutionState.Prepared;
574      EventHandler handler = Prepared;
575      if (handler != null) handler(this, EventArgs.Empty);
[4567]576      OnExecutionTimeChanged();
[4472]577    }
578    public event EventHandler Started;
579    private void OnStarted() {
[4542]580      startPending = false;
[4472]581      ExecutionState = ExecutionState.Started;
582      EventHandler handler = Started;
583      if (handler != null) handler(this, EventArgs.Empty);
584    }
585    public event EventHandler Paused;
586    private void OnPaused() {
[4542]587      pausePending = false;
[4472]588      ExecutionState = ExecutionState.Paused;
589      EventHandler handler = Paused;
590      if (handler != null) handler(this, EventArgs.Empty);
591    }
592    public event EventHandler Stopped;
593    private void OnStopped() {
[4542]594      stopPending = false;
[4567]595      Dictionary<string, IItem> collectedResults = new Dictionary<string, IItem>();
596      CollectResultValues(collectedResults);
597      results.AddRange(collectedResults.Select(x => new Result(x.Key, x.Value)).Cast<IResult>().ToArray());
[4561]598      runsCounter++;
599      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
[4472]600      ExecutionState = ExecutionState.Stopped;
601      EventHandler handler = Stopped;
602      if (handler != null) handler(this, EventArgs.Empty);
603    }
604    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
605    private void OnExceptionOccurred(Exception exception) {
606      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
607      if (handler != null) handler(this, new EventArgs<Exception>(exception));
608    }
[4561]609    public event EventHandler StoreAlgorithmInEachRunChanged;
610    private void OnStoreAlgorithmInEachRunChanged() {
611      EventHandler handler = StoreAlgorithmInEachRunChanged;
612      if (handler != null) handler(this, EventArgs.Empty);
613    }
[4472]614    #endregion
615  }
616}
Note: See TracBrowser for help on using the repository browser.