Index: branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs
===================================================================
--- branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs	(revision 4542)
+++ branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/CrossValidation.cs	(revision 4561)
@@ -21,4 +21,5 @@
 
 using System;
+using System.Collections.Generic;
 using System.Drawing;
 using System.Linq;
@@ -35,5 +36,5 @@
   [Creatable("Data Analysis")]
   [StorableClass]
-  public sealed class CrossValidation : NamedItem, IOptimizer {
+  public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm {
     public CrossValidation()
       : base() {
@@ -44,14 +45,16 @@
       executionTime = TimeSpan.Zero;
       runs = new RunCollection();
+      runsCounter = 0;
 
       algorithm = null;
       clonedAlgorithms = new ItemCollection<IAlgorithm>();
       readOnlyClonedAlgorithms = null;
-
-      folds = new IntValue(1);
+      results = new ResultCollection();
+
+      folds = new IntValue(2);
       numberOfWorkers = new IntValue(1);
       samplesStart = new IntValue(0);
       samplesEnd = new IntValue(0);
-
+      storeAlgorithmInEachRun = false;
 
       RegisterEvents();
@@ -69,12 +72,11 @@
 
     public override IDeepCloneable Clone(Cloner cloner) {
-      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
-      CrossValidation clone = new CrossValidation(false);
-      cloner.RegisterClonedObject(this, clone);
-      clone.name = name;
-      clone.description = description;
+      CrossValidation clone = (CrossValidation)base.Clone(cloner);
+      clone.DeregisterEvents();
       clone.executionState = executionState;
       clone.executionTime = executionTime;
+      clone.storeAlgorithmInEachRun = storeAlgorithmInEachRun;
       clone.runs = (RunCollection)cloner.Clone(runs);
+      clone.runsCounter = runsCounter;
       clone.algorithm = (IAlgorithm)cloner.Clone(algorithm);
       clone.clonedAlgorithms = (ItemCollection<IAlgorithm>)cloner.Clone(clonedAlgorithms);
@@ -102,14 +104,19 @@
           if (algorithm != null) DeregisterAlgorithmEvents();
           algorithm = value;
+          Parameters.Clear();
 
           if (algorithm != null) {
+            algorithm.StoreAlgorithmInEachRun = StoreAlgorithmInEachRun;
             RegisterAlgorithmEvents();
             algorithm.Prepare(true);
+            Parameters.AddRange(algorithm.Parameters);
           }
           OnAlgorithmChanged();
+          if (algorithm != null) OnProblemChanged();
           Prepare();
         }
       }
     }
+
 
     [Storable]
@@ -130,4 +137,16 @@
     }
 
+    IProblem IAlgorithm.Problem {
+      get { return Problem; }
+      set {
+        if (value != null && !ProblemType.IsInstanceOfType(value))
+          throw new ArgumentException("Only DataAnalysisProblems could be used for the cross validation.");
+        Problem = (IDataAnalysisProblem)value;
+      }
+    }
+    public Type ProblemType {
+      get { return typeof(IDataAnalysisProblem); }
+    }
+
     [Storable]
     private ItemCollection<IAlgorithm> clonedAlgorithms;
@@ -141,4 +160,10 @@
 
     [Storable]
