Free cookie consent management tool by TermsFeed Policy Generator

Changeset 6740 for trunk


Ignore:
Timestamp:
09/12/11 13:48:31 (13 years ago)
Author:
mkommend
Message:

#1597, #1609, #1640:

  • Corrected TableFileParser to handle empty rows correctly.
  • Refactored DataSet to store values in List<List> instead of a two-dimensional array.
  • Enable importing and storing string and datetime values.
  • Changed data access methods in dataset and adapted all concerning classes.
  • Changed interpreter to store the variable values for all rows during the compilation step.
Location:
trunk/sources
Files:
51 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/AlglibUtil.cs

    r6002 r6740  
    3131
    3232      double[,] matrix = new double[rowsList.Count, variablesList.Count];
    33       for (int row = 0; row < rowsList.Count; row++) {
    34         int col = 0;
    35         foreach (string column in variables) {
    36           matrix[row, col] = dataset[column, rowsList[row]];
    37           col++;
     33
     34      int col = 0;
     35      foreach (string column in variables) {
     36        var values = dataset.GetDoubleValues(column, rows);
     37        int row = 0;
     38        foreach (var value in values) {
     39          matrix[row, col] = value;
     40          row++;
    3841        }
     42        col++;
    3943      }
     44
    4045      return matrix;
    4146    }
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/MultinomialLogitClassification.cs

    r6649 r6740  
    7878      int nRows = inputMatrix.GetLength(0);
    7979      int nFeatures = inputMatrix.GetLength(1) - 1;
    80       double[] classValues = dataset.GetVariableValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
     80      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
    8181      int nClasses = classValues.Count();
    8282      // map original class values to values [0..nClasses-1]
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourClassification.cs

    r6649 r6740  
    9696      int nRows = inputMatrix.GetLength(0);
    9797      int nFeatures = inputMatrix.GetLength(1) - 1;
    98       double[] classValues = dataset.GetVariableValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
     98      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
    9999      int nClasses = classValues.Count();
    100100      // map original class values to values [0..nClasses-1]
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkClassification.cs

    r6720 r6740  
    192192      int nRows = inputMatrix.GetLength(0);
    193193      int nFeatures = inputMatrix.GetLength(1) - 1;
    194       double[] classValues = dataset.GetVariableValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
     194      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
    195195      int nClasses = classValues.Count();
    196196      // map original class values to values [0..nClasses-1]
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkEnsembleClassification.cs

    r6720 r6740  
    178178      int nRows = inputMatrix.GetLength(0);
    179179      int nFeatures = inputMatrix.GetLength(1) - 1;
    180       double[] classValues = dataset.GetVariableValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
     180      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
    181181      int nClasses = classValues.Count();
    182182      // map original class values to values [0..nClasses-1]
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/RandomForest/RandomForestClassification.cs

    r6649 r6740  
    108108      int nCols = inputMatrix.GetLength(1);
    109109      int info;
    110       double[] classValues = dataset.GetVariableValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
     110      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
    111111      int nClasses = classValues.Count();
    112112      // map original class values to values [0..nClasses-1]
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine/SupportVectorMachineUtil.cs

    r6002 r6740  
    3434    public static SVM.Problem CreateSvmProblem(Dataset dataset, string targetVariable, IEnumerable<string> inputVariables, IEnumerable<int> rowIndices) {
    3535      double[] targetVector =
    36         dataset.GetEnumeratedVariableValues(targetVariable, rowIndices)
    37         .ToArray();
     36        dataset.GetDoubleValues(targetVariable, rowIndices).ToArray();
    3837
    3938      SVM.Node[][] nodes = new SVM.Node[targetVector.Length][];
     
    4645        int colIndex = 1; // make sure the smallest node index for SVM = 1
    4746        foreach (var inputVariable in inputVariablesList) {
    48           double value = dataset[row, dataset.GetVariableIndex(inputVariable)];
     47          double value = dataset.GetDoubleValue(inputVariable, row);
    4948          // SVM also works with missing values
    5049          // => don't add NaN values in the dataset to the sparse SVM matrix representation
  • trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/kMeans/KMeansClusteringUtil.cs

    r5809 r6740  
    2020#endregion
    2121
     22using System;
    2223using System.Collections.Generic;
    2324using System.Linq;
    2425using HeuristicLab.Problems.DataAnalysis;
    25 using System;
    2626
    2727namespace HeuristicLab.Algorithms.DataAnalysis {
     
    4242          int col = 0;
    4343          foreach (var inputVariable in allowedInputVariables) {
    44             double d = center[col++] - dataset[inputVariable, row];
     44            double d = center[col++] - dataset.GetDoubleValue(inputVariable, row);
    4545            d = d * d; // square;
    4646            centerDistance += d;
     
    7373        double[] p = new double[allowedInputVariables.Count];
    7474        for (int i = 0; i < nCols; i++) {
    75           p[i] = dataset[allowedInputVariables[i], row];
     75          p[i] = dataset.GetDoubleValue(allowedInputVariables[i], row);
    7676        }
    7777        clusterPoints[clusterValues[clusterValueIndex++]].Add(p);
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/Instruction.cs

    r5809 r6740  
    3030    // number of arguments of the current instruction
    3131    public byte nArguments;
    32     // an optional short value (addresses for calls, argument index for arguments)
    33     public ushort iArg0;
     32    // an optional object value (addresses for calls, argument index for arguments)
     33    public object iArg0;
    3434  }
    3535}
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification.Views/3.4/InteractiveSymbolicDiscriminantFunctionClassificationSolutionSimplifierView.cs

    r6438 r6740  
    7373      List<ISymbolicExpressionTreeNode> nodes = tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPostfix().ToList();
    7474
    75       var targetClassValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
     75      var targetClassValues = dataset.GetDoubleValues(targetVariable, rows);
    7676      var originalOutput = interpreter.GetSymbolicExpressionTreeValues(tree, dataset, rows)
    7777        .LimitToRange(Content.Model.LowerEstimationLimit, Content.Model.UpperEstimationLimit)
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/MultiObjective/SymbolicClassificationMultiObjectiveMeanSquaredErrorTreeSizeEvaluator.cs

    r5942 r6740  
    5454    public static double[] Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IClassificationProblemData problemData, IEnumerable<int> rows) {
    5555      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    56       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     56      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5757      IEnumerable<double> boundedEstimationValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
    5858      OnlineCalculatorError errorState;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/MultiObjective/SymbolicClassificationMultiObjectivePearsonRSquaredTreeSizeEvaluator.cs

    r5942 r6740  
    3333    public static double[] Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IClassificationProblemData problemData, IEnumerable<int> rows) {
    3434      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    35       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     35      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    3636      OnlineCalculatorError errorState;
    3737      double r2 = OnlinePearsonsRSquaredCalculator.Calculate(estimatedValues, originalValues, out errorState);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/MultiObjective/SymbolicClassificationMultiObjectiveProblem.cs

    r5854 r6740  
    7474    private void UpdateEstimationLimits() {
    7575      if (ProblemData.TrainingPartition.Start < ProblemData.TrainingPartition.End) {
    76         var targetValues = ProblemData.Dataset.GetVariableValues(ProblemData.TargetVariable, ProblemData.TrainingPartition.Start, ProblemData.TrainingPartition.End);
     76        var targetValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToList();
    7777        var mean = targetValues.Average();
    7878        var range = targetValues.Max() - targetValues.Min();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SingleObjective/SymbolicClassificationSingleObjectiveBoundedMeanSquaredErrorEvaluator.cs

    r5906 r6740  
    5454    public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IClassificationProblemData problemData, IEnumerable<int> rows) {
    5555      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    56       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     56      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5757      IEnumerable<double> boundedEstimationValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
    5858
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SingleObjective/SymbolicClassificationSingleObjectiveMeanSquaredErrorEvaluator.cs

    r5942 r6740  
    5454    public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IClassificationProblemData problemData, IEnumerable<int> rows) {
    5555      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    56       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     56      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5757      IEnumerable<double> boundedEstimationValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
    5858      OnlineCalculatorError errorState;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SingleObjective/SymbolicClassificationSingleObjectivePearsonRSquaredEvaluator.cs

    r5942 r6740  
    5454    public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IClassificationProblemData problemData, IEnumerable<int> rows) {
    5555      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    56       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     56      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5757      OnlineCalculatorError errorState;
    5858      double r2 = OnlinePearsonsRSquaredCalculator.Calculate(estimatedValues, originalValues, out errorState);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SingleObjective/SymbolicClassificationSingleObjectiveProblem.cs

    r5854 r6740  
    7373    private void UpdateEstimationLimits() {
    7474      if (ProblemData.TrainingPartition.Start < ProblemData.TrainingPartition.End) {
    75         var targetValues = ProblemData.Dataset.GetVariableValues(ProblemData.TargetVariable, ProblemData.TrainingPartition.Start, ProblemData.TrainingPartition.End);
     75        var targetValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToList();
    7676        var mean = targetValues.Average();
    7777        var range = targetValues.Max() - targetValues.Min();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SymbolicDiscriminantFunctionClassificationModel.cs

    r6604 r6740  
    127127      var rows = problemData.TrainingIndizes;
    128128      var estimatedValues = model.Interpreter.GetSymbolicExpressionTreeValues(model.SymbolicExpressionTree, dataset, rows);
    129       var targetValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
     129      var targetValues = dataset.GetDoubleValues(targetVariable, rows);
    130130      double alpha;
    131131      double beta;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Views/3.4/InteractiveSymbolicRegressionSolutionSimplifierView.cs

    r6376 r6740  
    7272      var originalOutput = interpreter.GetSymbolicExpressionTreeValues(tree, dataset, rows)
    7373        .ToArray();
    74       var targetValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
     74      var targetValues = dataset.GetDoubleValues(targetVariable, rows);
    7575      OnlineCalculatorError errorState;
    7676      double originalR2 = OnlinePearsonsRSquaredCalculator.Calculate(targetValues, originalOutput, out errorState);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectiveMeanSquaredErrorTreeSizeEvaluator.cs

    r5942 r6740  
    5454    public static double[] Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable<int> rows) {
    5555      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    56       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     56      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5757      IEnumerable<double> boundedEstimationValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
    5858      OnlineCalculatorError errorState;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectivePearsonRSquaredTreeSizeEvaluator.cs

    r5942 r6740  
    5454    public static double[] Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable<int> rows) {
    5555      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    56       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     56      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5757      OnlineCalculatorError errorState;
    5858      double r2 = OnlinePearsonsRSquaredCalculator.Calculate(estimatedValues, originalValues, out errorState);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectiveProblem.cs

    r5854 r6740  
    7878    private void UpdateEstimationLimits() {
    7979      if (ProblemData.TrainingPartition.Start < ProblemData.TrainingPartition.End) {
    80         var targetValues = ProblemData.Dataset.GetVariableValues(ProblemData.TargetVariable, ProblemData.TrainingPartition.Start, ProblemData.TrainingPartition.End);
     80        var targetValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToList();
    8181        var mean = targetValues.Average();
    8282        var range = targetValues.Max() - targetValues.Min();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.cs

    r5942 r6740  
    5656    public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable<int> rows) {
    5757      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    58       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     58      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5959      IEnumerable<double> boundedEstimationValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
    6060      OnlineCalculatorError errorState;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.cs

    r5942 r6740  
    5656    public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable<int> rows) {
    5757      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    58       IEnumerable<double> originalValues = problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows);
     58      IEnumerable<double> originalValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    5959      OnlineCalculatorError errorState;
    6060      double r2 = OnlinePearsonsRSquaredCalculator.Calculate(estimatedValues, originalValues, out errorState);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/SymbolicRegressionSingleObjectiveProblem.cs

    r5854 r6740  
    7575    private void UpdateEstimationLimits() {
    7676      if (ProblemData.TrainingPartition.Start < ProblemData.TrainingPartition.End) {
    77         var targetValues = ProblemData.Dataset.GetVariableValues(ProblemData.TargetVariable, ProblemData.TrainingPartition.Start, ProblemData.TrainingPartition.End);
     77        var targetValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToList();
    7878        var mean = targetValues.Average();
    7979        var range = targetValues.Max() - targetValues.Min();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SymbolicRegressionModel.cs

    r6603 r6740  
    7373      var rows = problemData.TrainingIndizes;
    7474      var estimatedValues = model.Interpreter.GetSymbolicExpressionTreeValues(model.SymbolicExpressionTree, dataset, rows);
    75       var targetValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
     75      var targetValues = dataset.GetDoubleValues(targetVariable, rows);
    7676      double alpha;
    7777      double beta;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/SymbolicDataAnalysisSolutionResponseFunctionView.cs

    r6656 r6740  
    2727using HeuristicLab.Common;
    2828using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    29 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
     29using HeuristicLab.MainForm;
    3030using HeuristicLab.MainForm.WindowsForms;
    31 using System.Windows.Forms.DataVisualization.Charting;
    32 using HeuristicLab.MainForm;
    3331
    3432namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
     
    8886        select varNode.VariableName)
    8987         .Distinct()
    90          .OrderBy(x=>x)
     88         .OrderBy(x => x)
    9189         .ToList();
    9290
    9391        medianValues.Clear();
    9492        foreach (var variableName in referencedVariables) {
    95           medianValues.Add(variableName, Content.ProblemData.Dataset.GetEnumeratedVariableValues(variableName).Median());
     93          medianValues.Add(variableName, Content.ProblemData.Dataset.GetDoubleValues(variableName).Median());
    9694        }
    9795
     
    107105      foreach (var variableName in variableNames) {
    108106        var variableTrackbar = new VariableTrackbar(variableName,
    109                                                     Content.ProblemData.Dataset.GetEnumeratedVariableValues(variableName));
     107                                                    Content.ProblemData.Dataset.GetDoubleValues(variableName));
    110108        variableTrackbar.Size = new Size(variableTrackbar.Size.Width, flowLayoutPanel.Size.Height - 23);
    111109        variableTrackbar.ValueChanged += TrackBarValueChanged;
     
    132130        .Except(new string[] { freeVariable });
    133131
    134       var freeVariableValues = Content.ProblemData.Dataset.GetEnumeratedVariableValues(freeVariable, Content.ProblemData.TrainingIndizes).ToArray();
     132      var freeVariableValues = Content.ProblemData.Dataset.GetDoubleValues(freeVariable, Content.ProblemData.TrainingIndizes).ToArray();
    135133      var responseValues = Content.Model.Interpreter.GetSymbolicExpressionTreeValues(clonedTree,
    136134                                                                              Content.ProblemData.Dataset,
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeILEmittingInterpreter.cs

    r6732 r6740  
    2626using HeuristicLab.Common;
    2727using HeuristicLab.Core;
     28using HeuristicLab.Data;
    2829using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     30using HeuristicLab.Parameters;
    2931using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    30 using HeuristicLab.Data;
    31 using HeuristicLab.Parameters;
    3232
    3333namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
     
    224224        if (instr.opCode == OpCodes.Variable) {
    225225          var variableTreeNode = instr.dynamicNode as VariableTreeNode;
    226           instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
     226          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
    227227          code[i] = instr;
    228228        } else if (instr.opCode == OpCodes.LagVariable) {
    229229          var variableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
    230           instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
     230          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
    231231          code[i] = instr;
    232232        } else if (instr.opCode == OpCodes.VariableCondition) {
    233233          var variableConditionTreeNode = instr.dynamicNode as VariableConditionTreeNode;
    234           instr.iArg0 = (ushort)dataset.GetVariableIndex(variableConditionTreeNode.VariableName);
     234          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
    235235        } else if (instr.opCode == OpCodes.Call) {
    236236          necessaryArgStackSize += instr.nArguments + 1;
     
    468468          }
    469469        case OpCodes.Variable: {
    470             VariableTreeNode varNode = (VariableTreeNode)currentInstr.dynamicNode;
    471             il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // load dataset
    472             il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, 0); // sampleOffset
    473             il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); // sampleIndex
    474             il.Emit(System.Reflection.Emit.OpCodes.Add); // row = sampleIndex + sampleOffset
    475             il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, currentInstr.iArg0); // load var
    476             il.Emit(System.Reflection.Emit.OpCodes.Call, datasetGetValue); // dataset.GetValue
    477             il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.Weight); // load weight
    478             il.Emit(System.Reflection.Emit.OpCodes.Mul);
     470            //VariableTreeNode varNode = (VariableTreeNode)currentInstr.dynamicNode;
     471            //il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // load dataset
     472            //il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, 0); // sampleOffset
     473            //il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); // sampleIndex
     474            //il.Emit(System.Reflection.Emit.OpCodes.Add); // row = sampleIndex + sampleOffset
     475            //il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, currentInstr.iArg0); // load var
     476            //il.Emit(System.Reflection.Emit.OpCodes.Call, datasetGetValue); // dataset.GetValue
     477            //il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.Weight); // load weight
     478            //il.Emit(System.Reflection.Emit.OpCodes.Mul);
    479479            return;
    480480          }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeInterpreter.cs

    r6732 r6740  
    2424using HeuristicLab.Common;
    2525using HeuristicLab.Core;
     26using HeuristicLab.Data;
    2627using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     28using HeuristicLab.Parameters;
    2729using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    28 using HeuristicLab.Data;
    29 using HeuristicLab.Parameters;
    3030
    3131namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
     
    208208        if (instr.opCode == OpCodes.Variable) {
    209209          var variableTreeNode = instr.dynamicNode as VariableTreeNode;
    210           instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
     210          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
    211211          code[i] = instr;
    212212        } else if (instr.opCode == OpCodes.LagVariable) {
    213           var variableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
    214           instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
     213          var laggedVariableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
     214          instr.iArg0 = dataset.GetReadOnlyDoubleValues(laggedVariableTreeNode.VariableName);
    215215          code[i] = instr;
    216216        } else if (instr.opCode == OpCodes.VariableCondition) {
    217217          var variableConditionTreeNode = instr.dynamicNode as VariableConditionTreeNode;
    218           instr.iArg0 = (ushort)dataset.GetVariableIndex(variableConditionTreeNode.VariableName);
     218          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
    219219        } else if (instr.opCode == OpCodes.Call) {
    220220          necessaryArgStackSize += instr.nArguments + 1;
     
    390390            int savedPc = state.ProgramCounter;
    391391            // set pc to start of function 
    392             state.ProgramCounter = currentInstr.iArg0;
     392            state.ProgramCounter = (ushort)currentInstr.iArg0;
    393393            // evaluate the function
    394394            double v = Evaluate(dataset, ref row, state);
     
    402402          }
    403403        case OpCodes.Arg: {
    404             return state.GetStackFrameValue(currentInstr.iArg0);
     404            return state.GetStackFrameValue((ushort)currentInstr.iArg0);
    405405          }
    406406        case OpCodes.Variable: {
    407407            if (row < 0 || row >= dataset.Rows)
    408408              return double.NaN;
    409             var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
    410             return dataset[row, currentInstr.iArg0] * variableTreeNode.Weight;
     409            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
     410            return ((IList<double>)currentInstr.iArg0)[row] * variableTreeNode.Weight;
    411411          }
    412412        case OpCodes.LagVariable: {
    413             var laggedVariableTreeNode = currentInstr.dynamicNode as LaggedVariableTreeNode;
     413            var laggedVariableTreeNode = (LaggedVariableTreeNode)currentInstr.dynamicNode;
    414414            int actualRow = row + laggedVariableTreeNode.Lag;
    415415            if (actualRow < 0 || actualRow >= dataset.Rows)
    416416              return double.NaN;
    417             return dataset[actualRow, currentInstr.iArg0] * laggedVariableTreeNode.Weight;
     417            return ((IList<double>)currentInstr.iArg0)[row] * laggedVariableTreeNode.Weight;
    418418          }
    419419        case OpCodes.Constant: {
     
    428428              return double.NaN;
    429429            var variableConditionTreeNode = (VariableConditionTreeNode)currentInstr.dynamicNode;
    430             double variableValue = dataset[row, currentInstr.iArg0];
     430            double variableValue = ((IList<double>)currentInstr.iArg0)[row];
    431431            double x = variableValue - variableConditionTreeNode.Threshold;
    432432            double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x));
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationEnsembleSolutionEstimatedClassValuesView.cs

    r6680 r6740  
    9898      int modelCount = Content.Model.Models.Count();
    9999      string[,] values = new string[indizes.Length, 5 + classValuesCount + modelCount];
    100       double[] target = Content.ProblemData.Dataset.GetVariableValues(Content.ProblemData.TargetVariable);
     100      double[] target = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
    101101      List<List<double?>> estimatedValuesVector = GetEstimatedValues(SamplesComboBox.SelectedItem.ToString(), indizes,
    102102                                                            Content.ClassificationSolutions);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationSolutionConfusionMatrixView.cs

    r6642 r6740  
    114114        } else throw new InvalidOperationException();
    115115
    116         double[] targetValues = Content.ProblemData.Dataset.GetEnumeratedVariableValues(Content.ProblemData.TargetVariable, rows).ToArray();
     116        double[] targetValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable, rows).ToArray();
    117117
    118118        Dictionary<double, int> classValueIndexMapping = new Dictionary<double, int>();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationSolutionEstimatedClassValuesView.cs

    r6642 r6740  
    8686          string[,] values = new string[Content.ProblemData.Dataset.Rows, 5];
    8787
    88           double[] target = Content.ProblemData.Dataset.GetVariableValues(Content.ProblemData.TargetVariable);
     88          double[] target = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
    8989          double[] estimated = Content.EstimatedClassValues.ToArray();
    9090          for (int row = 0; row < target.Length; row++) {
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/DiscriminantFunctionClassificationRocCurvesView.cs

    r6642 r6740  
    107107
    108108        double[] estimatedValues = Content.GetEstimatedValues(rows).ToArray();
    109         double[] targetClassValues = Content.ProblemData.Dataset.GetEnumeratedVariableValues(Content.ProblemData.TargetVariable, rows).ToArray();
     109        double[] targetClassValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable, rows).ToArray();
    110110        double minThreshold = estimatedValues.Min();
    111111        double maxThreshold = estimatedValues.Max();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/DiscriminantFunctionClassificationSolutionEstimatedClassValuesView.cs

    r6642 r6740  
    5151          string[,] values = new string[Content.ProblemData.Dataset.Rows, 4];
    5252
    53           double[] target = Content.ProblemData.Dataset.GetVariableValues(Content.ProblemData.TargetVariable);
     53          double[] target = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
    5454          double[] estimatedClassValues = Content.EstimatedClassValues.ToArray();
    5555          double[] estimatedValues = Content.EstimatedValues.ToArray();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/DiscriminantFunctionClassificationSolutionThresholdView.cs

    r6729 r6740  
    135135    private void FillSeriesWithDataPoints(Series series) {
    136136      List<double> estimatedValues = Content.EstimatedValues.ToList();
     137      var targetValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToList();
     138
    137139      foreach (int row in Content.ProblemData.TrainingIndizes) {
    138140        double estimatedValue = estimatedValues[row];
    139         double targetValue = Content.ProblemData.Dataset[Content.ProblemData.TargetVariable, row];
     141        double targetValue = targetValues[row];
    140142        if (targetValue.IsAlmost((double)series.Tag)) {
    141143          double jitterValue = random.NextDouble() * 2.0 - 1.0;
     
    150152      foreach (int row in Content.ProblemData.TestIndizes) {
    151153        double estimatedValue = estimatedValues[row];
    152         double targetValue = Content.ProblemData.Dataset[Content.ProblemData.TargetVariable, row];
    153         if (targetValue == (double)series.Tag) {
     154        double targetValue = targetValues[row];
     155        if (targetValue.IsAlmost((double)series.Tag)) {
    154156          double jitterValue = random.NextDouble() * 2.0 - 1.0;
    155157          DataPoint point = new DataPoint();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Clustering/ClusteringSolutionEstimatedClusterView.cs

    r6642 r6740  
    8585          int[] clusters = Content.Model.GetClusterValues(Content.ProblemData.Dataset, Enumerable.Range(0, Content.ProblemData.Dataset.Rows)).ToArray();
    8686          var dataset = Content.ProblemData.Dataset;
    87           int columns = Content.ProblemData.AllowedInputVariables.Count() + 1;
    88           var columnsIndixes = Content.ProblemData.AllowedInputVariables.Select(x => dataset.GetVariableIndex(x)).ToList();
     87          int columns = Content.ProblemData.AllowedInputVariables.Count() + 1;         
    8988
    9089          double[,] values = new double[dataset.Rows, columns];
     
    9392
    9493            int column = 1;
    95             foreach (int columnIndex in columnsIndixes) {
    96               values[row, column] = dataset[row, columnIndex];
     94            foreach (var columnName in Content.ProblemData.AllowedInputVariables) {
     95              values[row, column] = dataset.GetDoubleValue(columnName, row);
    9796              column++;
    9897            }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionErrorCharacteristicsCurveView.cs

    r6642 r6740  
    164164      switch (cmbSamples.SelectedItem.ToString()) {
    165165        case TrainingSamples:
    166           originalValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes);
     166          originalValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes);
    167167          break;
    168168        case TestSamples:
    169           originalValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TestIndizes);
     169          originalValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TestIndizes);
    170170          break;
    171171        case AllSamples:
    172           originalValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable);
     172          originalValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable);
    173173          break;
    174174        default:
     
    197197
    198198    protected IEnumerable<double> GetMeanModelEstimatedValues(IEnumerable<double> originalValues) {
    199       double averageTrainingTarget = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).Average();
     199      double averageTrainingTarget = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).Average();
    200200      return Enumerable.Repeat(averageTrainingTarget, originalValues.Count());
    201201    }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionEstimatedValuesView.cs

    r6642 r6740  
    8888          string[,] values = new string[Content.ProblemData.Dataset.Rows, 7];
    8989
    90           double[] target = Content.ProblemData.Dataset.GetVariableValues(Content.ProblemData.TargetVariable);
     90          double[] target = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
    9191          var estimated = Content.EstimatedValues.GetEnumerator();
    9292          var estimated_training = Content.EstimatedTrainingValues.GetEnumerator();
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartView.cs

    r6679 r6740  
    6767        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    6868        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
    69           Content.ProblemData.Dataset.GetVariableValues(Content.ProblemData.TargetVariable));
     69          Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
    7070
    7171        this.chart.Series.Add(ESTIMATEDVALUES_TRAINING_SERIES_NAME);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionScatterPlotView.cs

    r6679 r6740  
    130130        if (this.chart.Series[ALL_SERIES].Points.Count > 0)
    131131          this.chart.Series[ALL_SERIES].Points.DataBindXY(Content.EstimatedValues.ToArray(), "",
    132             dataset.GetVariableValues(targetVariableName), "");
     132            dataset.GetDoubleValues(targetVariableName).ToArray(), "");
    133133        if (this.chart.Series[TRAINING_SERIES].Points.Count > 0)
    134134          this.chart.Series[TRAINING_SERIES].Points.DataBindXY(Content.EstimatedTrainingValues.ToArray(), "",
    135             dataset.GetEnumeratedVariableValues(targetVariableName, Content.ProblemData.TrainingIndizes).ToArray(), "");
     135            dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TrainingIndizes).ToArray(), "");
    136136        if (this.chart.Series[TEST_SERIES].Points.Count > 0)
    137137          this.chart.Series[TEST_SERIES].Points.DataBindXY(Content.EstimatedTestValues.ToArray(), "",
    138            dataset.GetEnumeratedVariableValues(targetVariableName, Content.ProblemData.TestIndizes).ToArray(), "");
    139 
    140         double max = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetVariableValues(targetVariableName)))).Max();
    141         double min = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetVariableValues(targetVariableName)))).Min();
     138           dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TestIndizes).ToArray(), "");
     139
     140        double max = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetDoubleValues(targetVariableName)))).Max();
     141        double min = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetDoubleValues(targetVariableName)))).Min();
    142142
    143143        max = max + 0.2 * Math.Abs(max);
     
    177177          case ALL_SERIES:
    178178            predictedValues = Content.EstimatedValues.ToArray();
    179             targetValues = Content.ProblemData.Dataset.GetVariableValues(targetVariableName);
     179            targetValues = Content.ProblemData.Dataset.GetDoubleValues(targetVariableName).ToArray();
    180180            break;
    181181          case TRAINING_SERIES:
    182182            predictedValues = Content.EstimatedTrainingValues.ToArray();
    183             targetValues = Content.ProblemData.Dataset.GetEnumeratedVariableValues(targetVariableName, Content.ProblemData.TrainingIndizes).ToArray();
     183            targetValues = Content.ProblemData.Dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TrainingIndizes).ToArray();
    184184            break;
    185185          case TEST_SERIES:
    186186            predictedValues = Content.EstimatedTestValues.ToArray();
    187             targetValues = Content.ProblemData.Dataset.GetEnumeratedVariableValues(targetVariableName, Content.ProblemData.TestIndizes).ToArray();
     187            targetValues = Content.ProblemData.Dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TestIndizes).ToArray();
    188188            break;
    189189        }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs

    r5847 r6740  
    2121
    2222using System;
     23using System.Collections;
    2324using System.Collections.Generic;
     25using System.Collections.ObjectModel;
    2426using System.Linq;
    2527using HeuristicLab.Common;
     
    3638    private Dataset(Dataset original, Cloner cloner)
    3739      : base(original, cloner) {
    38       variableNameToVariableIndexMapping = original.variableNameToVariableIndexMapping;
    39       data = original.data;
    40     }
    41     public override IDeepCloneable Clone(Cloner cloner) {
    42       return new Dataset(this, cloner);
    43     }
     40      variableValues = new Dictionary<string, IList>(original.variableValues);
     41      variableNames = new List<string>(original.variableNames);
     42      rows = original.rows;
     43    }
     44    public override IDeepCloneable Clone(Cloner cloner) { return new Dataset(this, cloner); }
    4445
    4546    public Dataset()
     
    4748      Name = "-";
    4849      VariableNames = Enumerable.Empty<string>();
    49       data = new double[0, 0];
    50     }
    51 
    52     public Dataset(IEnumerable<string> variableNames, double[,] data)
     50      variableValues = new Dictionary<string, IList>();
     51      rows = 0;
     52    }
     53
     54    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
    5355      : base() {
    5456      Name = "-";
    55       if (variableNames.Count() != data.GetLength(1)) {
    56         throw new ArgumentException("Number of variable names doesn't match the number of columns of data");
    57       }
    58       this.data = (double[,])data.Clone();
    59       VariableNames = variableNames;
    60     }
    61 
    62 
    63     private Dictionary<string, int> variableNameToVariableIndexMapping;
    64     private Dictionary<int, string> variableIndexToVariableNameMapping;
     57      if (!variableNames.Any()) {
     58        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
     59      } else if (variableNames.Count() != variableValues.Count()) {
     60        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
     61      } else if (!variableValues.All(list => list.Count == variableValues.First().Count)) {
     62        throw new ArgumentException("The number of values must be equal for every variable");
     63      } else if (variableNames.Distinct().Count() != variableNames.Count()) {
     64        var duplicateVariableNames =
     65          variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
     66        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
     67        foreach (var duplicateVariableName in duplicateVariableNames)
     68          message += duplicateVariableName + Environment.NewLine;
     69        throw new ArgumentException(message);
     70      }
     71
     72      rows = variableValues.First().Count;
     73      this.variableNames = new List<string>(variableNames);
     74      this.variableValues = new Dictionary<string, IList>();
     75      for (int i = 0; i < this.variableNames.Count; i++) {
     76        var values = variableValues.ElementAt(i);
     77        IList clonedValues = null;
     78        if (values is List<double>)
     79          clonedValues = new List<double>(values.Cast<double>());
     80        else if (values is List<string>)
     81          clonedValues = new List<string>(values.Cast<string>());
     82        else if (values is List<DateTime>)
     83          clonedValues = new List<DateTime>(values.Cast<DateTime>());
     84        else {
     85          this.variableNames = new List<string>();
     86          this.variableValues = new Dictionary<string, IList>();
     87          throw new ArgumentException("The variable values must be of type List<double>, List<string> or List<DateTime>");
     88        }
     89        this.variableValues.Add(this.variableNames[i], clonedValues);
     90      }
     91    }
     92
     93    public Dataset(IEnumerable<string> variableNames, double[,] variableValues) {
     94      Name = "-";
     95      if (variableNames.Count() != variableValues.GetLength(1)) {
     96        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
     97      }
     98      if (variableNames.Distinct().Count() != variableNames.Count()) {
     99        var duplicateVariableNames = variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
     100        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
     101        foreach (var duplicateVariableName in duplicateVariableNames)
     102          message += duplicateVariableName + Environment.NewLine;
     103        throw new ArgumentException(message);
     104      }
     105
     106      rows = variableValues.GetLength(0);
     107      this.variableNames = new List<string>(variableNames);
     108
     109      this.variableValues = new Dictionary<string, IList>();
     110      for (int col = 0; col < variableValues.GetLength(1); col++) {
     111        string columName = this.variableNames[col];
     112        var values = new List<double>();
     113        for (int row = 0; row < variableValues.GetLength(0); row++) {
     114          values.Add(variableValues[row, col]);
     115        }
     116        this.variableValues.Add(columName, values);
     117      }
     118    }
     119
     120    #region Backwards compatible code, remove with 3.5
     121    private double[,] storableData;
     122    //name alias used to suppport backwards compatibility
     123    [Storable(Name = "data", AllowOneWay = true)]
     124    private double[,] StorableData { set { storableData = value; } }
     125
     126    [StorableHook(HookType.AfterDeserialization)]
     127    private void AfterDeserialization() {
     128      if (variableValues == null) {
     129        rows = storableData.GetLength(0);
     130        variableValues = new Dictionary<string, IList>();
     131        for (int col = 0; col < storableData.GetLength(1); col++) {
     132          string columName = variableNames[col];
     133          var values = new List<double>();
     134          for (int row = 0; row < storableData.GetLength(0); row++) {
     135            values.Add(storableData[row, col]);
     136          }
     137          variableValues.Add(columName, values);
     138        }
     139        storableData = null;
     140      }
     141    }
     142    #endregion
     143
     144    private Dictionary<string, IList> variableValues;
     145    private List<string> variableNames;
    65146    [Storable]
    66147    public IEnumerable<string> VariableNames {
    67       get {
    68         // convert KeyCollection to an array first for persistence
    69         return variableNameToVariableIndexMapping.Keys.ToArray();
    70       }
     148      get { return variableNames; }
    71149      private set {
    72         if (variableNameToVariableIndexMapping != null) throw new InvalidOperationException("VariableNames can only be set once.");
    73         this.variableNameToVariableIndexMapping = new Dictionary<string, int>();
    74         this.variableIndexToVariableNameMapping = new Dictionary<int, string>();
    75         int i = 0;
    76         foreach (string variableName in value) {
    77           this.variableNameToVariableIndexMapping.Add(variableName, i);
    78           this.variableIndexToVariableNameMapping.Add(i, variableName);
    79           i++;
    80         }
    81       }
    82     }
    83 
     150        if (variableNames != null) throw new InvalidOperationException();
     151        variableNames = new List<string>(value);
     152      }
     153    }
     154
     155    public IEnumerable<string> DoubleVariables {
     156      get { return variableValues.Where(p => p.Value is List<double>).Select(p => p.Key); }
     157    }
     158
     159    public IEnumerable<double> GetDoubleValues(string variableName) {
     160      IList list;
     161      if (!variableValues.TryGetValue(variableName, out list))
     162        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
     163      List<double> values = list as List<double>;
     164      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a double variable.");
     165
     166      //mkommend yield return used to enable lazy evaluation
     167      foreach (double value in values)
     168        yield return value;
     169    }
     170    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
     171      IList list;
     172      if (!variableValues.TryGetValue(variableName, out list))
     173        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
     174      List<double> values = list as List<double>;
     175      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a double variable.");
     176      return values.AsReadOnly();
     177    }
     178    public double GetDoubleValue(string variableName, int row) {
     179      IList list;
     180      if (!variableValues.TryGetValue(variableName, out list))
     181        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
     182      List<double> values = list as List<double>;
     183      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a double variable.");
     184      return values[row];
     185    }
     186    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
     187      IList list;
     188      if (!variableValues.TryGetValue(variableName, out list))
     189        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
     190      List<double> values = list as List<double>;
     191      if (values == null) throw new ArgumentException("The varialbe " + variableName + " is not a double variable.");
     192
     193      foreach (int index in rows)
     194        yield return values[index];
     195    }
     196
     197    #region IStringConvertibleMatrix Members
    84198    [Storable]
    85     private double[,] data;
    86     private double[,] Data {
    87       get { return data; }
    88     }
    89 
    90     // elementwise access
    91     public double this[int rowIndex, int columnIndex] {
    92       get { return data[rowIndex, columnIndex]; }
    93     }
    94     public double this[string variableName, int rowIndex] {
    95       get {
    96         int columnIndex = GetVariableIndex(variableName);
    97         return data[rowIndex, columnIndex];
    98       }
    99     }
    100 
    101     public double[] GetVariableValues(int variableIndex) {
    102       return GetVariableValues(variableIndex, 0, Rows);
    103     }
    104     public double[] GetVariableValues(string variableName) {
    105       return GetVariableValues(GetVariableIndex(variableName), 0, Rows);
    106     }
    107     public double[] GetVariableValues(int variableIndex, int start, int end) {
    108       return GetEnumeratedVariableValues(variableIndex, start, end).ToArray();
    109     }
    110     public double[] GetVariableValues(string variableName, int start, int end) {
    111       return GetVariableValues(GetVariableIndex(variableName), start, end);
    112     }
    113 
    114     public IEnumerable<double> GetEnumeratedVariableValues(int variableIndex) {
    115       return GetEnumeratedVariableValues(variableIndex, 0, Rows);
    116     }
    117     public IEnumerable<double> GetEnumeratedVariableValues(int variableIndex, int start, int end) {
    118       if (start < 0 || !(start <= end))
    119         throw new ArgumentException("Start must be between 0 and end (" + end + ").");
    120       if (end > Rows || end < start)
    121         throw new ArgumentException("End must be between start (" + start + ") and dataset rows (" + Rows + ").");
    122 
    123       for (int i = start; i < end; i++)
    124         yield return data[i, variableIndex];
    125     }
    126     public IEnumerable<double> GetEnumeratedVariableValues(int variableIndex, IEnumerable<int> rows) {
    127       foreach (int row in rows)
    128         yield return data[row, variableIndex];
    129     }
    130 
    131     public IEnumerable<double> GetEnumeratedVariableValues(string variableName) {
    132       return GetEnumeratedVariableValues(GetVariableIndex(variableName), 0, Rows);
    133     }
    134     public IEnumerable<double> GetEnumeratedVariableValues(string variableName, int start, int end) {
    135       return GetEnumeratedVariableValues(GetVariableIndex(variableName), start, end);
    136     }
    137     public IEnumerable<double> GetEnumeratedVariableValues(string variableName, IEnumerable<int> rows) {
    138       return GetEnumeratedVariableValues(GetVariableIndex(variableName), rows);
    139     }
    140 
    141     public string GetVariableName(int variableIndex) {
    142       try {
    143         return variableIndexToVariableNameMapping[variableIndex];
    144       }
    145       catch (KeyNotFoundException ex) {
    146         throw new ArgumentException("The variable index " + variableIndex + " was not found.", ex);
    147       }
    148     }
    149     public int GetVariableIndex(string variableName) {
    150       try {
    151         return variableNameToVariableIndexMapping[variableName];
    152       }
    153       catch (KeyNotFoundException ex) {
    154         throw new ArgumentException("The variable name " + variableName + " was not found.", ex);
    155       }
    156     }
    157 
    158     #region IStringConvertibleMatrix Members
     199    private int rows;
    159200    public int Rows {
    160       get { return data.GetLength(0); }
     201      get { return rows; }
    161202      set { throw new NotSupportedException(); }
    162203    }
    163204    public int Columns {
    164       get { return data.GetLength(1); }
     205      get { return variableNames.Count; }
    165206      set { throw new NotSupportedException(); }
    166207    }
     
    184225
    185226    public string GetValue(int rowIndex, int columnIndex) {
    186       return data[rowIndex, columnIndex].ToString();
     227      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
    187228    }
    188229    public bool SetValue(string value, int rowIndex, int columnIndex) {
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationProblemData.cs

    r6672 r6740  
    226226      get {
    227227        if (classValues == null) {
    228           classValues = Dataset.GetEnumeratedVariableValues(TargetVariableParameter.Value.Value).Distinct().ToList();
     228          classValues = Dataset.GetDoubleValues(TargetVariableParameter.Value.Value).Distinct().ToList();
    229229          classValues.Sort();
    230230        }
     
    291291    private static IEnumerable<string> CheckVariablesForPossibleTargetVariables(Dataset dataset) {
    292292      int maxSamples = Math.Min(InspectedRowsToDetermineTargets, dataset.Rows);
    293       var validTargetVariables = (from v in dataset.VariableNames
    294                                   let distinctValues = dataset.GetEnumeratedVariableValues(v)
     293      var validTargetVariables = (from v in dataset.DoubleVariables
     294                                  let distinctValues = dataset.GetDoubleValues(v)
    295295                                    .Take(maxSamples)
    296296                                    .Distinct()
     
    410410      dataset.Name = Path.GetFileName(fileName);
    411411
    412       ClassificationProblemData problemData = new ClassificationProblemData(dataset, dataset.VariableNames.Skip(1), dataset.VariableNames.First());
     412      ClassificationProblemData problemData = new ClassificationProblemData(dataset, dataset.DoubleVariables.Skip(1), dataset.DoubleVariables.First());
    413413      problemData.Name = "Data imported from " + Path.GetFileName(fileName);
    414414      return problemData;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolutionBase.cs

    r6653 r6740  
    6767    protected void CalculateResults() {
    6868      double[] estimatedTrainingClassValues = EstimatedTrainingClassValues.ToArray(); // cache values
    69       double[] originalTrainingClassValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToArray();
     69      double[] originalTrainingClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToArray();
    7070      double[] estimatedTestClassValues = EstimatedTestClassValues.ToArray(); // cache values
    71       double[] originalTestClassValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TestIndizes).ToArray();
     71      double[] originalTestClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TestIndizes).ToArray();
    7272
    7373      OnlineCalculatorError errorState;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationSolutionBase.cs

    r6606 r6740  
    103103    protected void CalculateRegressionResults() {
    104104      double[] estimatedTrainingValues = EstimatedTrainingValues.ToArray(); // cache values
    105       double[] originalTrainingValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToArray();
     105      double[] originalTrainingValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToArray();
    106106      double[] estimatedTestValues = EstimatedTestValues.ToArray(); // cache values
    107       double[] originalTestValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TestIndizes).ToArray();
     107      double[] originalTestValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TestIndizes).ToArray();
    108108
    109109      OnlineCalculatorError errorState;
     
    132132      double[] classValues;
    133133      double[] thresholds;
    134       var targetClassValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes);
     134      var targetClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes);
    135135      AccuracyMaximizationThresholdCalculator.CalculateThresholds(ProblemData, EstimatedTrainingValues, targetClassValues, out classValues, out thresholds);
    136136
     
    141141      double[] classValues;
    142142      double[] thresholds;
    143       var targetClassValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes);
     143      var targetClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes);
    144144      NormalDistributionCutPointsThresholdCalculator.CalculateThresholds(ProblemData, EstimatedTrainingValues, targetClassValues, out classValues, out thresholds);
    145145
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Clustering/ClusteringProblemData.cs

    r5809 r6740  
    2020#endregion
    2121
    22 using System;
    2322using System.Collections.Generic;
    2423using System.IO;
    25 using System.Linq;
    2624using HeuristicLab.Common;
    2725using HeuristicLab.Core;
    28 using HeuristicLab.Data;
    29 using HeuristicLab.Parameters;
    3026using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    3127
     
    10399      dataset.Name = Path.GetFileName(fileName);
    104100
    105       ClusteringProblemData problemData = new ClusteringProblemData(dataset, dataset.VariableNames);
     101      ClusteringProblemData problemData = new ClusteringProblemData(dataset, dataset.DoubleVariables);
    106102      problemData.Name = "Data imported from " + Path.GetFileName(fileName);
    107103      return problemData;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs

    r6672 r6740  
    116116      if (allowedInputVariables == null) throw new ArgumentNullException("The allowedInputVariables must not be null.");
    117117
    118       if (allowedInputVariables.Except(dataset.VariableNames).Any())
    119         throw new ArgumentException("All allowed input variables must be present in the dataset.");
     118      if (allowedInputVariables.Except(dataset.DoubleVariables).Any())
     119        throw new ArgumentException("All allowed input variables must be present in the dataset and of type double.");
    120120
    121       var inputVariables = new CheckedItemList<StringValue>(dataset.VariableNames.Select(x => new StringValue(x)));
     121      var inputVariables = new CheckedItemList<StringValue>(dataset.DoubleVariables.Select(x => new StringValue(x)));
    122122      foreach (StringValue x in inputVariables)
    123123        inputVariables.SetItemCheckedState(x, allowedInputVariables.Contains(x.Value));
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionProblemData.cs

    r6672 r6740  
    144144      dataset.Name = Path.GetFileName(fileName);
    145145
    146       RegressionProblemData problemData = new RegressionProblemData(dataset, dataset.VariableNames.Skip(1), dataset.VariableNames.First());
     146      RegressionProblemData problemData = new RegressionProblemData(dataset, dataset.DoubleVariables.Skip(1), dataset.DoubleVariables.First());
    147147      problemData.Name = "Data imported from " + Path.GetFileName(fileName);
    148148      return problemData;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolutionBase.cs

    r6661 r6740  
    127127        OnlineCalculatorError errorState;
    128128        Add(new Result(TrainingMeanAbsoluteErrorResultName, "Mean of absolute errors of the model on the training partition", new DoubleValue()));
    129         double trainingMAE = OnlineMeanAbsoluteErrorCalculator.Calculate(EstimatedTrainingValues, ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes), out errorState);
     129        double trainingMAE = OnlineMeanAbsoluteErrorCalculator.Calculate(EstimatedTrainingValues, ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes), out errorState);
    130130        TrainingMeanAbsoluteError = errorState == OnlineCalculatorError.None ? trainingMAE : double.NaN;
    131131      }
     
    134134        OnlineCalculatorError errorState;
    135135        Add(new Result(TestMeanAbsoluteErrorResultName, "Mean of absolute errors of the model on the test partition", new DoubleValue()));
    136         double testMAE = OnlineMeanAbsoluteErrorCalculator.Calculate(EstimatedTestValues, ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TestIndizes), out errorState);
     136        double testMAE = OnlineMeanAbsoluteErrorCalculator.Calculate(EstimatedTestValues, ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TestIndizes), out errorState);
    137137        TestMeanAbsoluteError = errorState == OnlineCalculatorError.None ? testMAE : double.NaN;
    138138      }
     
    142142    protected void CalculateResults() {
    143143      double[] estimatedTrainingValues = EstimatedTrainingValues.ToArray(); // cache values
    144       double[] originalTrainingValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToArray();
     144      double[] originalTrainingValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndizes).ToArray();
    145145      double[] estimatedTestValues = EstimatedTestValues.ToArray(); // cache values
    146       double[] originalTestValues = ProblemData.Dataset.GetEnumeratedVariableValues(ProblemData.TargetVariable, ProblemData.TestIndizes).ToArray();
     146      double[] originalTestValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TestIndizes).ToArray();
    147147
    148148      OnlineCalculatorError errorState;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/TableFileParser.cs

    r5809 r6740  
    2121
    2222using System;
     23using System.Collections;
    2324using System.Collections.Generic;
    2425using System.Globalization;
     
    3334    private readonly char[] POSSIBLE_SEPARATORS = new char[] { ',', ';', '\t' };
    3435    private Tokenizer tokenizer;
    35     private List<List<double>> rowValues;
     36    private List<List<object>> rowValues;
    3637
    3738    private int rows;
     
    4748    }
    4849
    49     private double[,] values;
    50     public double[,] Values {
     50    private List<IList> values;
     51    public List<IList> Values {
    5152      get {
    5253        return values;
     
    6970
    7071    public TableFileParser() {
    71       rowValues = new List<List<double>>();
     72      rowValues = new List<List<object>>();
    7273      variableNames = new List<string>();
    7374    }
     
    7576    public void Parse(string fileName) {
    7677      NumberFormatInfo numberFormat;
     78      DateTimeFormatInfo dateTimeFormatInfo;
    7779      char separator;
    78       DetermineFileFormat(fileName, out numberFormat, out separator);
     80      DetermineFileFormat(fileName, out numberFormat, out dateTimeFormatInfo, out separator);
    7981      using (StreamReader reader = new StreamReader(fileName)) {
    80         tokenizer = new Tokenizer(reader, numberFormat, separator);
     82        tokenizer = new Tokenizer(reader, numberFormat, dateTimeFormatInfo, separator);
    8183        // parse the file
    8284        Parse();
     
    8688      rows = rowValues.Count;
    8789      columns = rowValues[0].Count;
    88       values = new double[rows, columns];
    89 
    90       int rowIndex = 0;
    91       int columnIndex = 0;
    92       foreach (List<double> row in rowValues) {
    93         columnIndex = 0;
    94         foreach (double element in row) {
    95           values[rowIndex, columnIndex++] = element;
    96         }
    97         rowIndex++;
    98       }
    99     }
    100 
    101     private void DetermineFileFormat(string fileName, out NumberFormatInfo numberFormat, out char separator) {
     90      values = new List<IList>();
     91
     92      //create columns
     93      for (int col = 0; col < columns; col++) {
     94        var types = rowValues.Select(r => r[col]).Where(v => v != null && v as string != string.Empty).Take(10).Select(v => v.GetType());
     95        if (!types.Any()) {
     96          values.Add(new List<string>());
     97          continue;
     98        }
     99
     100        var columnType = types.GroupBy(v => v).OrderBy(v => v).Last().Key;
     101        if (columnType == typeof(double)) values.Add(new List<double>());
     102        else if (columnType == typeof(DateTime)) values.Add(new List<DateTime>());
     103        else if (columnType == typeof(string)) values.Add(new List<string>());
     104        else throw new InvalidOperationException();
     105      }
     106
     107
     108
     109      //fill with values
     110      foreach (List<object> row in rowValues) {
     111        int columnIndex = 0;
     112        foreach (object element in row) {
     113          //handle missing values with default values
     114          if (element as string == string.Empty) {
     115            if (values[columnIndex] is List<double>) values[columnIndex].Add(double.NaN);
     116            else if (values[columnIndex] is List<DateTime>) values[columnIndex].Add(DateTime.MinValue);
     117            else if (values[columnIndex] is List<string>) values[columnIndex].Add(string.Empty);
     118            else throw new InvalidOperationException();
     119          } else values[columnIndex].Add(element);
     120          columnIndex++;
     121        }
     122      }
     123    }
     124
     125    private void DetermineFileFormat(string fileName, out NumberFormatInfo numberFormat, out DateTimeFormatInfo dateTimeFormatInfo, out char separator) {
    102126      using (StreamReader reader = new StreamReader(fileName)) {
    103127        // skip first line
     
    123147        if (OccurrencesOf(charCounts, '.') > 10) {
    124148          numberFormat = NumberFormatInfo.InvariantInfo;
     149          dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo;
    125150          separator = POSSIBLE_SEPARATORS
    126151            .Where(c => OccurrencesOf(charCounts, c) > 10)
     
    139164            // English format (only integer values) with ',' as separator
    140165            numberFormat = NumberFormatInfo.InvariantInfo;
     166            dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo;
    141167            separator = ',';
    142168          } else {
     
    144170            // German format (real values)
    145171            numberFormat = NumberFormatInfo.GetInstance(new CultureInfo("de-DE"));
     172            dateTimeFormatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("de-DE"));
    146173            separator = POSSIBLE_SEPARATORS
    147174              .Except(disallowedSeparators)
     
    154181          // no points and no commas => English format
    155182          numberFormat = NumberFormatInfo.InvariantInfo;
     183          dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo;
    156184          separator = POSSIBLE_SEPARATORS
    157185            .Where(c => OccurrencesOf(charCounts, c) > 10)
     
    169197    #region tokenizer
    170198    internal enum TokenTypeEnum {
    171       NewLine, Separator, String, Double
     199      NewLine, Separator, String, Double, DateTime
    172200    }
    173201
     
    176204      public string stringValue;
    177205      public double doubleValue;
     206      public DateTime dateTimeValue;
    178207
    179208      public Token(TokenTypeEnum type, string value) {
    180209        this.type = type;
    181210        stringValue = value;
     211        dateTimeValue = DateTime.MinValue;
    182212        doubleValue = 0.0;
    183213      }
     
    193223      private List<Token> tokens;
    194224      private NumberFormatInfo numberFormatInfo;
     225      private DateTimeFormatInfo dateTimeFormatInfo;
    195226      private char separator;
    196227      private const string INTERNAL_SEPARATOR = "#";
     
    218249      }
    219250
    220       public Tokenizer(StreamReader reader, NumberFormatInfo numberFormatInfo, char separator) {
     251      public Tokenizer(StreamReader reader, NumberFormatInfo numberFormatInfo, DateTimeFormatInfo dateTimeFormatInfo, char separator) {
    221252        this.reader = reader;
    222253        this.numberFormatInfo = numberFormatInfo;
     254        this.dateTimeFormatInfo = dateTimeFormatInfo;
    223255        this.separator = separator;
    224256        separatorToken = new Token(TokenTypeEnum.Separator, INTERNAL_SEPARATOR);
     
    264296          token.type = TokenTypeEnum.Double;
    265297          return token;
    266         }
    267 
    268         // couldn't parse the token as an int or float number so return a string token
     298        } else if (DateTime.TryParse(strToken, out token.dateTimeValue)) {
     299          token.type = TokenTypeEnum.DateTime;
     300          return token;
     301        }
     302
     303        // couldn't parse the token as an int or float number  or datetime value so return a string token
    269304        return token;
    270305      }
     
    299334    private void ParseValues() {
    300335      while (tokenizer.HasNext()) {
    301         List<double> row = new List<double>();
    302         row.Add(NextValue(tokenizer));
     336        List<object> row = new List<object>();
     337        object value = NextValue(tokenizer);
     338        if (value == null) { tokenizer.Next(); continue; }
     339        row.Add(value);
    303340        while (tokenizer.HasNext() && tokenizer.Peek() == tokenizer.SeparatorToken) {
    304341          Expect(tokenizer.SeparatorToken);
     
    312349            "\nLine " + tokenizer.CurrentLineNumber + " has " + row.Count + " columns.", "", tokenizer.CurrentLineNumber);
    313350        }
    314         // add the current row to the collection of rows and start a new row
    315351        rowValues.Add(row);
    316         row = new List<double>();
    317       }
    318     }
    319 
    320     private double NextValue(Tokenizer tokenizer) {
    321       if (tokenizer.Peek() == tokenizer.SeparatorToken || tokenizer.Peek() == tokenizer.NewlineToken) return double.NaN;
     352        row = new List<object>();
     353      }
     354    }
     355
     356    private object NextValue(Tokenizer tokenizer) {
     357      if (tokenizer.Peek() == tokenizer.SeparatorToken) return string.Empty;
     358      if (tokenizer.Peek() == tokenizer.NewlineToken) return null;
    322359      Token current = tokenizer.Next();
    323       if (current.type == TokenTypeEnum.Separator || current.type == TokenTypeEnum.String) {
     360      if (current.type == TokenTypeEnum.Separator) {
    324361        return double.NaN;
     362      } else if (current.type == TokenTypeEnum.String) {
     363        return current.stringValue;
    325364      } else if (current.type == TokenTypeEnum.Double) {
    326         // just take the value
    327365        return current.doubleValue;
     366      } else if (current.type == TokenTypeEnum.DateTime) {
     367        return current.dateTimeValue;
    328368      }
    329369      // found an unexpected token => throw error
     
    334374
    335375    private void ParseVariableNames() {
    336       // if the first line doesn't start with a double value then we assume that the
    337       // first line contains variable names
    338       if (tokenizer.HasNext() && tokenizer.Peek().type != TokenTypeEnum.Double) {
    339 
    340         List<Token> tokens = new List<Token>();
    341         Token valueToken;
     376      //if first token is double no variables names are given
     377      if (tokenizer.Peek().type == TokenTypeEnum.Double) return;
     378
     379      // the first line must contain variable names
     380      List<Token> tokens = new List<Token>();
     381      Token valueToken;
     382      valueToken = tokenizer.Next();
     383      tokens.Add(valueToken);
     384      while (tokenizer.HasNext() && tokenizer.Peek() == tokenizer.SeparatorToken) {
     385        Expect(tokenizer.SeparatorToken);
    342386        valueToken = tokenizer.Next();
    343         tokens.Add(valueToken);
    344         while (tokenizer.HasNext() && tokenizer.Peek() == tokenizer.SeparatorToken) {
    345           Expect(tokenizer.SeparatorToken);
    346           valueToken = tokenizer.Next();
    347           if (valueToken != tokenizer.NewlineToken) {
    348             tokens.Add(valueToken);
    349           }
    350         }
    351387        if (valueToken != tokenizer.NewlineToken) {
    352           Expect(tokenizer.NewlineToken);
    353         }
    354         variableNames = tokens.Select(x => x.stringValue.Trim()).ToList();
    355       }
     388          tokens.Add(valueToken);
     389        }
     390      }
     391      if (valueToken != tokenizer.NewlineToken) {
     392        Expect(tokenizer.NewlineToken);
     393      }
     394      variableNames = tokens.Select(x => x.stringValue.Trim()).ToList();
    356395    }
    357396
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Tests/OnlineCalculatorPerformanceTest.cs

    r5963 r6740  
    8080      watch.Start();
    8181      for (int i = 0; i < Repetitions; i++) {
    82         double value = calculateFunc(dataset.GetEnumeratedVariableValues(0), dataset.GetEnumeratedVariableValues(1), out errorState);
     82        double value = calculateFunc(dataset.GetDoubleValues("y"), dataset.GetDoubleValues("x0"), out errorState);
    8383      }
    8484      Assert.AreEqual(errorState, OnlineCalculatorError.None);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Tests/TableFileParserTest.cs

    r5809 r6740  
    2121
    2222using System;
    23 using System.Collections.Generic;
    24 using System.Linq;
    25 using Microsoft.VisualStudio.TestTools.UnitTesting;
    2623using System.IO;
    2724using HeuristicLab.Problems.DataAnalysis;
     25using Microsoft.VisualStudio.TestTools.UnitTesting;
    2826namespace HeuristicLab.Problems.DataAnalysis_3_4.Tests {
    2927
     
    4644        Assert.AreEqual(6, parser.Rows);
    4745        Assert.AreEqual(4, parser.Columns);
    48         Assert.AreEqual(parser.Values[0, 3], 3.14);
     46        Assert.AreEqual(parser.Values[3][0], 3.14);
    4947      }
    5048      finally {
     
    6866        Assert.AreEqual(6, parser.Rows);
    6967        Assert.AreEqual(4, parser.Columns);
    70         Assert.AreEqual(parser.Values[0, 3], 3.14);
     68        Assert.AreEqual(parser.Values[3][0], 3.14);
    7169      }
    7270      finally {
     
    9088        Assert.AreEqual(6, parser.Rows);
    9189        Assert.AreEqual(4, parser.Columns);
    92         Assert.AreEqual(parser.Values[0, 3], 3.14);
     90        Assert.AreEqual(parser.Values[3][0], 3.14);
    9391      }
    9492      finally {
     
    113111        Assert.AreEqual(6, parser.Rows);
    114112        Assert.AreEqual(4, parser.Columns);
    115         Assert.AreEqual(parser.Values[0, 3], 3.14);
     113        Assert.AreEqual(parser.Values[3][0], 3.14);
    116114      }
    117115      finally {
     
    135133        Assert.AreEqual(6, parser.Rows);
    136134        Assert.AreEqual(4, parser.Columns);
    137         Assert.AreEqual(parser.Values[0, 3], 3);
     135        Assert.AreEqual((double)parser.Values[3][0], 3);
    138136      }
    139137      finally {
     
    157155        Assert.AreEqual(6, parser.Rows);
    158156        Assert.AreEqual(4, parser.Columns);
    159         Assert.AreEqual(parser.Values[0, 3], 3);
     157        Assert.AreEqual((double)parser.Values[3][0], 3);
    160158      }
    161159      finally {
     
    179177        Assert.AreEqual(6, parser.Rows);
    180178        Assert.AreEqual(4, parser.Columns);
    181         Assert.AreEqual(parser.Values[0, 3], 3);
     179        Assert.AreEqual((double)parser.Values[3][0], 3);
    182180      }
    183181      finally {
     
    202200        Assert.AreEqual(6, parser.Rows);
    203201        Assert.AreEqual(4, parser.Columns);
    204         Assert.AreEqual(parser.Values[0, 3], 3);
     202        Assert.AreEqual((double)parser.Values[3][0], 3);
    205203      }
    206204      finally {
     
    225223        Assert.AreEqual(6, parser.Rows);
    226224        Assert.AreEqual(4, parser.Columns);
    227         Assert.AreEqual(parser.Values[0, 3], 3.14);
     225        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    228226      }
    229227      finally {
     
    248246        Assert.AreEqual(6, parser.Rows);
    249247        Assert.AreEqual(4, parser.Columns);
    250         Assert.AreEqual(parser.Values[0, 3], 3.14);
     248        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    251249      }
    252250      finally {
     
    270268        Assert.AreEqual(6, parser.Rows);
    271269        Assert.AreEqual(4, parser.Columns);
    272         Assert.AreEqual(parser.Values[0, 3], 3.14);
     270        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    273271      }
    274272      finally {
     
    292290        Assert.AreEqual(6, parser.Rows);
    293291        Assert.AreEqual(4, parser.Columns);
    294         Assert.AreEqual(parser.Values[0, 3], 3.14);
     292        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    295293      }
    296294      finally {
     
    314312        Assert.AreEqual(6, parser.Rows);
    315313        Assert.AreEqual(4, parser.Columns);
    316         Assert.AreEqual(parser.Values[0, 3], 3);
     314        Assert.AreEqual((double)parser.Values[3][0], 3);
    317315      }
    318316      finally {
     
    336334        Assert.AreEqual(6, parser.Rows);
    337335        Assert.AreEqual(4, parser.Columns);
    338         Assert.AreEqual(parser.Values[0, 3], 3);
     336        Assert.AreEqual((double)parser.Values[3][0], 3);
     337      }
     338      finally {
     339        File.Delete(tempFileName);
     340      }
     341    }
     342
     343    [TestMethod]
     344    public void ParseWithEmtpyLines() {
     345      string tempFileName = Path.GetTempFileName();
     346      WriteToFile(tempFileName,
     347"x01\t x02\t x03\t x04" + Environment.NewLine +
     348"0\t 0\t 0\t 3" + Environment.NewLine +
     349 Environment.NewLine +
     350"0\t 0\t 0\t 0" + Environment.NewLine +
     351" " + Environment.NewLine +
     352"0\t 0\t 0\t 0" + Environment.NewLine +
     353"0\t 0\t 0\t 0" + Environment.NewLine + Environment.NewLine);
     354      TableFileParser parser = new TableFileParser();
     355      try {
     356        parser.Parse(tempFileName);
     357        Assert.AreEqual(4, parser.Rows);
     358        Assert.AreEqual(4, parser.Columns);
    339359      }
    340360      finally {
     
    358378        Assert.AreEqual(6, parser.Rows);
    359379        Assert.AreEqual(4, parser.Columns);
    360         Assert.AreEqual(parser.Values[0, 3], 3.14);
     380        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    361381      }
    362382      finally {
     
    380400        Assert.AreEqual(6, parser.Rows);
    381401        Assert.AreEqual(4, parser.Columns);
    382         Assert.AreEqual(parser.Values[0, 3], 3.14);
     402        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    383403      }
    384404      finally {
     
    402422        Assert.AreEqual(6, parser.Rows);
    403423        Assert.AreEqual(4, parser.Columns);
    404         Assert.AreEqual(parser.Values[0, 3], 3.14);
     424        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    405425      }
    406426      finally {
     
    424444        Assert.AreEqual(6, parser.Rows);
    425445        Assert.AreEqual(4, parser.Columns);
    426         Assert.AreEqual(parser.Values[0, 3], 3.14);
     446        Assert.AreEqual((double)parser.Values[3][0], 3.14);
    427447      }
    428448      finally {
     
    446466        Assert.AreEqual(6, parser.Rows);
    447467        Assert.AreEqual(4, parser.Columns);
    448         Assert.AreEqual(parser.Values[0, 3], 3);
     468        Assert.AreEqual((double)parser.Values[3][0], 3);
    449469      }
    450470      finally {
     
    468488        Assert.AreEqual(6, parser.Rows);
    469489        Assert.AreEqual(4, parser.Columns);
    470         Assert.AreEqual(parser.Values[0, 3], 3);
     490        Assert.AreEqual((double)parser.Values[3][0], 3);
    471491      }
    472492      finally {
Note: See TracChangeset for help on using the changeset viewer.