Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4711 was 4617, checked in by mkommend, 14 years ago

Enabled saving of the CrossValidation (ticket #1199).

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