+    private ResultCollection results;
+    public ResultCollection Results {
+      get { return results; }
+    }
+
+    [Storable]
     private IntValue folds;
     public IntValue Folds {
@@ -162,8 +187,23 @@
 
     [Storable]
+    private bool storeAlgorithmInEachRun;
+    public bool StoreAlgorithmInEachRun {
+      get { return storeAlgorithmInEachRun; }
+      set {
+        if (storeAlgorithmInEachRun != value) {
+          storeAlgorithmInEachRun = value;
+          OnStoreAlgorithmInEachRunChanged();
+        }
+      }
+    }
+
+    [Storable]
+    private int runsCounter;
+    [Storable]
     private RunCollection runs;
     public RunCollection Runs {
       get { return runs; }
     }
+
     [Storable]
     private ExecutionState executionState;
@@ -192,5 +232,5 @@
     public TimeSpan ExecutionTime {
       get {
-        if (ExecutionState != ExecutionState.Stopped)
+        if (ExecutionState != ExecutionState.Stopped && ExecutionState != ExecutionState.Prepared)
           return executionTime + TimeSpan.FromMilliseconds(clonedAlgorithms.Select(x => x.ExecutionTime.TotalMilliseconds).Sum());
         else
@@ -227,7 +267,11 @@
         //create cloned algorithms
         if (clonedAlgorithms.Count == 0) {
+          int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
           for (int i = 0; i < Folds.Value; i++) {
             IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
             clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
+            IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
+            problem.DataAnalysisProblemData.TestSamplesEnd.Value = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
+            problem.DataAnalysisProblemData.TestSamplesStart.Value = (i * testSamplesCount) + SamplesStart.Value;
             clonedAlgorithms.Add(clonedAlgorithm);
           }
@@ -283,10 +327,90 @@
     }
 
+    #region collect parameters and results
+    public override void CollectParameterValues(IDictionary<string, IItem> values) {
+      values.Add("Algorithm Name", new StringValue(Name));
+      values.Add("Algorithm Type", new StringValue(GetType().GetPrettyName()));
+      values.Add("Folds", new IntValue(Folds.Value));
+
+      if (algorithm != null) {
+        values.Add("CrossValidation Algorithm Name", new StringValue(Algorithm.Name));
+        values.Add("CrossValidation Algorithm Type", new StringValue(Algorithm.GetType().GetPrettyName()));
+        base.CollectParameterValues(values);
+      }
+      if (Problem != null) {
+        values.Add("Problem Name", new StringValue(Problem.Name));
+        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
+        Problem.CollectParameterValues(values);
+      }
+    }
+
+    public void CollectResultValues(IDictionary<string, IItem> results) {
+      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
+      IEnumerable<IRun> runs = ClonedAlgorithms.Select(alg => alg.Runs.FirstOrDefault()).Where(run => run != null);
+      IEnumerable<KeyValuePair<string, IItem>> resultCollections = runs.Where(x => x != null).SelectMany(x => x.Results).ToList();
+
+      foreach (IResult result in ExtractAndAggregateResults<IntValue>(resultCollections))
+        results.Add(result.Name, result.Value);
+      foreach (IResult result in ExtractAndAggregateResults<DoubleValue>(resultCollections))
+        results.Add(result.Name, result.Value);
+      foreach (IResult result in ExtractAndAggregateResults<PercentValue>(resultCollections))
+        results.Add(result.Name, result.Value);
+
+      results.Add("Execution Time", new TimeSpanValue(TimeSpan.FromMilliseconds(clonedAlgorithms.Select(x => x.ExecutionTime.TotalMilliseconds).Sum())));
+      results.Add("CrossValidation Folds", new RunCollection(runs));
+    }
+
+    private static IEnumerable<IResult> ExtractAndAggregateResults<T>(IEnumerable<KeyValuePair<string, IItem>> results)
+  where T : class, IItem, new() {
+      Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
+      foreach (var resultValue in results.Where(r => r.Value.GetType() == typeof(T))) {
+        if (!resultValues.ContainsKey(resultValue.Key))
+          resultValues[resultValue.Key] = new List<double>();
+        resultValues[resultValue.Key].Add(ConvertToDouble(resultValue.Value));
+      }
+
+      DoubleValue doubleValue;
+      if (typeof(T) == typeof(PercentValue))
+        doubleValue = new PercentValue();
+      else if (typeof(T) == typeof(DoubleValue))
+        doubleValue = new DoubleValue();
+      else if (typeof(T) == typeof(IntValue))
+        doubleValue = new DoubleValue();
+      else
+        throw new NotSupportedException();
+
+      List<IResult> aggregatedResults = new List<IResult>();
+      foreach (KeyValuePair<string, List<double>> resultValue in resultValues) {
+        doubleValue.Value = resultValue.Value.Average();
+        aggregatedResults.Add(new Result(resultValue.Key, (IItem)doubleValue.Clone()));
+        doubleValue.Value = resultValue.Value.StandardDeviation();
+        aggregatedResults.Add(new Result(resultValue.Key + " StdDev", (IItem)doubleValue.Clone()));
+      }
+      return aggregatedResults;
+    }
+
+    private static double ConvertToDouble(IItem item) {
+      if (item is DoubleValue) return ((DoubleValue)item).Value;
+      else if (item is IntValue) return ((IntValue)item).Value;
+      else throw new NotSupportedException("Could not convert any item type to double");
+    }
+
+    #endregion
+
     #region events
     private void RegisterEvents() {
       Folds.ValueChanged += new EventHandler(Folds_ValueChanged);
-      NumberOfWorkers.ValueChanged += new EventHandler(NumberOfWorkers_ValueChanged);
+      SamplesStart.ValueChanged += new EventHandler(SamplesStart_ValueChanged);
+      SamplesEnd.ValueChanged += new EventHandler(SamplesEnd_ValueChanged);
       RegisterClonedAlgorithmsEvents();
       RegisterRunsEvents();
+    }
+    private void DeregisterEvents() {
+      Folds.ValueChanged -= new EventHandler(Folds_ValueChanged);
+      SamplesStart.ValueChanged -= new EventHandler(SamplesStart_ValueChanged);
+      SamplesEnd.ValueChanged -= new EventHandler(SamplesEnd_ValueChanged);
+      DeregisterClonedAlgorithmsEvents();
+      DeregisterRunsEvents();
+
     }
     private void Folds_ValueChanged(object sender, EventArgs e) {
@@ -294,24 +418,9 @@
         throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
     }
-    private void NumberOfWorkers_ValueChanged(object sender, EventArgs e) {
-      if (ExecutionState == ExecutionState.Started) {
-        int workers = numberOfWorkers.Value;
-        int runningWorkers = clonedAlgorithms.Count(alg => alg.ExecutionState == ExecutionState.Started);
-
-        foreach (IAlgorithm algorithm in clonedAlgorithms) {
-          if (algorithm.ExecutionState == ExecutionState.Prepared ||
-              algorithm.ExecutionState == ExecutionState.Paused) {
-            if (runningWorkers < workers) {
-              algorithm.Start();
-              runningWorkers++;
-            }
-          } else if (algorithm.ExecutionState == ExecutionState.Started) {
-            if (runningWorkers > workers) {
-              algorithm.Pause();
-              runningWorkers--;
-            }
-          }
-        }
-      }
+    private void SamplesStart_ValueChanged(object sender, EventArgs e) {
+      if (Problem != null) Problem.DataAnalysisProblemData.TrainingSamplesStart.Value = SamplesStart.Value;
+    }
+    private void SamplesEnd_ValueChanged(object sender, EventArgs e) {
+      if (Problem != null) Problem.DataAnalysisProblemData.TrainingSamplesEnd.Value = SamplesEnd.Value;
     }
 
@@ -338,15 +447,16 @@
       }
       cachedProblem = (IDataAnalysisProblem)algorithm.Problem;
+      OnProblemChanged();
+    }
+    public event EventHandler ProblemChanged;
+    private void OnProblemChanged() {
+      EventHandler handler = ProblemChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+
       SamplesStart.Value = 0;
-      if (algorithm.Problem != null)
+      if (Problem != null)
         SamplesEnd.Value = Problem.DataAnalysisProblemData.Dataset.Rows;
       else
         SamplesEnd.Value = 0;
-      OnProblemChanged();
-    }
-    public event EventHandler ProblemChanged;
-    private void OnProblemChanged() {
-      EventHandler handler = ProblemChanged;
-      if (handler != null) handler(this, EventArgs.Empty);
     }
 
@@ -371,4 +481,11 @@
         RegisterClonedAlgorithmEvents(algorithm);
     }
+    private void DeregisterClonedAlgorithmsEvents() {
+      clonedAlgorithms.ItemsAdded -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
+      clonedAlgorithms.ItemsRemoved -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
+      clonedAlgorithms.CollectionReset -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
+      foreach (IAlgorithm algorithm in clonedAlgorithms)
+        DeregisterClonedAlgorithmEvents(algorithm);
+    }
     private void ClonedAlgorithms_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
       foreach (IAlgorithm algorithm in e.Items)
@@ -435,8 +552,12 @@
           if (preparedAlgorithm != null) preparedAlgorithm.Start();
         }
