Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs @ 4563

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

Adapted CrossValidation to use ISingleObjectiveDataAnalysisProblem (ticket #1199).

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