Free cookie consent management tool by TermsFeed Policy Generator

Changeset 7129


Ignore:
Timestamp:
12/05/11 20:17:59 (13 years ago)
Author:
gkronber
Message:

#1081 worked on multi-variate time series prognosis

Location:
branches/HeuristicLab.TimeSeries
Files:
1 added
13 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis.Views/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis.Views-3.4.csproj

    r7120 r7129  
    110110  </ItemGroup>
    111111  <ItemGroup>
     112    <Compile Include="InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView.cs">
     113      <SubType>UserControl</SubType>
     114    </Compile>
     115    <Compile Include="InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView.Designer.cs">
     116      <DependentUpon>InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView.cs</DependentUpon>
     117    </Compile>
    112118    <Compile Include="Plugin.cs" />
     119    <Compile Include="SymbolicTimeSeriesPrognosisSolutionView.cs">
     120      <SubType>UserControl</SubType>
     121    </Compile>
     122    <Compile Include="SymbolicTimeSeriesPrognosisSolutionView.Designer.cs">
     123      <DependentUpon>SymbolicTimeSeriesPrognosisSolutionView.cs</DependentUpon>
     124    </Compile>
    113125    <None Include="HeuristicLab.snk" />
    114126    <None Include="Plugin.cs.frame" />
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis.Views/3.4/InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView.cs

    r6808 r7129  
    5050
    5151    protected override void UpdateModel(ISymbolicExpressionTree tree) {
    52       var model = new SymbolicTimeSeriesPrognosisModel(tree, Content.Model.Interpreter);
     52      var model = new SymbolicTimeSeriesPrognosisModel(tree, Content.Model.Interpreter, Content.ProblemData.TargetVariables.ToArray());
    5353      SymbolicTimeSeriesPrognosisModel.Scale(model, Content.ProblemData);
    5454      Content.Model = model;
     
    6767      var dataset = Content.ProblemData.Dataset;
    6868      var rows = Content.ProblemData.TrainingIndizes;
    69       string targetVariable = Content.ProblemData.TargetVariable;
    70       Dictionary<ISymbolicExpressionTreeNode, double> impactValues = new Dictionary<ISymbolicExpressionTreeNode, double>();
    71       List<ISymbolicExpressionTreeNode> nodes = tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPostfix().ToList();
    72       var originalOutput = interpreter.GetSymbolicExpressionTreeValues(tree, dataset, rows)
     69      Dictionary<ISymbolicExpressionTreeNode, double> impactValues =
     70        new Dictionary<ISymbolicExpressionTreeNode, double>();
     71      var originalOutput = interpreter.GetSymbolicExpressionTreeValues(tree, dataset, Content.ProblemData.TargetVariables.ToArray(), rows, 1)
    7372        .ToArray();
    74       var targetValues = dataset.GetDoubleValues(targetVariable, rows);
    75       OnlineCalculatorError errorState;
    76       double originalR2 = OnlinePearsonsRSquaredCalculator.Calculate(targetValues, originalOutput, out errorState);
    77       if (errorState != OnlineCalculatorError.None) originalR2 = 0.0;
     73      int i = 0;
     74      foreach (var targetVariable in Content.ProblemData.TargetVariables) {
     75        List<ISymbolicExpressionTreeNode> nodes = tree.Root.GetSubtree(0).GetSubtree(i).IterateNodesPostfix().ToList();
     76        var targetValues = dataset.GetDoubleValues(targetVariable, rows);
     77        OnlineCalculatorError errorState;
     78        double originalR2 = OnlinePearsonsRSquaredCalculator.Calculate(targetValues, originalOutput.Select(v => v.ElementAt(i).First()), out errorState);
     79        if (errorState != OnlineCalculatorError.None) originalR2 = 0.0;
    7880
    79       foreach (ISymbolicExpressionTreeNode node in nodes) {
    80         var parent = node.Parent;
    81         constantNode.Value = CalculateReplacementValue(node, tree);
    82         ISymbolicExpressionTreeNode replacementNode = constantNode;
    83         SwitchNode(parent, node, replacementNode);
    84         var newOutput = interpreter.GetSymbolicExpressionTreeValues(tree, dataset, rows);
    85         double newR2 = OnlinePearsonsRSquaredCalculator.Calculate(targetValues, newOutput, out errorState);
    86         if (errorState != OnlineCalculatorError.None) newR2 = 0.0;
     81        foreach (ISymbolicExpressionTreeNode node in nodes) {
     82          var parent = node.Parent;
     83          constantNode.Value = CalculateReplacementValue(node, tree);
     84          ISymbolicExpressionTreeNode replacementNode = constantNode;
     85          SwitchNode(parent, node, replacementNode);
     86          var newOutput = interpreter.GetSymbolicExpressionTreeValues(tree, dataset, Content.ProblemData.TargetVariables.ToArray(), rows, 1);
     87          double newR2 = OnlinePearsonsRSquaredCalculator.Calculate(targetValues, newOutput.Select(v => v.ElementAt(i).First()), out errorState);
     88          if (errorState != OnlineCalculatorError.None) newR2 = 0.0;
    8789
    88         // impact = 0 if no change
    89         // impact < 0 if new solution is better
    90         // impact > 0 if new solution is worse
    91         impactValues[node] = originalR2 - newR2;
    92         SwitchNode(parent, replacementNode, node);
     90          // impact = 0 if no change
     91          // impact < 0 if new solution is better
     92          // impact > 0 if new solution is worse
     93          impactValues[node] = originalR2 - newR2;
     94          SwitchNode(parent, replacementNode, node);
     95        }
     96        i++;
    9397      }
    9498      return impactValues;
     
    107111      var interpreter = Content.Model.Interpreter;
    108112      var rows = Content.ProblemData.TrainingIndizes;
    109       return interpreter.GetSymbolicExpressionTreeValues(tempTree, Content.ProblemData.Dataset, rows).Median();
     113      var allPrognosedValues = interpreter.GetSymbolicExpressionTreeValues(tempTree, Content.ProblemData.Dataset, Content.ProblemData.TargetVariables.ToArray(), rows, 1);
     114     
     115      return allPrognosedValues.Select(x=>x.First().First()).Median();
    110116    }
    111117
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis-3.4.csproj

    r7120 r7129  
    117117    <Compile Include="Plugin.cs" />
    118118    <Compile Include="SingleObjective\SymbolicTimeSeriesPrognosisSingleObjectiveEvaluator.cs" />
    119     <Compile Include="SingleObjective\SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator.cs" />
    120     <Compile Include="SingleObjective\SymbolicTimeSeriesPrognosisSingleObjectivePearsonRSquaredEvaluator.cs" />
     119    <Compile Include="SingleObjective\SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator.cs">
     120      <SubType>Code</SubType>
     121    </Compile>
    121122    <Compile Include="SingleObjective\SymbolicTimeSeriesPrognosisSingleObjectiveProblem.cs" />
    122123    <Compile Include="SingleObjective\SymbolicTimeSeriesPrognosisSingleObjectiveTrainingBestSolutionAnalyzer.cs" />
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/Interfaces/ISymbolicTimeSeriesPrognosisModel.cs

    r7120 r7129  
    2222using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2323namespace HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis {
    24   public interface ISymbolicTimeSeriesPrognosisModel : ITimeSeriesPrognosisModel {
    25     ISymbolicExpressionTree SymbolicExpressionTree { get; }
     24  public interface ISymbolicTimeSeriesPrognosisModel : ITimeSeriesPrognosisModel, ISymbolicDataAnalysisModel {
    2625    ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter Interpreter { get; }
    2726  }
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/SingleObjective/SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator.cs

    r7120 r7129  
    6161
    6262    public static double Calculate(ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, ITimeSeriesPrognosisProblemData problemData, IEnumerable<int> rows, int horizon) {
    63       var allPredictedContinuations = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, problemData.TargetVariables.ToArray(), rows, horizon);
    64       var meanCalculator = new OnlineMeanAndVarianceCalculator();
    65       var allPredictedContinuationsEnumerator = allPredictedContinuations.GetEnumerator();
    66       foreach (var targetVariable in problemData.TargetVariables) {
    67         if (!allPredictedContinuationsEnumerator.MoveNext()) throw new InvalidOperationException();
    68         var actualContinuations = from r in rows
    69                                   select problemData.Dataset.GetDoubleValues(targetVariable, Enumerable.Range(r, horizon));
    70         var actualContinuationsEnumerator = actualContinuations.GetEnumerator();
    71         var predictedContinuationsEnumerator = allPredictedContinuationsEnumerator.Current.GetEnumerator();
    72         while (actualContinuationsEnumerator.MoveNext() & predictedContinuationsEnumerator.MoveNext()) {
    73           OnlineCalculatorError errorState;
    74           meanCalculator.Add(OnlineMeanSquaredErrorCalculator.Calculate(predictedContinuationsEnumerator.Current.LimitToRange(lowerEstimationLimit, upperEstimationLimit),
    75                                                                         actualContinuationsEnumerator.Current, out errorState));
    76           if (errorState != OnlineCalculatorError.None) return double.NaN;
     63      double[] alpha;
     64      double[] beta;
     65      DetermineScalingFactors(solution, problemData, interpreter, rows, out alpha, out beta);
     66      var scaledSolution = Scale(solution, alpha, beta);
     67
     68      var meanSquaredErrorCalculators = Enumerable.Range(0, problemData.TargetVariables.Count())
     69        .Select(i => new OnlineMeanSquaredErrorCalculator()).ToArray();
     70
     71      var allPredictedContinuations = interpreter.GetSymbolicExpressionTreeValues(scaledSolution, problemData.Dataset,
     72                                                                                  problemData.TargetVariables.ToArray(),
     73                                                                                  rows, horizon);
     74      var allContinuationsEnumerator = allPredictedContinuations.GetEnumerator();
     75      var rowsEnumerator = rows.GetEnumerator();
     76      while (allContinuationsEnumerator.MoveNext() & rowsEnumerator.MoveNext()) {
     77        var componentEnumerator = allContinuationsEnumerator.Current.GetEnumerator();
     78        var mseCalculatorsEnumerator = meanSquaredErrorCalculators.AsEnumerable().GetEnumerator();
     79        var targetVarEnumerator = problemData.TargetVariables.GetEnumerator();
     80        while (componentEnumerator.MoveNext() & mseCalculatorsEnumerator.MoveNext() & targetVarEnumerator.MoveNext()) {
     81          var stepEnumerator = componentEnumerator.Current.GetEnumerator();
     82          var actualContinuationEnumerator = problemData.Dataset.GetDoubleValues(targetVarEnumerator.Current,
     83                                                                       Enumerable.Range(rowsEnumerator.Current, horizon)).GetEnumerator();
     84          while (stepEnumerator.MoveNext() & actualContinuationEnumerator.MoveNext()) {
     85            double e = Math.Min(upperEstimationLimit, Math.Max(lowerEstimationLimit, stepEnumerator.Current));
     86            mseCalculatorsEnumerator.Current.Add(actualContinuationEnumerator.Current, e);
     87            if (mseCalculatorsEnumerator.Current.ErrorState == OnlineCalculatorError.InvalidValueAdded)
     88              return double.NaN;
     89          }
    7790        }
    7891      }
    79       return meanCalculator.Mean;
     92      var meanCalculator = new OnlineMeanAndVarianceCalculator();
     93      foreach (var calc in meanSquaredErrorCalculators) {
     94        if (calc.ErrorState != OnlineCalculatorError.None) return double.NaN;
     95        meanCalculator.Add(calc.MeanSquaredError);
     96      }
     97      //int i = 0;
     98      //foreach (var targetVariable in problemData.TargetVariables) {
     99      //  var predictedContinuations = allPredictedContinuations.Select(v => v.ElementAt(i));
     100      //  for (int h = 0; h < horizon; h++) {
     101      //    OnlineCalculatorError errorState;
     102      //    meanCalculator.Add(OnlineMeanSquaredErrorCalculator.Calculate(predictedContinuations
     103      //                                                                    .Select(x => x.ElementAt(h))
     104      //                                                                    .LimitToRange(lowerEstimationLimit,
     105      //                                                                                  upperEstimationLimit),
     106      //                                                                  actualContinuations.Select(x => x.ElementAt(h)),
     107      //                                                                  out errorState));
     108      //    if (errorState != OnlineCalculatorError.None) return double.NaN;
     109      //  }
     110      //}
     111      return meanCalculator.MeanErrorState == OnlineCalculatorError.None ? meanCalculator.Mean : double.NaN;
     112    }
     113
     114    private static ISymbolicExpressionTree Scale(ISymbolicExpressionTree solution, double[] alpha, double[] beta) {
     115      var clone = (ISymbolicExpressionTree)solution.Clone();
     116      int n = alpha.Length;
     117      for (int i = 0; i < n; i++) {
     118        var parent = clone.Root.GetSubtree(0);
     119        var rpb = clone.Root.GetSubtree(0).GetSubtree(i);
     120        var scaledRpb = MakeSum(
     121          MakeProduct(rpb,
     122            MakeConstant(beta[i], clone.Root.Grammar), clone.Root.Grammar),
     123            MakeConstant(alpha[i], clone.Root.Grammar), clone.Root.Grammar);
     124        parent.RemoveSubtree(i);
     125        parent.InsertSubtree(i, scaledRpb);
     126      }
     127      return clone;
     128    }
     129
     130    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, ISymbolicExpressionTreeGrammar grammar) {
     131      var sum = grammar.Symbols.Where(s => s is Addition).First().CreateTreeNode();
     132      sum.AddSubtree(a);
     133      sum.AddSubtree(b);
     134      return sum;
     135    }
     136
     137    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, ISymbolicExpressionTreeGrammar grammar) {
     138      var prod = grammar.Symbols.Where(s => s is Multiplication).First().CreateTreeNode();
     139      prod.AddSubtree(a);
     140      prod.AddSubtree(b);
     141      return prod;
     142    }
     143
     144    private static ISymbolicExpressionTreeNode MakeConstant(double c, ISymbolicExpressionTreeGrammar grammar) {
     145      var node = (ConstantTreeNode)grammar.Symbols.Where(s => s is Constant).First().CreateTreeNode();
     146      node.Value = c;
     147      return node;
     148    }
     149
     150    private static void DetermineScalingFactors(ISymbolicExpressionTree solution, ITimeSeriesPrognosisProblemData problemData, ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, IEnumerable<int> rows, out double[] alpha, out double[] beta) {
     151      string[] targetVariables = problemData.TargetVariables.ToArray();
     152      int nComponents = targetVariables.Length;
     153      alpha = new double[nComponents];
     154      beta = new double[nComponents];
     155      var oneStepPredictions = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset,
     156                                                                     targetVariables, rows,
     157                                                                     1);
     158      for (int i = 0; i < nComponents; i++) {
     159        var target = problemData.Dataset.GetDoubleValues(targetVariables[i], rows);
     160        var prediction = oneStepPredictions.Select(v => v.ElementAt(i).First());
     161        OnlineCalculatorError errorState;
     162        OnlineLinearScalingParameterCalculator.Calculate(prediction, target, out alpha[i], out beta[i], out errorState);
     163        if (errorState != OnlineCalculatorError.None) {
     164          alpha[i] = 0;
     165          beta[i] = 1;
     166        }
     167      }
    80168    }
    81169
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/SingleObjective/SymbolicTimeSeriesPrognosisSingleObjectiveProblem.cs

    r7120 r7129  
    5252
    5353    public SymbolicTimeSeriesPrognosisSingleObjectiveProblem()
    54       : base(new TimeSeriesPrognosisProblemData(), new SymbolicTimeSeriesPrognosisSingleObjectivePearsonRSquaredEvaluator(), new SymbolicDataAnalysisExpressionTreeCreator()) {
     54      : base(new TimeSeriesPrognosisProblemData(), new SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator(), new SymbolicDataAnalysisExpressionTreeCreator()) {
    5555      Parameters.Add(new FixedValueParameter<DoubleLimit>(EstimationLimitsParameterName, EstimationLimitsParameterDescription));
    5656
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/SymbolicTimeSeriesPrognosisModel.cs

    r7120 r7129  
    5353    }
    5454
     55    ISymbolicDataAnalysisExpressionTreeInterpreter ISymbolicDataAnalysisModel.Interpreter {
     56      get { return (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter; }
     57    }
     58
    5559    #endregion
    5660
     
    102106        double beta;
    103107        OnlineCalculatorError errorState;
    104         OnlineLinearScalingParameterCalculator.Calculate(estimatedValues[i].Select(x => x.First()), targetValues,
     108        OnlineLinearScalingParameterCalculator.Calculate(estimatedValues.Select(x => x.ElementAt(i).First()), targetValues,
    105109          out alpha, out beta, out errorState);
    106         if (errorState != OnlineCalculatorError.None) return;
     110        if (errorState != OnlineCalculatorError.None) continue;
    107111
    108112        ConstantTreeNode alphaTreeNode = null;
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeILEmittingInterpreter.cs

    r7120 r7129  
    179179
    180180    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
     181      return from prog in GetSymbolicExpressionTreeValues(tree, dataset, new string[] { "#NOTHING#" }, rows, 1)
     182             select prog.First().First();
     183    }
     184
     185    // for each row for each target variable one prognosis (=enumerable of future values)
     186    public IEnumerable<IEnumerable<IEnumerable<double>>> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, Dataset dataset, string[] targetVariables, IEnumerable<int> rows, int horizon) {
    181187      if (CheckExpressionsWithIntervalArithmetic.Value)
    182188        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
     
    186192
    187193      Dictionary<string, int> doubleVariableNames = dataset.DoubleVariables.Select((x, i) => new { x, i }).ToDictionary(e => e.x, e => e.i);
    188       IList<double>[] columns = (from v in doubleVariableNames.Keys
    189                                  select dataset.GetReadOnlyDoubleValues(v))
    190                                 .ToArray();
    191194
    192195      for (int i = 0; i < code.Length; i++) {
     
    208211      }
    209212      var state = new InterpreterState(code);
    210 
    211213      Type[] methodArgs = { typeof(int), typeof(IList<double>[]) };
    212       DynamicMethod testFun = new DynamicMethod("TestFun", typeof(double), methodArgs, typeof(SymbolicDataAnalysisExpressionTreeILEmittingInterpreter).Module);
    213 
    214       ILGenerator il = testFun.GetILGenerator();
    215       CompileInstructions(il, state, dataset);
    216       il.Emit(System.Reflection.Emit.OpCodes.Conv_R8);
    217       il.Emit(System.Reflection.Emit.OpCodes.Ret);
    218       var function = (CompiledFunction)testFun.CreateDelegate(typeof(CompiledFunction));
    219 
    220       foreach (var row in rows) {
    221         yield return function(row, columns);
    222       }
    223     }
    224     public IEnumerable<IEnumerable<IEnumerable<double>>> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, Dataset dataset, string[] targetVariables, IEnumerable<int> rows, int horizon) {
    225       throw new NotImplementedException();
     214
     215      CompiledFunction[] function = new CompiledFunction[targetVariables.Length];
     216      for (int i = 0; i < function.Length; i++) {
     217        DynamicMethod testFun = new DynamicMethod("TestFun", typeof(double), methodArgs, typeof(SymbolicDataAnalysisExpressionTreeILEmittingInterpreter).Module);
     218        ILGenerator il = testFun.GetILGenerator();
     219        CompileInstructions(il, state, dataset);
     220        il.Emit(System.Reflection.Emit.OpCodes.Conv_R8);
     221        il.Emit(System.Reflection.Emit.OpCodes.Ret);
     222        function[i] = (CompiledFunction)testFun.CreateDelegate(typeof(CompiledFunction));
     223      }
     224      int nComponents = tree.Root.GetSubtree(0).SubtreeCount;
     225      // produce a n-step forecast for each target variable for all rows
     226      var values = doubleVariableNames.Keys
     227        .Select(v => targetVariables.Contains(v) ?
     228          (IList<double>)dataset.GetDoubleValues(v).ToList() :
     229          dataset.GetReadOnlyDoubleValues(v))
     230        .Concat(new List<double>[] { Enumerable.Repeat(0.0, dataset.Rows).ToList() }) // append list for calculated target variable
     231        .ToArray();
     232      doubleVariableNames.Add("#NOTHING#", values.Count() - 1);
     233      foreach (var rowEnum in rows) {
     234        int row = rowEnum;
     235        foreach (var horizonRow in Enumerable.Range(row, horizon)) {
     236          for (int i = 0; i < nComponents; i++) {
     237            var componentProg = function[i](horizonRow, values);
     238            // set cachedValues for prognosis of future values
     239            values[doubleVariableNames[targetVariables[i]]][horizonRow] = componentProg;
     240          }
     241        }
     242
     243        yield return from component in Enumerable.Range(0, nComponents)
     244                     select from horizonRow in Enumerable.Range(row, horizon)
     245                            select values[doubleVariableNames[targetVariables[component]]][horizonRow];
     246        // reset start value
     247        foreach (var v in targetVariables) {
     248          if (v != "#NOTHING#")
     249            values[doubleVariableNames[v]][row] = dataset.GetDoubleValue(v, row);
     250        }
     251      }
    226252    }
    227253
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Views/3.4/HeuristicLab.Problems.DataAnalysis.Views-3.4.csproj

    r7100 r7129  
    257257      <DependentUpon>RegressionSolutionScatterPlotView.cs</DependentUpon>
    258258    </Compile>
     259    <Compile Include="TimeSeriesPrognosis\TimeSeriesPrognosisSolutionLineChartView.cs">
     260      <SubType>UserControl</SubType>
     261    </Compile>
     262    <Compile Include="TimeSeriesPrognosis\TimeSeriesPrognosisSolutionLineChartView.Designer.cs">
     263      <DependentUpon>TimeSeriesPrognosisSolutionLineChartView.cs</DependentUpon>
     264    </Compile>
    259265    <Compile Include="TimeSeriesPrognosis\TimeSeriesPrognosisSolutionPrognosedValuesView.cs">
    260266      <SubType>UserControl</SubType>
     
    378384    </BootstrapperPackage>
    379385  </ItemGroup>
    380   <ItemGroup />
     386  <ItemGroup>
     387    <EmbeddedResource Include="TimeSeriesPrognosis\TimeSeriesPrognosisSolutionLineChartView.resx">
     388      <DependentUpon>TimeSeriesPrognosisSolutionLineChartView.cs</DependentUpon>
     389    </EmbeddedResource>
     390  </ItemGroup>
    381391  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
    382392  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Views/3.4/TimeSeriesPrognosis/TimeSeriesPrognosisSolutionLineChartView.Designer.cs

    r6802 r7129  
    4444    /// </summary>
    4545    private void InitializeComponent() {
    46       System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
    47       System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
     46      System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea2 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
     47      System.Windows.Forms.DataVisualization.Charting.Legend legend2 = new System.Windows.Forms.DataVisualization.Charting.Legend();
    4848      this.chart = new HeuristicLab.Visualization.ChartControlsExtensions.EnhancedChart();
     49      this.targetVariableComboBox = new System.Windows.Forms.ComboBox();
     50      this.label = new System.Windows.Forms.Label();
     51      this.prognosedValuesCheckbox = new System.Windows.Forms.CheckBox();
    4952      ((System.ComponentModel.ISupportInitialize)(this.chart)).BeginInit();
    5053      this.SuspendLayout();
     
    5255      // chart
    5356      //
    54       chartArea1.Name = "ChartArea";
    55       this.chart.ChartAreas.Add(chartArea1);
    56       this.chart.Dock = System.Windows.Forms.DockStyle.Fill;
    57       legend1.Alignment = System.Drawing.StringAlignment.Center;
    58       legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
    59       legend1.Name = "Default";
    60       this.chart.Legends.Add(legend1);
    61       this.chart.Location = new System.Drawing.Point(0, 0);
     57      this.chart.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     58                  | System.Windows.Forms.AnchorStyles.Left)
     59                  | System.Windows.Forms.AnchorStyles.Right)));
     60      chartArea2.Name = "ChartArea";
     61      this.chart.ChartAreas.Add(chartArea2);
     62      legend2.Alignment = System.Drawing.StringAlignment.Center;
     63      legend2.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
     64      legend2.Name = "Default";
     65      this.chart.Legends.Add(legend2);
     66      this.chart.Location = new System.Drawing.Point(0, 31);
    6267      this.chart.Name = "chart";
    63       this.chart.Size = new System.Drawing.Size(358, 225);
     68      this.chart.Size = new System.Drawing.Size(388, 194);
    6469      this.chart.TabIndex = 0;
    6570      this.chart.CustomizeLegend += new System.EventHandler<System.Windows.Forms.DataVisualization.Charting.CustomizeLegendEventArgs>(this.chart_CustomizeLegend);
     
    6873      this.chart.MouseMove += new System.Windows.Forms.MouseEventHandler(this.chart_MouseMove);
    6974      //
     75      // targetVariableComboBox
     76      //
     77      this.targetVariableComboBox.FormattingEnabled = true;
     78      this.targetVariableComboBox.Location = new System.Drawing.Point(91, 4);
     79      this.targetVariableComboBox.Name = "targetVariableComboBox";
     80      this.targetVariableComboBox.Size = new System.Drawing.Size(173, 21);
     81      this.targetVariableComboBox.TabIndex = 1;
     82      this.targetVariableComboBox.SelectedIndexChanged += new System.EventHandler(this.targetVariableComboBox_SelectedIndexChanged);
     83      //
     84      // label
     85      //
     86      this.label.AutoSize = true;
     87      this.label.Location = new System.Drawing.Point(4, 7);
     88      this.label.Name = "label";
     89      this.label.Size = new System.Drawing.Size(81, 13);
     90      this.label.TabIndex = 2;
     91      this.label.Text = "Target variable:";
     92      //
     93      // prognosedValuesCheckbox
     94      //
     95      this.prognosedValuesCheckbox.AutoSize = true;
     96      this.prognosedValuesCheckbox.Checked = true;
     97      this.prognosedValuesCheckbox.CheckState = System.Windows.Forms.CheckState.Checked;
     98      this.prognosedValuesCheckbox.Location = new System.Drawing.Point(271, 7);
     99      this.prognosedValuesCheckbox.Name = "prognosedValuesCheckbox";
     100      this.prognosedValuesCheckbox.Size = new System.Drawing.Size(112, 17);
     101      this.prognosedValuesCheckbox.TabIndex = 3;
     102      this.prognosedValuesCheckbox.Text = "Prognosed Values";
     103      this.prognosedValuesCheckbox.UseVisualStyleBackColor = true;
     104      this.prognosedValuesCheckbox.CheckedChanged += new System.EventHandler(this.prognosedValuesCheckbox_CheckedChanged);
     105      //
    70106      // TimeSeriesPrognosisSolutionLineChartView
    71107      //
     
    73109      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    74110      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
     111      this.Controls.Add(this.prognosedValuesCheckbox);
     112      this.Controls.Add(this.label);
     113      this.Controls.Add(this.targetVariableComboBox);
    75114      this.Controls.Add(this.chart);
    76115      this.Name = "TimeSeriesPrognosisSolutionLineChartView";
    77       this.Size = new System.Drawing.Size(358, 225);
     116      this.Size = new System.Drawing.Size(388, 225);
    78117      ((System.ComponentModel.ISupportInitialize)(this.chart)).EndInit();
    79118      this.ResumeLayout(false);
     119      this.PerformLayout();
    80120
    81121    }
     
    84124
    85125    private HeuristicLab.Visualization.ChartControlsExtensions.EnhancedChart chart;
     126    private System.Windows.Forms.ComboBox targetVariableComboBox;
     127    private System.Windows.Forms.Label label;
     128    private System.Windows.Forms.CheckBox prognosedValuesCheckbox;
    86129  }
    87130}
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Views/3.4/TimeSeriesPrognosis/TimeSeriesPrognosisSolutionLineChartView.cs

    r6802 r7129  
    3636    private const string PROGNOSEDVALUES_TEST_SERIES_NAME = "Prognosed Values (test)";
    3737    private const string PROGNOSEDVALUES_ALL_SERIES_NAME = "Prognosed Values (all samples)";
     38    private string prevTargetVariable;
    3839
    3940    public new ITimeSeriesPrognosisSolution Content {
     
    5758    }
    5859
     60    private void UpdateTargetVariables() {
     61      // populate combobox
     62      targetVariableComboBox.Items.Clear();
     63      if (Content != null) {
     64        foreach (var targetVariable in Content.ProblemData.TargetVariables)
     65          targetVariableComboBox.Items.Add(targetVariable);
     66
     67        targetVariableComboBox.SelectedIndex = 0;
     68      }
     69    }
     70
     71
     72
    5973    private void RedrawChart() {
    6074      this.chart.Series.Clear();
     
    6276        this.chart.ChartAreas[0].AxisX.Minimum = 0;
    6377        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
     78        string targetVariable = (string)targetVariableComboBox.SelectedItem;
     79        int varIndex = Content.ProblemData.TargetVariables.ToList().IndexOf(targetVariable);
    6480
    6581        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
    66         this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = Content.ProblemData.TargetVariable;
     82        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = targetVariable;
    6783        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    6884        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
    69           Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
     85          Content.ProblemData.Dataset.GetDoubleValues(targetVariable).ToArray());
    7086
    7187        this.chart.Series.Add(PROGNOSEDVALUES_TRAINING_SERIES_NAME);
    7288        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].LegendText = PROGNOSEDVALUES_TRAINING_SERIES_NAME;
    7389        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    74         this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TrainingIndizes.ToArray(), Content.PrognosedTrainingValues.ToArray());
     90        if (prognosedValuesCheckbox.Checked) {
     91          this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points
     92            .DataBindXY(Content.ProblemData.TrainingIndizes.ToArray(),
     93                        Content.PrognosedTrainingValues.ElementAt(varIndex).ToArray());
     94        } else {
     95          this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points
     96            .DataBindXY(Content.ProblemData.TrainingIndizes.ToArray(),
     97                        Content.GetPrognosedValues(Content.ProblemData.TrainingIndizes, 1).Select(v => v.ElementAt(varIndex).First()).ToArray());
     98        }
    7599        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
    76100        this.chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, PROGNOSEDVALUES_TRAINING_SERIES_NAME);
     
    82106        this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].LegendText = PROGNOSEDVALUES_TEST_SERIES_NAME;
    83107        this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    84         this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TestIndizes.ToArray(), Content.PrognosedTestValues.ToArray());
     108        if (prognosedValuesCheckbox.Checked) {
     109          this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points
     110            .DataBindXY(Content.ProblemData.TestIndizes.ToArray(),
     111                        Content.PrognosedTestValues.ElementAt(varIndex).ToArray());
     112        } else {
     113          this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points
     114            .DataBindXY(Content.ProblemData.TestIndizes.ToArray(),
     115                        Content.GetPrognosedValues(Content.ProblemData.TestIndizes, 1).Select(
     116                          v => v.ElementAt(varIndex).First()).ToArray());
     117        }
    85118        this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Tag = Content;
    86 
    87 
    88         int[] allIndizes = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).Except(Content.ProblemData.TrainingIndizes).Except(Content.ProblemData.TestIndizes).ToArray();
    89         var estimatedValues = Content.PrognosedValues.ToArray();
    90         List<double> allEstimatedValues = allIndizes.Select(index => estimatedValues[index]).ToList();
    91 
    92         this.chart.Series.Add(PROGNOSEDVALUES_ALL_SERIES_NAME);
    93         this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME].LegendText = PROGNOSEDVALUES_ALL_SERIES_NAME;
    94         this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    95         this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIndizes, allEstimatedValues);
    96         this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME].Tag = Content;
    97         this.chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, PROGNOSEDVALUES_ALL_SERIES_NAME);
    98         this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.BorderWidth = 0;
    99         this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.MarkerStyle = MarkerStyle.None;
    100         this.ToggleSeriesData(this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME]);
    101119
    102120        UpdateCursorInterval();
     
    130148    protected override void OnContentChanged() {
    131149      base.OnContentChanged();
     150      UpdateTargetVariables();
     151    }
     152
     153    private void Content_ProblemDataChanged(object sender, EventArgs e) {
     154      UpdateTargetVariables();
     155    }
     156    private void Content_ModelChanged(object sender, EventArgs e) {
    132157      RedrawChart();
    133158    }
    134     private void Content_ProblemDataChanged(object sender, EventArgs e) {
     159
     160    private void targetVariableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
    135161      RedrawChart();
    136162    }
    137     private void Content_ModelChanged(object sender, EventArgs e) {
     163    private void prognosedValuesCheckbox_CheckedChanged(object sender, EventArgs e) {
    138164      RedrawChart();
    139165    }
     
    207233        }
    208234      } else if (Content != null) {
    209         string targetVariableName = Content.ProblemData.TargetVariable;
     235        string targetVariable = (string)targetVariableComboBox.SelectedItem;
     236        int varIndex = Content.ProblemData.TargetVariables.ToList().IndexOf(targetVariable);
     237
    210238
    211239        IEnumerable<int> indizes = null;
    212240        IEnumerable<double> predictedValues = null;
    213241        switch (series.Name) {
    214           case PROGNOSEDVALUES_ALL_SERIES_NAME:
    215             indizes = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).Except(Content.ProblemData.TrainingIndizes).Except(Content.ProblemData.TestIndizes).ToArray();
    216             var estimatedValues = Content.PrognosedValues.ToArray();
    217             predictedValues = indizes.Select(index => estimatedValues[index]).ToList();
    218             break;
    219242          case PROGNOSEDVALUES_TRAINING_SERIES_NAME:
    220243            indizes = Content.ProblemData.TrainingIndizes.ToArray();
    221             predictedValues = Content.PrognosedTrainingValues.ToArray();
     244            predictedValues = Content.PrognosedTrainingValues.ElementAt(varIndex).ToArray();
    222245            break;
    223246          case PROGNOSEDVALUES_TEST_SERIES_NAME:
    224247            indizes = Content.ProblemData.TestIndizes.ToArray();
    225             predictedValues = Content.PrognosedTestValues.ToArray();
     248            predictedValues = Content.PrognosedTestValues.ElementAt(varIndex).ToArray();
    226249            break;
    227250        }
     
    255278      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
    256279    }
     280
    257281  }
    258282}
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicDataAnalysisExpressionTreeInterpreterTest.cs

    r6866 r7129  
    2424using System.Globalization;
    2525using System.Linq;
     26using HeuristicLab.Encodings.IntegerVectorEncoding;
    2627using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2728using HeuristicLab.Random;
     
    339340      Evaluate(interpreter, ds, "(lag -1.0 (* (lagVariable 1.0 a 1) (lagVariable 1.0 b 2)))", 1, ds.GetDoubleValue("A", 1) * ds.GetDoubleValue("B", 2));
    340341      Evaluate(interpreter, ds, "(lag -2.0 3.0)", 1, 3.0);
     342
     343      // prognosis
     344      Evaluate(interpreter, ds, "(lagVariable 1.0 a -1)", new string[] { "A" }, Enumerable.Range(1, 1), 3, new[] { new double[] { 1.0, 1.0, 1.0 } });
     345      Evaluate(interpreter, ds, "(lagVariable 2.0 a -1)", new string[] { "A" }, Enumerable.Range(1, 1), 3, new[] { new double[] { 2.0, 4.0, 8.0 } });
     346      Evaluate(interpreter, ds, "(lagVariable 1.0 a -2)", new string[] { "A" }, Enumerable.Range(2, 1), 4, new[] { new double[] { 1.0, 2.0, 1.0, 2.0 } });
     347
     348      // multi-variate
     349      Evaluate(interpreter, ds, @"(PROG
     350                                    (MAIN (lagVariable 1.0 a -1) (lagVariable 1.0 b -1)))", new string[] { "A", "B" }, Enumerable.Range(1, 2), 3,
     351      new[] { new[] { 1.0, 1.0, 1.0 }, new[] { 1.0, 1.0, 1.0 } },
     352      new[] { new[] { 2.0, 2.0, 2.0 }, new[] { 2.0, 2.0, 2.0 } }
     353        );
     354
     355      //1.0, 1.0
     356      //2.0, 2.0
     357      //1.0, 2.0
     358      //1.0, 1.0
     359      //2.0, 2.0
     360      //1.0, 2.0
     361      //1.0, 1.0
     362      //2.0, 2.0
     363      //1.0, 2.0
     364      Evaluate(interpreter, ds, @"(PROG
     365                                     (MAIN (lagVariable 2.0 a -2) (lagVariable 1.0 a -1)))", new string[] { "A", "B" }, Enumerable.Range(2, 3), 4,
     366      new[] { new[] { 2.0, 4.0, 4.0, 8.0 }, new[] { 2.0, 2.0, 4.0, 4.0 } },
     367      new[] { new[] { 4.0, 2.0, 8.0, 4.0 }, new[] { 1.0, 4.0, 2.0, 8.0 } },
     368      new[] { new[] { 2.0, 2.0, 4.0, 4.0 }, new[] { 1.0, 2.0, 2.0, 4.0 } }
     369        );
    341370    }
    342371
     
    351380      Assert.AreEqual(expected, actual, 1.0E-12, expr);
    352381    }
     382    private void Evaluate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, Dataset ds, string expr, string[] targetVariables, IEnumerable<int> rows, int horizon, params IEnumerable<IEnumerable<double>>[] expected) {
     383      var importer = new SymbolicExpressionImporter();
     384      ISymbolicExpressionTree tree = importer.Import(expr);
     385
     386      var allPrognosis = interpreter.GetSymbolicExpressionTreeValues(tree, ds, targetVariables, rows, horizon);
     387      int i = 0;
     388      foreach (var actual in allPrognosis) {
     389        var actualEnumerator = actual.GetEnumerator();
     390        var expectedEnumerator = expected[i].GetEnumerator();
     391        while (actualEnumerator.MoveNext() & expectedEnumerator.MoveNext()) {
     392          var aEnumerator = actualEnumerator.Current.GetEnumerator();
     393          var eEnumerator = expectedEnumerator.Current.GetEnumerator();
     394          while (aEnumerator.MoveNext() & eEnumerator.MoveNext()) {
     395            Assert.IsFalse(double.IsNaN(aEnumerator.Current) && !double.IsNaN(eEnumerator.Current));
     396            Assert.IsFalse(!double.IsNaN(aEnumerator.Current) && double.IsNaN(eEnumerator.Current));
     397            Assert.AreEqual(eEnumerator.Current, aEnumerator.Current, 1.0E-12, expr);
     398          }
     399        }
     400        i++;
     401      }
     402    }
    353403  }
    354404}
  • branches/HeuristicLab.TimeSeries/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicExpressionImporter.cs

    r6866 r7129  
    7777      ISymbolicExpressionTreeNode root = programRootSymbol.CreateTreeNode();
    7878      ISymbolicExpressionTreeNode start = startSymbol.CreateTreeNode();
    79       ISymbolicExpressionTreeNode mainBranch = ParseSexp(new Queue<Token>(GetTokenStream(str)));
     79      var q = new Queue<Token>(GetTokenStream(str));
     80      ISymbolicExpressionTreeNode mainBranch = ParseSexp(q);
    8081      if (mainBranch.Symbol is ProgramRootSymbol) {
    8182        // when a root symbol was parsed => use main branch as root
Note: See TracChangeset for help on using the changeset viewer.