-        if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
-          OnStopped();
-        else if (stopPending && clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
-          OnStopped();
+        if (ExecutionState != ExecutionState.Stopped) {
+          if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
+            OnStopped();
+          else if (stopPending &&
+                   clonedAlgorithms.All(
+                     alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
+            OnStopped();
+        }
       }
     }
@@ -449,4 +570,9 @@
       runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
     }
+    private void DeregisterRunsEvents() {
+      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
+      runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsAdded);
+      runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
+    }
     private void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
       foreach (IRun run in e.OldItems) {
@@ -454,5 +580,5 @@
         run.Results.TryGetValue("Execution Time", out item);
         TimeSpanValue executionTime = item as TimeSpanValue;
-        if (executionTime != null) ExecutionTime -= executionTime.Value;
+        if (executionTime != null) ExecutionTime = this.executionTime - executionTime.Value;
       }
       foreach (IRun run in e.Items) {
@@ -460,6 +586,7 @@
         run.Results.TryGetValue("Execution Time", out item);
         TimeSpanValue executionTime = item as TimeSpanValue;
-        if (executionTime != null) ExecutionTime += executionTime.Value;
-      }
+        if (executionTime != null) ExecutionTime = this.executionTime + executionTime.Value;
+      }
+      runsCounter = Runs.Count;
     }
     private void Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
