Index: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs
===================================================================
--- branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs	(revision 5475)
+++ branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs	(revision 5475)
@@ -0,0 +1,616 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using HeuristicLab.Collections;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Optimization;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.Problems.DataAnalysis;
+
+namespace HeuristicLab.Algorithms.DataAnalysis {
+  [Item("Cross Validation", "Cross Validation wrapper for data analysis algorithms.")]
+  [Creatable("Data Analysis")]
+  [StorableClass]
+  public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm, IStorableContent {
+    public CrossValidation()
+      : base() {
+      name = ItemName;
+      description = ItemDescription;
+
+      executionState = ExecutionState.Stopped;
+      runs = new RunCollection();
+      runsCounter = 0;
+
+      algorithm = null;
+      clonedAlgorithms = new ItemCollection<IAlgorithm>();
+      results = new ResultCollection();
+
+      folds = new IntValue(2);
+      numberOfWorkers = new IntValue(1);
+      samplesStart = new IntValue(0);
+      samplesEnd = new IntValue(0);
+      storeAlgorithmInEachRun = false;
+
+      RegisterEvents();
+      if (Algorithm != null) RegisterAlgorithmEvents();
+    }
+
+    public string Filename { get; set; }
+
+    #region persistence and cloning
+    [StorableConstructor]
+    private CrossValidation(bool deserializing)
+      : base(deserializing) {
+    }
+    [StorableHook(HookType.AfterDeserialization)]
+    private void AfterDeserialization() {
+      RegisterEvents();
+      if (Algorithm != null) RegisterAlgorithmEvents();
+    }
+
+    private CrossValidation(CrossValidation original, Cloner cloner)
+      : base(original, cloner) {
+      executionState = original.executionState;
+      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
+      runs = cloner.Clone(original.runs);
+      runsCounter = original.runsCounter;
+      algorithm = cloner.Clone(original.algorithm);
+      clonedAlgorithms = cloner.Clone(original.clonedAlgorithms);
+      results = cloner.Clone(original.results);
+
+      folds = cloner.Clone(original.folds);
+      numberOfWorkers = cloner.Clone(original.numberOfWorkers);
+      samplesStart = cloner.Clone(original.samplesStart);
+      samplesEnd = cloner.Clone(original.samplesEnd);
+      RegisterEvents();
+      if (Algorithm != null) RegisterAlgorithmEvents();
+    }
+    public override IDeepCloneable Clone(Cloner cloner) {
+      return new CrossValidation(this, cloner);
+    }
+
+    #endregion
+
+    #region properties
+    [Storable]
+    private IAlgorithm algorithm;
+    public IAlgorithm Algorithm {
+      get { return algorithm; }
+      set {
+        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
+          throw new InvalidOperationException("Changing the algorithm is only allowed if the CrossValidation is stopped or prepared.");
+        if (algorithm != value) {
+          if (value != null && value.Problem != null && !(value.Problem is IDataAnalysisProblem))
+            throw new ArgumentException("Only algorithms with a DataAnalysisProblem could be used for the cross validation.");
+          if (algorithm != null) DeregisterAlgorithmEvents();
+          algorithm = value;
+          Parameters.Clear();
+
+          if (algorithm != null) {
+            algorithm.StoreAlgorithmInEachRun = false;
+            RegisterAlgorithmEvents();
+            algorithm.Prepare(true);
+            Parameters.AddRange(algorithm.Parameters);
+          }
+          OnAlgorithmChanged();
+          if (algorithm != null) OnProblemChanged();
+          Prepare();
+        }
+      }
+    }
+
+
+    [Storable]
+    private ISingleObjectiveDataAnalysisProblem problem;
+    public ISingleObjectiveDataAnalysisProblem Problem {
+      get {
+        if (algorithm == null)
+          return null;
+        return (ISingleObjectiveDataAnalysisProblem)algorithm.Problem;
+      }
+      set {
+        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
+          throw new InvalidOperationException("Changing the problem is only allowed if the CrossValidation is stopped or prepared.");
+        if (algorithm == null) throw new ArgumentNullException("Could not set a problem before an algorithm was set.");
+        algorithm.Problem = value;
+        problem = value;
+      }
+    }
+
+    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 = (ISingleObjectiveDataAnalysisProblem)value;
+      }
+    }
+    public Type ProblemType {
+      get { return typeof(ISingleObjectiveDataAnalysisProblem); }
+    }
+
+    [Storable]
+    private ItemCollection<IAlgorithm> clonedAlgorithms;
+
+    public IEnumerable<IOptimizer> NestedOptimizers {
+      get {
+        if (Algorithm == null) yield break;
+        yield return Algorithm;
+      }
+    }
+
+    [Storable]
+    private ResultCollection results;
+    public ResultCollection Results {
+      get { return results; }
+    }
+
+    [Storable]
+    private IntValue folds;
+    public IntValue Folds {
+      get { return folds; }
+    }
+    [Storable]
+    private IntValue samplesStart;
+    public IntValue SamplesStart {
+      get { return samplesStart; }
+    }
+    [Storable]
+    private IntValue samplesEnd;
+    public IntValue SamplesEnd {
+      get { return samplesEnd; }
+    }
+    [Storable]
+    private IntValue numberOfWorkers;
+    public IntValue NumberOfWorkers {
+      get { return numberOfWorkers; }
+    }
+
+    [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;
+    public ExecutionState ExecutionState {
+      get { return executionState; }
+      private set {
+        if (executionState != value) {
+          executionState = value;
+          OnExecutionStateChanged();
+          OnItemImageChanged();
+        }
+      }
+    }
+    public override Image ItemImage {
+      get {
+        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
+        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
+        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
+        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
+        else return HeuristicLab.Common.Resources.VSImageLibrary.Event;
+      }
+    }
+
+    public TimeSpan ExecutionTime {
+      get {
+        if (ExecutionState != ExecutionState.Prepared)
+          return TimeSpan.FromMilliseconds(clonedAlgorithms.Select(x => x.ExecutionTime.TotalMilliseconds).Sum());
+        return TimeSpan.Zero;
+      }
+    }
+    #endregion
+
+    public void Prepare() {
+      if (ExecutionState == ExecutionState.Started)
+        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
+      results.Clear();
+      clonedAlgorithms.Clear();
+      if (Algorithm != null) {
+        Algorithm.Prepare();
+        if (Algorithm.ExecutionState == ExecutionState.Prepared) OnPrepared();
+      }
+    }
+    public void Prepare(bool clearRuns) {
+      if (clearRuns) runs.Clear();
+      Prepare();
+    }
+
+    private bool startPending;
+    public void Start() {
+      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
+        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
+
+      if (Algorithm != null && !startPending) {
+        startPending = true;
+        //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);
+          }
+        }
+
+        //start prepared or paused cloned algorithms
+        int startedAlgorithms = 0;
+        foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
+          if (startedAlgorithms < NumberOfWorkers.Value) {
+            if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
+                clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
+              clonedAlgorithm.Start();
+              startedAlgorithms++;
+            }
+          }
+        }
+        OnStarted();
+      }
+    }
+
+    private bool pausePending;
+    public void Pause() {
+      if (ExecutionState != ExecutionState.Started)
+        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
+      if (!pausePending) {
+        pausePending = true;
+        if (!startPending) PauseAllClonedAlgorithms();
+      }
+    }
+    private void PauseAllClonedAlgorithms() {
+      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
+        if (clonedAlgorithm.ExecutionState == ExecutionState.Started)
+          clonedAlgorithm.Pause();
+      }
+    }
+
+    private bool stopPending;
+    public void Stop() {
+      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
+        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".",
+                                                          ExecutionState));
+      if (!stopPending) {
+        stopPending = true;
+        if (!startPending) StopAllClonedAlgorithms();
+      }
+    }
+    private void StopAllClonedAlgorithms() {
+      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
+        if (clonedAlgorithm.ExecutionState == ExecutionState.Started ||
+            clonedAlgorithm.ExecutionState == ExecutionState.Paused)
+          clonedAlgorithm.Stop();
+      }
+    }
+
+    #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(this.ExecutionTime));
+      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);
+      SamplesStart.ValueChanged += new EventHandler(SamplesStart_ValueChanged);
+      SamplesEnd.ValueChanged += new EventHandler(SamplesEnd_ValueChanged);
+      RegisterClonedAlgorithmsEvents();
+    }
+    private void Folds_ValueChanged(object sender, EventArgs e) {
+      if (ExecutionState != ExecutionState.Prepared)
+        throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
+    }
+    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;
+    }
+
+    #region template algorithms events
+    public event EventHandler AlgorithmChanged;
+    private void OnAlgorithmChanged() {
+      EventHandler handler = AlgorithmChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+      OnProblemChanged();
+      if (Problem == null) ExecutionState = ExecutionState.Stopped;
+    }
+    private void RegisterAlgorithmEvents() {
+      algorithm.ProblemChanged += new EventHandler(Algorithm_ProblemChanged);
+      algorithm.ExecutionStateChanged += new EventHandler(Algorithm_ExecutionStateChanged);
+    }
+    private void DeregisterAlgorithmEvents() {
+      algorithm.ProblemChanged -= new EventHandler(Algorithm_ProblemChanged);
+      algorithm.ExecutionStateChanged -= new EventHandler(Algorithm_ExecutionStateChanged);
+    }
+    private void Algorithm_ProblemChanged(object sender, EventArgs e) {
+      if (algorithm.Problem != null && !(algorithm.Problem is ISingleObjectiveDataAnalysisProblem)) {
+        algorithm.Problem = problem;
+        throw new ArgumentException("A cross validation algorithm can only contain DataAnalysisProblems.");
+      }
+      problem = (ISingleObjectiveDataAnalysisProblem)algorithm.Problem;
+      OnProblemChanged();
+    }
+    public event EventHandler ProblemChanged;
+    private void OnProblemChanged() {
+      EventHandler handler = ProblemChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+
+      SamplesStart.Value = 0;
+      if (Problem != null)
+        SamplesEnd.Value = Problem.DataAnalysisProblemData.Dataset.Rows;
+      else
+        SamplesEnd.Value = 0;
+    }
+
+    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
+      switch (Algorithm.ExecutionState) {
+        case ExecutionState.Prepared: OnPrepared();
+          break;
+        case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
+        case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
+        case ExecutionState.Stopped: OnStopped();
+          break;
+      }
+    }
+    #endregion
+
+    #region clonedAlgorithms events
+    private void RegisterClonedAlgorithmsEvents() {
+      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)
+        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)
+        RegisterClonedAlgorithmEvents(algorithm);
+    }
+    private void ClonedAlgorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
+      foreach (IAlgorithm algorithm in e.Items)
+        DeregisterClonedAlgorithmEvents(algorithm);
+    }
+    private void ClonedAlgorithms_CollectionReset(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
+      foreach (IAlgorithm algorithm in e.OldItems)
+        DeregisterClonedAlgorithmEvents(algorithm);
+      foreach (IAlgorithm algorithm in e.Items)
+        RegisterClonedAlgorithmEvents(algorithm);
+    }
+    private void RegisterClonedAlgorithmEvents(IAlgorithm algorithm) {
+      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
+      algorithm.ExecutionTimeChanged += new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
+      algorithm.Started += new EventHandler(ClonedAlgorithm_Started);
+      algorithm.Paused += new EventHandler(ClonedAlgorithm_Paused);
+      algorithm.Stopped += new EventHandler(ClonedAlgorithm_Stopped);
+    }
+    private void DeregisterClonedAlgorithmEvents(IAlgorithm algorithm) {
+      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
+      algorithm.ExecutionTimeChanged -= new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
+      algorithm.Started -= new EventHandler(ClonedAlgorithm_Started);
+      algorithm.Paused -= new EventHandler(ClonedAlgorithm_Paused);
+      algorithm.Stopped -= new EventHandler(ClonedAlgorithm_Stopped);
+    }
+    private void ClonedAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
+      OnExceptionOccurred(e.Value);
+    }
+    private void ClonedAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
+      OnExecutionTimeChanged();
+    }
+
+    private readonly object locker = new object();
+    private void ClonedAlgorithm_Started(object sender, EventArgs e) {
+      lock (locker) {
+        IAlgorithm algorithm = sender as IAlgorithm;
+        if (algorithm != null && !results.ContainsKey(algorithm.Name))
+          results.Add(new Result(algorithm.Name, "Contains results for the specific fold.", algorithm.Results));
+
+        if (startPending) {
+          int startedAlgorithms = clonedAlgorithms.Count(alg => alg.ExecutionState == ExecutionState.Started);
+          if (startedAlgorithms == NumberOfWorkers.Value ||
+             clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Prepared))
+            startPending = false;
+
+          if (pausePending) PauseAllClonedAlgorithms();
+          if (stopPending) StopAllClonedAlgorithms();
+        }
+      }
+    }
+
+    private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
+      lock (locker) {
+        if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
+          OnPaused();
+      }
+    }
+
+    private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
+      lock (locker) {
+        if (!stopPending && ExecutionState == ExecutionState.Started) {
+          IAlgorithm preparedAlgorithm = clonedAlgorithms.Where(alg => alg.ExecutionState == ExecutionState.Prepared ||
+                                                                       alg.ExecutionState == ExecutionState.Paused).FirstOrDefault();
+          if (preparedAlgorithm != null) preparedAlgorithm.Start();
+        }
+        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();
+        }
+      }
+    }
+    #endregion
+    #endregion
+
+    #region event firing
+    public event EventHandler ExecutionStateChanged;
+    private void OnExecutionStateChanged() {
+      EventHandler handler = ExecutionStateChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
+    public event EventHandler ExecutionTimeChanged;
+    private void OnExecutionTimeChanged() {
+      EventHandler handler = ExecutionTimeChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
+    public event EventHandler Prepared;
+    private void OnPrepared() {
+      ExecutionState = ExecutionState.Prepared;
+      EventHandler handler = Prepared;
+      if (handler != null) handler(this, EventArgs.Empty);
+      OnExecutionTimeChanged();
+    }
+    public event EventHandler Started;
+    private void OnStarted() {
+      startPending = false;
+      ExecutionState = ExecutionState.Started;
+      EventHandler handler = Started;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
+    public event EventHandler Paused;
+    private void OnPaused() {
+      pausePending = false;
+      ExecutionState = ExecutionState.Paused;
+      EventHandler handler = Paused;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
+    public event EventHandler Stopped;
+    private void OnStopped() {
+      stopPending = false;
+      Dictionary<string, IItem> collectedResults = new Dictionary<string, IItem>();
+      CollectResultValues(collectedResults);
+      results.AddRange(collectedResults.Select(x => new Result(x.Key, x.Value)).Cast<IResult>().ToArray());
+      runsCounter++;
+      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
+      ExecutionState = ExecutionState.Stopped;
+      EventHandler handler = Stopped;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
+    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
+    private void OnExceptionOccurred(Exception exception) {
+      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
+      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/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/HeuristicLab.Algorithms.DataAnalysis-3.4.csproj
===================================================================
--- branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/HeuristicLab.Algorithms.DataAnalysis-3.4.csproj	(revision 5475)
+++ branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/HeuristicLab.Algorithms.DataAnalysis-3.4.csproj	(revision 5475)
@@ -0,0 +1,207 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProductVersion>9.0.30729</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{A8D5676D-9662-437A-B44D-ECB4046CDE12}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.Algorithms.DataAnalysis</RootNamespace>
+    <AssemblyName>HeuristicLab.Algorithms.DataAnalysis-3.4</AssemblyName>
+    <SignAssembly>true</SignAssembly>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+    <FileUpgradeFlags>
+    </FileUpgradeFlags>
+    <OldToolsVersion>3.5</OldToolsVersion>
+    <UpgradeBackupLocation>
+    </UpgradeBackupLocation>
+    <StartupObject>
+    </StartupObject>
+    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+    <TargetFrameworkProfile></TargetFrameworkProfile>
+    <PublishUrl>publish\</PublishUrl>
+    <Install>true</Install>
+    <InstallFrom>Disk</InstallFrom>
+    <UpdateEnabled>false</UpdateEnabled>
+    <UpdateMode>Foreground</UpdateMode>
+    <UpdateInterval>7</UpdateInterval>
+    <UpdateIntervalUnits>Days</UpdateIntervalUnits>
+    <UpdatePeriodically>false</UpdatePeriodically>
+    <UpdateRequired>false</UpdateRequired>
+    <MapFileExtensions>true</MapFileExtensions>
+    <ApplicationRevision>0</ApplicationRevision>
+    <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
+    <IsWebBootstrapper>false</IsWebBootstrapper>
+    <UseApplicationTrust>false</UseApplicationTrust>
+    <BootstrapperEnabled>true</BootstrapperEnabled>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Release\HeuristicLab.Algorithms.DataAnalysis-3.4.xml</DocumentationFile>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>bin\x86\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>bin\x86\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <DocumentationFile>bin\x86\Release\HeuristicLab.Algorithms.DataAnalysis-3.4.xml</DocumentationFile>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>bin\x64\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>bin\x64\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <DocumentationFile>bin\x64\Release\HeuristicLab.Algorithms.DataAnalysis-3.3.xml</DocumentationFile>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Data" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="CrossValidation.cs" />
+    <Compile Include="SupportVectorMachine.cs" />
+    <Compile Include="HeuristicLabAlgorithmsDataAnalysisPlugin.cs" />
+    <Compile Include="LinearRegression.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\HeuristicLab.Collections\3.3\HeuristicLab.Collections-3.3.csproj">
+      <Project>{958B43BC-CC5C-4FA2-8628-2B3B01D890B6}</Project>
+      <Name>HeuristicLab.Collections-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Common.Resources\3.3\HeuristicLab.Common.Resources-3.3.csproj">
+      <Project>{0E27A536-1C4A-4624-A65E-DC4F4F23E3E1}</Project>
+      <Name>HeuristicLab.Common.Resources-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Common\3.3\HeuristicLab.Common-3.3.csproj">
+      <Project>{A9AD58B9-3EF9-4CC1-97E5-8D909039FF5C}</Project>
+      <Name>HeuristicLab.Common-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Core\3.3\HeuristicLab.Core-3.3.csproj">
+      <Project>{C36BD924-A541-4A00-AFA8-41701378DDC5}</Project>
+      <Name>HeuristicLab.Core-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Data\3.3\HeuristicLab.Data-3.3.csproj">
+      <Project>{BBAB9DF5-5EF3-4BA8-ADE9-B36E82114937}</Project>
+      <Name>HeuristicLab.Data-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding\3.4\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj">
+      <Project>{125D3006-67F5-48CB-913E-73C0548F17FA}</Project>
+      <Name>HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Operators\3.3\HeuristicLab.Operators-3.3.csproj">
+      <Project>{23DA7FF4-D5B8-41B6-AA96-F0561D24F3EE}</Project>
+      <Name>HeuristicLab.Operators-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Optimization\3.3\HeuristicLab.Optimization-3.3.csproj">
+      <Project>{14AB8D24-25BC-400C-A846-4627AA945192}</Project>
+      <Name>HeuristicLab.Optimization-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Parameters\3.3\HeuristicLab.Parameters-3.3.csproj">
+      <Project>{56F9106A-079F-4C61-92F6-86A84C2D84B7}</Project>
+      <Name>HeuristicLab.Parameters-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Persistence\3.3\HeuristicLab.Persistence-3.3.csproj">
+      <Project>{102BC7D3-0EF9-439C-8F6D-96FF0FDB8E1B}</Project>
+      <Name>HeuristicLab.Persistence-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.PluginInfrastructure\3.3\HeuristicLab.PluginInfrastructure-3.3.csproj">
+      <Project>{94186A6A-5176-4402-AE83-886557B53CCA}</Project>
+      <Name>HeuristicLab.PluginInfrastructure-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Problems.DataAnalysis.Regression\3.4\HeuristicLab.Problems.DataAnalysis.Regression-3.4.csproj">
+      <Project>{BDF86B1D-630E-4CE2-8A49-8C90B1BDE4C9}</Project>
+      <Name>HeuristicLab.Problems.DataAnalysis.Regression-3.3</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Problems.DataAnalysis\3.4\HeuristicLab.Problems.DataAnalysis-3.4.csproj">
+      <Project>{70DFD984-B1D9-46FE-8EB7-4DE92D71A9FC}</Project>
+      <Name>HeuristicLab.Problems.DataAnalysis-3.3</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+    <None Include="HeuristicLabAlgorithmsDataAnalysisPlugin.cs.frame" />
+    <None Include="Properties\AssemblyInfo.frame" />
+  </ItemGroup>
+  <ItemGroup>
+    <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
+      <Visible>False</Visible>
+      <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
+      <Install>false</Install>
+    </BootstrapperPackage>
+    <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
+      <Visible>False</Visible>
+      <ProductName>.NET Framework 3.5 SP1</ProductName>
+      <Install>true</Install>
+    </BootstrapperPackage>
+    <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
+      <Visible>False</Visible>
+      <ProductName>Windows Installer 3.1</ProductName>
+      <Install>true</Install>
+    </BootstrapperPackage>
+  </ItemGroup>
+  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd
+SubWCRev "%25ProjectDir%25\" "%25ProjectDir%25\HeuristicLabAlgorithmsDataAnalysisPlugin.cs.frame" "%25ProjectDir%25\HeuristicLabAlgorithmsDataAnalysisPlugin.cs"</PreBuildEvent>
+  </PropertyGroup>
+</Project>
Index: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/HeuristicLabAlgorithmsDataAnalysisPlugin.cs.frame
===================================================================
--- branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/HeuristicLabAlgorithmsDataAnalysisPlugin.cs.frame	(revision 5475)
+++ branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/HeuristicLabAlgorithmsDataAnalysisPlugin.cs.frame	(revision 5475)
@@ -0,0 +1,44 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Algorithms.DataAnalysis {
+  /// <summary>
+  /// Plugin class for HeuristicLab.Algorithms.DataAnalysis plugin.
+  /// </summary>
+  [Plugin("HeuristicLab.Algorithms.DataAnalysis", "3.4.0.$WCREV$")]
+  [PluginFile("HeuristicLab.Algorithms.DataAnalysis-3.4.dll", PluginFileType.Assembly)]
+  [PluginDependency("HeuristicLab.Collections", "3.3")]
+  [PluginDependency("HeuristicLab.Common", "3.3")]
+  [PluginDependency("HeuristicLab.Common.Resources", "3.3")]
+  [PluginDependency("HeuristicLab.Core", "3.3")]
+  [PluginDependency("HeuristicLab.Data", "3.3")]
+  [PluginDependency("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding", "3.4")]
+  [PluginDependency("HeuristicLab.Operators", "3.3")]
+  [PluginDependency("HeuristicLab.Optimization", "3.3")]
+  [PluginDependency("HeuristicLab.Parameters", "3.3")]
+  [PluginDependency("HeuristicLab.Persistence", "3.3")]
+  [PluginDependency("HeuristicLab.Problems.DataAnalysis", "3.4")]
+  [PluginDependency("HeuristicLab.Problems.DataAnalysis.Regression", "3.4")]
+  public class HeuristicLabAlgorithmsDataAnalysisPlugin : PluginBase {
+  }
+}
Index: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/LinearRegression.cs
===================================================================
--- branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/LinearRegression.cs	(revision 5475)
+++ branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/LinearRegression.cs	(revision 5475)
@@ -0,0 +1,185 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.Problems.DataAnalysis;
+using HeuristicLab.Problems.DataAnalysis.Evaluators;
+using HeuristicLab.Problems.DataAnalysis.Regression.LinearRegression;
+using HeuristicLab.Problems.DataAnalysis.Regression.Symbolic;
+using HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Analyzers;
+using HeuristicLab.Problems.DataAnalysis.Symbolic;
+
+namespace HeuristicLab.Algorithms.DataAnalysis {
+  /// <summary>
+  /// Linear regression data analysis algorithm.
+  /// </summary>
+  [Item("Linear Regression", "Linear regression data analysis algorithm.")]
+  [Creatable("Data Analysis")]
+  [StorableClass]
+  public sealed class LinearRegression : EngineAlgorithm, IStorableContent {
+    private const string TrainingSamplesStartParameterName = "Training start";
+    private const string TrainingSamplesEndParameterName = "Training end";
+    private const string LinearRegressionModelParameterName = "LinearRegressionModel";
+    private const string ModelInterpreterParameterName = "Model interpreter";
+
+    public string Filename { get; set; }
+
+    #region Problem Properties
+    public override Type ProblemType {
+      get { return typeof(DataAnalysisProblem); }
+    }
+    public new DataAnalysisProblem Problem {
+      get { return (DataAnalysisProblem)base.Problem; }
+      set { base.Problem = value; }
+    }
+    #endregion
+
+    #region parameter properties
+    public IValueParameter<IntValue> TrainingSamplesStartParameter {
+      get { return (IValueParameter<IntValue>)Parameters[TrainingSamplesStartParameterName]; }
+    }
+    public IValueParameter<IntValue> TrainingSamplesEndParameter {
+      get { return (IValueParameter<IntValue>)Parameters[TrainingSamplesEndParameterName]; }
+    }
+    public IValueParameter<ISymbolicExpressionTreeInterpreter> ModelInterpreterParameter {
+      get { return (IValueParameter<ISymbolicExpressionTreeInterpreter>)Parameters[ModelInterpreterParameterName]; }
+    }
+    #endregion
+
+    [Storable]
+    private LinearRegressionSolutionCreator solutionCreator;
+    [Storable]
+    private SimpleSymbolicRegressionEvaluator evaluator;
+    [Storable]
+    private SimpleMSEEvaluator mseEvaluator;
+    [Storable]
+    private BestSymbolicRegressionSolutionAnalyzer analyzer;
+    public LinearRegression()
+      : base() {
+      Parameters.Add(new ValueParameter<IntValue>(TrainingSamplesStartParameterName, "The first index of the data set partition to use for training."));
+      Parameters.Add(new ValueParameter<IntValue>(TrainingSamplesEndParameterName, "The last index of the data set partition to use for training."));
+      Parameters.Add(new ValueParameter<ISymbolicExpressionTreeInterpreter>(ModelInterpreterParameterName, "The interpreter to use for evaluation of the model.", new SimpleArithmeticExpressionInterpreter()));
+
+      solutionCreator = new LinearRegressionSolutionCreator();
+      evaluator = new SimpleSymbolicRegressionEvaluator();
+      mseEvaluator = new SimpleMSEEvaluator();
+      analyzer = new BestSymbolicRegressionSolutionAnalyzer();
+
+      OperatorGraph.InitialOperator = solutionCreator;
+      solutionCreator.Successor = evaluator;
+      evaluator.Successor = mseEvaluator;
+      mseEvaluator.Successor = analyzer;
+
+      Initialize();
+    }
+    [StorableConstructor]
+    private LinearRegression(bool deserializing) : base(deserializing) { }
+    [StorableHook(HookType.AfterDeserialization)]
+    private void AfterDeserialization() {
+      Initialize();
+    }
+
+    private LinearRegression(LinearRegression original, Cloner cloner)
+      : base(original, cloner) {
+      solutionCreator = cloner.Clone(original.solutionCreator);
+      evaluator = cloner.Clone(original.evaluator);
+      mseEvaluator = cloner.Clone(original.mseEvaluator);
+      analyzer = cloner.Clone(original.analyzer);
+      Initialize();
+    }
+    public override IDeepCloneable Clone(Cloner cloner) {
+      return new LinearRegression(this, cloner);
+    }
+
+    public override void Prepare() {
+      if (Problem != null) base.Prepare();
+    }
+
+    protected override void Problem_Reset(object sender, EventArgs e) {
+      UpdateAlgorithmParameterValues();
+      base.Problem_Reset(sender, e);
+    }
+
+    #region Events
+    protected override void OnProblemChanged() {
+      solutionCreator.DataAnalysisProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+      evaluator.RegressionProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+      analyzer.ProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+      UpdateAlgorithmParameterValues();
+      Problem.Reset += new EventHandler(Problem_Reset);
+      base.OnProblemChanged();
+    }
+
+
+    #endregion
+
+    #region Helpers
+    private void Initialize() {
+      solutionCreator.SamplesStartParameter.ActualName = TrainingSamplesStartParameter.Name;
+      solutionCreator.SamplesEndParameter.ActualName = TrainingSamplesEndParameter.Name;
+      solutionCreator.SymbolicExpressionTreeParameter.ActualName = LinearRegressionModelParameterName;
+
+      evaluator.SymbolicExpressionTreeParameter.ActualName = solutionCreator.SymbolicExpressionTreeParameter.ActualName;
+      evaluator.SymbolicExpressionTreeInterpreterParameter.ActualName = ModelInterpreterParameter.Name;
+      evaluator.ValuesParameter.ActualName = "Training values";
+      evaluator.SamplesStartParameter.ActualName = TrainingSamplesStartParameterName;
+      evaluator.SamplesEndParameter.ActualName = TrainingSamplesEndParameterName;
+
+      mseEvaluator.ValuesParameter.ActualName = "Training values";
+      mseEvaluator.MeanSquaredErrorParameter.ActualName = "Training MSE";
+
+      analyzer.SymbolicExpressionTreeParameter.ActualName = solutionCreator.SymbolicExpressionTreeParameter.ActualName;
+      analyzer.SymbolicExpressionTreeParameter.Depth = 0;
+      analyzer.QualityParameter.ActualName = mseEvaluator.MeanSquaredErrorParameter.ActualName;
+      analyzer.QualityParameter.Depth = 0;
+      analyzer.SymbolicExpressionTreeInterpreterParameter.ActualName = ModelInterpreterParameter.Name;
+
+      if (Problem != null) {
+        solutionCreator.DataAnalysisProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+        evaluator.RegressionProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+        analyzer.ProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+        Problem.Reset += new EventHandler(Problem_Reset);
+      }
+    }
+
+    private void UpdateAlgorithmParameterValues() {
+      TrainingSamplesStartParameter.ActualValue = Problem.DataAnalysisProblemData.TrainingSamplesStart;
+      TrainingSamplesEndParameter.ActualValue = Problem.DataAnalysisProblemData.TrainingSamplesEnd;
+      //var targetValues =
+      //  Problem.DataAnalysisProblemData.Dataset.GetVariableValues(Problem.DataAnalysisProblemData.TargetVariable.Value,
+      //  TrainingSamplesStartParameter.Value.Value, TrainingSamplesEndParameter.Value.Value);
+      //double range = targetValues.Max() - targetValues.Min();
+      //double lowerEstimationLimit = targetValues.Average() - 10.0 * range;
+      //double upperEstimationLimit = targetValues.Average() + 10.0 * range;
+      //evaluator.LowerEstimationLimitParameter.Value = new DoubleValue(lowerEstimationLimit);
+      //evaluator.UpperEstimationLimitParameter.Value = new DoubleValue(upperEstimationLimit);
+      //analyzer.LowerEstimationLimitParameter.Value = new DoubleValue(lowerEstimationLimit);
+      //analyzer.UpperEstimationLimitParameter.Value = new DoubleValue(upperEstimationLimit);
+    }
+    #endregion
+  }
+}
Index: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/Properties/AssemblyInfo.frame
===================================================================
--- branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/Properties/AssemblyInfo.frame	(revision 5475)
+++ branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/Properties/AssemblyInfo.frame	(revision 5475)
@@ -0,0 +1,55 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.Algorithms.DataAnalysis")]
+[assembly: AssemblyDescription("HeuristicLab data-analysis algorithms")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2011 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("3E422463-0CE0-400D-9544-5C11D5818769")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Revision and Build Numbers 
+// by using the '*' as shown below:
+[assembly: AssemblyVersion("3.4.0.0")]
+[assembly: AssemblyFileVersion("3.4.0.$WCREV$")]
Index: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine.cs
===================================================================
--- branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine.cs	(revision 5475)
+++ branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine.cs	(revision 5475)
@@ -0,0 +1,222 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.Problems.DataAnalysis;
+using HeuristicLab.Problems.DataAnalysis.Evaluators;
+using HeuristicLab.Problems.DataAnalysis.Regression.SupportVectorRegression;
+using HeuristicLab.Problems.DataAnalysis.SupportVectorMachine;
+
+namespace HeuristicLab.Algorithms.DataAnalysis {
+  /// <summary>
+  /// A support vector machine.
+  /// </summary>
+  [Item("Support Vector Machine", "Support vector machine data analysis algorithm.")]
+  [Creatable("Data Analysis")]
+  [StorableClass]
+  public sealed class SupportVectorMachine : EngineAlgorithm, IStorableContent {
+    private const string TrainingSamplesStartParameterName = "Training start";
+    private const string TrainingSamplesEndParameterName = "Training end";
+    private const string DataAnalysisProblemDataParameterName = "DataAnalysisProblemData";
+    private const string SvmTypeParameterName = "SvmType";
+    private const string KernelTypeParameterName = "KernelType";
+    private const string CostParameterName = "Cost";
+    private const string NuParameterName = "Nu";
+    private const string GammaParameterName = "Gamma";
+    private const string EpsilonParameterName = "Epsilon";
+    private const string ModelParameterName = "SupportVectorMachineModel";
+
+    public string Filename { get; set; }
+
+    #region Problem Properties
+    public override Type ProblemType {
+      get { return typeof(DataAnalysisProblem); }
+    }
+    public new DataAnalysisProblem Problem {
+      get { return (DataAnalysisProblem)base.Problem; }
+      set { base.Problem = value; }
+    }
+    #endregion
+
+    #region parameter properties
+    public IValueParameter<IntValue> TrainingSamplesStartParameter {
+      get { return (IValueParameter<IntValue>)Parameters[TrainingSamplesStartParameterName]; }
+    }
+    public IValueParameter<IntValue> TrainingSamplesEndParameter {
+      get { return (IValueParameter<IntValue>)Parameters[TrainingSamplesEndParameterName]; }
+    }
+    public IValueParameter<StringValue> SvmTypeParameter {
+      get { return (IValueParameter<StringValue>)Parameters[SvmTypeParameterName]; }
+    }
+    public IValueParameter<StringValue> KernelTypeParameter {
+      get { return (IValueParameter<StringValue>)Parameters[KernelTypeParameterName]; }
+    }
+    public IValueParameter<DoubleValue> NuParameter {
+      get { return (IValueParameter<DoubleValue>)Parameters[NuParameterName]; }
+    }
+    public IValueParameter<DoubleValue> CostParameter {
+      get { return (IValueParameter<DoubleValue>)Parameters[CostParameterName]; }
+    }
+    public IValueParameter<DoubleValue> GammaParameter {
+      get { return (IValueParameter<DoubleValue>)Parameters[GammaParameterName]; }
+    }
+    public IValueParameter<DoubleValue> EpsilonParameter {
+      get { return (IValueParameter<DoubleValue>)Parameters[EpsilonParameterName]; }
+    }
+    #endregion
+
+    [Storable]
+    private SupportVectorMachineModelCreator solutionCreator;
+    [Storable]
+    private SupportVectorMachineModelEvaluator evaluator;
+    [Storable]
+    private SimpleMSEEvaluator mseEvaluator;
+    [Storable]
+    private BestSupportVectorRegressionSolutionAnalyzer analyzer;
+    public SupportVectorMachine()
+      : base() {
+      #region svm types
+      StringValue cSvcType = new StringValue("C_SVC").AsReadOnly();
+      StringValue nuSvcType = new StringValue("NU_SVC").AsReadOnly();
+      StringValue eSvrType = new StringValue("EPSILON_SVR").AsReadOnly();
+      StringValue nuSvrType = new StringValue("NU_SVR").AsReadOnly();
+      ItemSet<StringValue> allowedSvmTypes = new ItemSet<StringValue>();
+      allowedSvmTypes.Add(cSvcType);
+      allowedSvmTypes.Add(nuSvcType);
+      allowedSvmTypes.Add(eSvrType);
+      allowedSvmTypes.Add(nuSvrType);
+      #endregion
+      #region kernel types
+      StringValue rbfKernelType = new StringValue("RBF").AsReadOnly();
+      StringValue linearKernelType = new StringValue("LINEAR").AsReadOnly();
+      StringValue polynomialKernelType = new StringValue("POLY").AsReadOnly();
+      StringValue sigmoidKernelType = new StringValue("SIGMOID").AsReadOnly();
+      ItemSet<StringValue> allowedKernelTypes = new ItemSet<StringValue>();
+      allowedKernelTypes.Add(rbfKernelType);
+      allowedKernelTypes.Add(linearKernelType);
+      allowedKernelTypes.Add(polynomialKernelType);
+      allowedKernelTypes.Add(sigmoidKernelType);
+      #endregion
+      Parameters.Add(new ValueParameter<IntValue>(TrainingSamplesStartParameterName, "The first index of the data set partition to use for training."));
+      Parameters.Add(new ValueParameter<IntValue>(TrainingSamplesEndParameterName, "The last index of the data set partition to use for training."));
+      Parameters.Add(new ConstrainedValueParameter<StringValue>(SvmTypeParameterName, "The type of SVM to use.", allowedSvmTypes, nuSvrType));
+      Parameters.Add(new ConstrainedValueParameter<StringValue>(KernelTypeParameterName, "The kernel type to use for the SVM.", allowedKernelTypes, rbfKernelType));
+      Parameters.Add(new ValueParameter<DoubleValue>(NuParameterName, "The value of the nu parameter nu-SVC, one-class SVM and nu-SVR.", new DoubleValue(0.5)));
+      Parameters.Add(new ValueParameter<DoubleValue>(CostParameterName, "The value of the C (cost) parameter of C-SVC, epsilon-SVR and nu-SVR.", new DoubleValue(1.0)));
+      Parameters.Add(new ValueParameter<DoubleValue>(GammaParameterName, "The value of the gamma parameter in the kernel function.", new DoubleValue(1.0)));
+      Parameters.Add(new ValueLookupParameter<DoubleValue>(EpsilonParameterName, "The value of the epsilon parameter (only for epsilon-SVR).", new DoubleValue(1.0)));
+
+      solutionCreator = new SupportVectorMachineModelCreator();
+      evaluator = new SupportVectorMachineModelEvaluator();
+      mseEvaluator = new SimpleMSEEvaluator();
+      analyzer = new BestSupportVectorRegressionSolutionAnalyzer();
+
+      OperatorGraph.InitialOperator = solutionCreator;
+      solutionCreator.Successor = evaluator;
+      evaluator.Successor = mseEvaluator;
+      mseEvaluator.Successor = analyzer;
+
+      Initialize();
+    }
+    [StorableConstructor]
+    private SupportVectorMachine(bool deserializing) : base(deserializing) { }
+    [StorableHook(HookType.AfterDeserialization)]
+    private void AfterDeserialization() {
+      Initialize();
+    }
+
+    private SupportVectorMachine(SupportVectorMachine original, Cloner cloner)
+      : base(original, cloner) {
+      solutionCreator = cloner.Clone(original.solutionCreator);
+      evaluator = cloner.Clone(original.evaluator);
+      mseEvaluator = cloner.Clone(original.mseEvaluator);
+      analyzer = cloner.Clone(original.analyzer);
+      Initialize();
+    }
+    public override IDeepCloneable Clone(Cloner cloner) {
+      return new SupportVectorMachine(this, cloner);
+    }
+
+    public override void Prepare() {
+      if (Problem != null) base.Prepare();
+    }
+
+    protected override void Problem_Reset(object sender, EventArgs e) {
+      UpdateAlgorithmParameters();
+      base.Problem_Reset(sender, e);
+    }
+
+    #region Events
+    protected override void OnProblemChanged() {
+      solutionCreator.DataAnalysisProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+      evaluator.DataAnalysisProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+      analyzer.ProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+      UpdateAlgorithmParameters();
+      Problem.Reset += new EventHandler(Problem_Reset);
+      base.OnProblemChanged();
+    }
+
+    #endregion
+
+    #region Helpers
+    private void Initialize() {
+      solutionCreator.SvmTypeParameter.ActualName = SvmTypeParameter.Name;
+      solutionCreator.KernelTypeParameter.ActualName = KernelTypeParameter.Name;
+      solutionCreator.CostParameter.ActualName = CostParameter.Name;
+      solutionCreator.GammaParameter.ActualName = GammaParameter.Name;
+      solutionCreator.NuParameter.ActualName = NuParameter.Name;
+      solutionCreator.SamplesStartParameter.ActualName = TrainingSamplesStartParameter.Name;
+      solutionCreator.SamplesEndParameter.ActualName = TrainingSamplesEndParameter.Name;
+
+      evaluator.SamplesStartParameter.ActualName = TrainingSamplesStartParameter.Name;
+      evaluator.SamplesEndParameter.ActualName = TrainingSamplesEndParameter.Name;
+      evaluator.SupportVectorMachineModelParameter.ActualName = solutionCreator.SupportVectorMachineModelParameter.ActualName;
+      evaluator.ValuesParameter.ActualName = "Training values";
+
+      mseEvaluator.ValuesParameter.ActualName = "Training values";
+      mseEvaluator.MeanSquaredErrorParameter.ActualName = "Training MSE";
+
+      analyzer.SupportVectorRegressionModelParameter.ActualName = solutionCreator.SupportVectorMachineModelParameter.ActualName;
+      analyzer.SupportVectorRegressionModelParameter.Depth = 0;
+      analyzer.QualityParameter.ActualName = mseEvaluator.MeanSquaredErrorParameter.ActualName;
+      analyzer.QualityParameter.Depth = 0;
+
+      if (Problem != null) {
+        solutionCreator.DataAnalysisProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+        evaluator.DataAnalysisProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+        analyzer.ProblemDataParameter.ActualName = Problem.DataAnalysisProblemDataParameter.Name;
+        Problem.Reset += new EventHandler(Problem_Reset);
+      }
+    }
+
+    private void UpdateAlgorithmParameters() {
+      TrainingSamplesStartParameter.ActualValue = Problem.DataAnalysisProblemData.TrainingSamplesStart;
+      TrainingSamplesEndParameter.ActualValue = Problem.DataAnalysisProblemData.TrainingSamplesEnd;
+    }
+    #endregion
+  }
+}