@@ -468,5 +595,5 @@
         run.Results.TryGetValue("Execution Time", out item);
         TimeSpanValue executionTime = item as TimeSpanValue;
-        if (executionTime != null) ExecutionTime += executionTime.Value;
+        if (executionTime != null) this.executionTime = this.executionTime + executionTime.Value;
       }
     }
@@ -476,5 +603,5 @@
         run.Results.TryGetValue("Execution Time", out item);
         TimeSpanValue executionTime = item as TimeSpanValue;
-        if (executionTime != null) ExecutionTime -= executionTime.Value;
+        if (executionTime != null) ExecutionTime = this.executionTime - executionTime.Value;
       }
     }
@@ -516,6 +643,7 @@
     private void OnStopped() {
       stopPending = false;
+      runsCounter++;
+      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
       ExecutionState = ExecutionState.Stopped;
-      //TODO create run;
       EventHandler handler = Stopped;
       if (handler != null) handler(this, EventArgs.Empty);
@@ -526,4 +654,9 @@
       if (handler != null) handler(this, new EventArgs<Exception>(exception));
     }
+    public event EventHandler StoreAlgorithmInEachRunChanged;
+    private void OnStoreAlgorithmInEachRunChanged() {
+      EventHandler handler = StoreAlgorithmInEachRunChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
     #endregion
   }
Index: branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/HeuristicLab.Algorithms.DataAnalysis-3.3.csproj
===================================================================
--- branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/HeuristicLab.Algorithms.DataAnalysis-3.3.csproj	(revision 4542)
+++ branches/HeuristicLab.Classification/HeuristicLab.Algorithms.DataAnalysis/3.3/HeuristicLab.Algorithms.DataAnalysis-3.3.csproj	(revision 4561)
@@ -148,4 +148,5 @@
     <Reference Include="System.Data" />
     <Reference Include="System.Drawing" />
+    <Reference Include="System.Windows.Forms" />
     <Reference Include="System.Xml" />
   </ItemGroup>
