Changeset 3442


Ignore:
Timestamp:
04/20/10 15:49:22 (11 years ago)
Author:
gkronber
Message:

Implemented views for DataAnalysisProblems and DataAnalysisSolutions. #938 (Data types and operators for regression problems)

Location:
trunk/sources
Files:
15 added
2 deleted
27 edited
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.3/SymbolicExpressionTreeChart.cs

    r3294 r3442  
    258258
    259259      //draw name of symbol
    260       graphics.DrawString(node.Symbol.Name, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
     260      var text = node.ToString();
     261      graphics.DrawString(text, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
    261262
    262263      //draw connection line to parent node
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.3/SymbolicExpressionView.cs

    r3244 r3442  
    4848      if (node.SubTrees.Count > 0) {
    4949        // symbol on same line as '('
    50         strBuilder.AppendLine(node.Symbol.Name);
     50        strBuilder.AppendLine(node.ToString());
    5151        // each subtree expression on a new line
    5252        // and closing ')' also on new line
     
    5757      } else {
    5858        // symbol in the same line with as '(' and ')'
    59         strBuilder.Append(node.Symbol.Name);
     59        strBuilder.Append(node.ToString());
    6060        strBuilder.Append(")");
    6161      }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Creators/ProbabilisticTreeCreator.cs

    r3376 r3442  
    5656      SymbolicExpressionTree tree = new SymbolicExpressionTree();
    5757      var rootNode = grammar.StartSymbol.CreateTreeNode();
     58      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
    5859      rootNode.Grammar = grammar;
    5960      tree.Root = PTC2(random, rootNode, maxTreeSize, maxTreeHeight, maxFunctionDefinitions, maxFunctionArguments);
     
    111112        var dummy = new SymbolicExpressionTreeNode();
    112113        root.AddSubTree(dummy);
    113         // dummy.Grammar = (ISymbolicExpressionGrammar)dummy.Grammar.Clone();
    114114        extensionPoints.Add(new TreeExtensionPoint { Parent = root, ChildIndex = i, ExtensionPointDepth = 2 });
    115115      }
     
    132132          Symbol selectedSymbol = SelectRandomSymbol(random, allowedSymbols);
    133133          SymbolicExpressionTreeNode newTree = selectedSymbol.CreateTreeNode();
     134          if (newTree.HasLocalParameters) newTree.ResetLocalParameters(random);
    134135          parent.RemoveSubTree(argumentIndex);
    135136          parent.InsertSubTree(argumentIndex, newTree);
     
    145146            var dummy = new SymbolicExpressionTreeNode();
    146147            newTree.AddSubTree(dummy);
    147             //if (IsTopLevelBranch(root, dummy))
    148             //  dummy.Grammar = (ISymbolicExpressionGrammar)dummy.Grammar.Clone();
    149148            extensionPoints.Add(new TreeExtensionPoint { Parent = newTree, ChildIndex = i, ExtensionPointDepth = extensionDepth + 1 });
    150149          }
     
    172171      var selectedSymbol = SelectRandomSymbol(random, possibleSymbols);
    173172      var tree = selectedSymbol.CreateTreeNode();
     173      if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
    174174      parent.RemoveSubTree(argumentIndex);
    175175      parent.InsertSubTree(argumentIndex, tree);
     
    179179        var dummy = new SymbolicExpressionTreeNode();
    180180        tree.AddSubTree(dummy);
    181         // dummy.Grammar = (ISymbolicExpressionGrammar)dummy.Grammar.Clone();
    182181        // replace the just inserted dummy by recursive application
    183182        ReplaceWithMinimalTree(random, root, tree, i, maxFunctionDefinitions, maxFunctionArguments);
     
    229228
    230229    private static bool IsTopLevelBranch(SymbolicExpressionTreeNode root, SymbolicExpressionTreeNode branch) {
    231       //return root.SubTrees.IndexOf(branch) > -1;
    232230      return branch is SymbolicExpressionTreeTopLevelNode;
    233231    }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTree.cs

    r3431 r3442  
    6565    public SymbolicExpressionTree(SymbolicExpressionTreeNode root)
    6666      : base() {
     67      this.Root = root;
    6768    }
    6869
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeCompiler.cs

    r3409 r3442  
    4646      entryPoint.Clear();
    4747      // compile main body
    48       code.AddRange(Compile(tree.Root.SubTrees[0]));
     48      code.AddRange(Compile(tree.Root.SubTrees[0].SubTrees[0]));
    4949      // compile branches
    5050      var functionBranches = from node in tree.IterateNodesPrefix()
     
    5353      foreach (DefunTreeNode branch in functionBranches) {
    5454        entryPoint[branch.FunctionName] = (short)code.Count;
    55         code.AddRange(Compile(branch));
     55        code.AddRange(Compile(branch.SubTrees[0]));
    5656      }
     57      // address of all functions is fixed now
     58      // iterate through code again and fill in the jump locations
     59      for (int i = 0; i < code.Count; i++) {
     60        Instruction instr = code[i];
     61        if (instr.symbol == CodeSymbol.Call) {
     62          var invokeNode = (InvokeFunctionTreeNode)instr.dynamicNode;
     63          instr.iArg0 = entryPoint[invokeNode.Symbol.FunctionName];
     64          instr.dynamicNode = null;
     65          code[i] = instr;
     66        }
     67      }
     68
    5769      return code.ToArray();
    5870    }
     
    6577        if (codeSymbol.ContainsKey(node.Symbol.GetType())) {
    6678          instr.symbol = codeSymbol[node.Symbol.GetType()];
    67           if (instr.symbol == CodeSymbol.Call) {
    68             var invokeNode = (InvokeFunctionTreeNode)node;
    69             instr.iArg0 = entryPoint[invokeNode.Symbol.FunctionName];
    70           } else if (instr.symbol == CodeSymbol.Arg) {
     79          if (instr.symbol == CodeSymbol.Arg) {
    7180            var argNode = (ArgumentTreeNode)node;
    7281            instr.iArg0 = (short)argNode.Symbol.ArgumentIndex;
     82          } else if (instr.symbol == CodeSymbol.Call) {
     83            instr.dynamicNode = node; // save node for fixup of jump addresses in second iteration
    7384          }
    7485        } else {
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeCreator.cs

    r3376 r3442  
    6565      SymbolicExpressionTreeParameter.ActualValue = Create(Random, SymbolicExpressionGrammar,
    6666        MaxTreeSize, MaxTreeHeight, MaxFunctionDefinitions, MaxFunctionArguments);
    67 
    68       foreach (var node in SymbolicExpressionTreeParameter.ActualValue.IterateNodesPostfix()) {
    69         node.ResetLocalParameters(RandomParameter.ActualValue);
    70       }
    7167      return null;
    7268    }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeNode.cs

    r3376 r3442  
    145145    #endregion
    146146
    147 
     147    public override string ToString() {
     148      return Symbol.Name;
     149    }
    148150
    149151  }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Symbols/DefunTreeNode.cs

    r3376 r3442  
    5353      return new DefunTreeNode(this);
    5454    }
     55
     56    public override string ToString() {
     57      return FunctionName;
     58    }
    5559  }
    5660}
  • trunk/sources/HeuristicLab.GP.StructureIdentification/3.3/Symbols/Variable.cs

    r2910 r3442  
    2525using HeuristicLab.Data;
    2626using System.Xml;
     27using HeuristicLab.Core;
    2728
    2829namespace HeuristicLab.GP.StructureIdentification {
     
    149150    public override object Clone(System.Collections.Generic.IDictionary<System.Guid, object> clonedObjects) {
    150151      Variable clone = (Variable)base.Clone(clonedObjects);
    151       clone.MaxTimeOffset = MaxTimeOffset;
    152       clone.MinTimeOffset = MinTimeOffset;
     152      clone.maxOffset = MaxTimeOffset;
     153      clone.minOffset = MinTimeOffset;
    153154      return clone;
    154155    }
     
    166167      base.Populate(node, restoredObjects);
    167168      if (node.Attributes["MinTimeOffset"] != null)
    168         MinTimeOffset = XmlConvert.ToInt32(node.Attributes["MinTimeOffset"].Value);
     169        minOffset = XmlConvert.ToInt32(node.Attributes["MinTimeOffset"].Value);
    169170      else MinTimeOffset = 0;
    170171      if (node.Attributes["MaxTimeOffset"] != null)
    171         MaxTimeOffset = XmlConvert.ToInt32(node.Attributes["MaxTimeOffset"].Value);
     172        maxOffset = XmlConvert.ToInt32(node.Attributes["MaxTimeOffset"].Value);
    172173      else MaxTimeOffset = 0;
    173174    }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/HeuristicLab.Problems.DataAnalysis.Regression-3.3.csproj

    r3384 r3442  
    8686    <Compile Include="HeuristicLabProblemsDataAnalysisRegressionPlugin.cs" />
    8787    <Compile Include="Properties\AssemblyInfo.cs" />
     88    <Compile Include="Symbolic\BestValidationSymbolicRegressionSolutionVisualizer.cs" />
     89    <Compile Include="Symbolic\SymbolicRegressionSolution.cs" />
     90    <Compile Include="Symbolic\SymbolicRegressionModel.cs" />
    8891    <Compile Include="Symbolic\ISymbolicRegressionEvaluator.cs">
    8992      <SubType>Code</SubType>
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/SymbolicRegressionProblem.cs

    r3409 r3442  
    118118      get { return EvaluatorParameter.Value; }
    119119    }
    120     public ArithmeticExpressionGrammar FunctionTreeGrammar {
    121       get { return (ArithmeticExpressionGrammar)FunctionTreeGrammarParameter.Value; }
     120    public ISymbolicExpressionGrammar FunctionTreeGrammar {
     121      get { return (ISymbolicExpressionGrammar)FunctionTreeGrammarParameter.Value; }
    122122    }
    123123    public ISingleObjectiveSolutionsVisualizer Visualizer {
     
    141141      SymbolicExpressionTreeCreator creator = new ProbabilisticTreeCreator();
    142142      var evaluator = new SymbolicRegressionMeanSquaredErrorEvaluator();
    143       var grammar = new GlobalSymbolicExpressionGrammar(new ArithmeticExpressionGrammar());
     143      var grammar = new ArithmeticExpressionGrammar();
     144      var globalGrammar = new GlobalSymbolicExpressionGrammar(grammar);
     145      var visualizer = new BestValidationSymbolicRegressionSolutionVisualizer();
    144146      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the error of the regression model should be minimized.", new BoolValue(false)));
    145147      Parameters.Add(new ValueParameter<SymbolicExpressionTreeCreator>("SolutionCreator", "The operator which should be used to create new symbolic regression solutions.", creator));
    146148      Parameters.Add(new ValueParameter<ISymbolicRegressionEvaluator>("Evaluator", "The operator which should be used to evaluate symbolic regression solutions.", evaluator));
    147149      Parameters.Add(new ValueParameter<DoubleValue>("BestKnownQuality", "The minimal error value that can be reached by symbolic regression models.", new DoubleValue(0)));
    148       Parameters.Add(new ValueParameter<ISymbolicExpressionGrammar>("FunctionTreeGrammar", "The grammar that should be used for symbolic regression models.", grammar));
     150      Parameters.Add(new ValueParameter<ISymbolicExpressionGrammar>("FunctionTreeGrammar", "The grammar that should be used for symbolic regression models.", globalGrammar));
    149151      Parameters.Add(new ValueParameter<IntValue>("MaxExpressionLength", "Maximal length of the symbolic expression.", new IntValue(100)));
    150152      Parameters.Add(new ValueParameter<IntValue>("MaxExpressionDepth", "Maximal depth of the symbolic expression.", new IntValue(10)));
     
    152154      Parameters.Add(new ValueParameter<IntValue>("MaxFunctionArguments", "Maximal number of arguments of automatically defined functions.", new IntValue(3)));
    153155      Parameters.Add(new ValueParameter<DoubleValue>("NumberOfEvaluatedNodes", "The total number of evaluated function tree nodes (for performance measurements.)", new DoubleValue()));
    154       Parameters.Add(new ValueParameter<ISingleObjectiveSolutionsVisualizer>("Visualizer", "The operator which should be used to visualize artificial ant solutions.", null));
     156      Parameters.Add(new ValueParameter<ISingleObjectiveSolutionsVisualizer>("Visualizer", "The operator which should be used to visualize symbolic regression solutions.", visualizer));
    155157
    156158      creator.SymbolicExpressionTreeParameter.ActualName = "SymbolicRegressionModel";
     159      creator.MaxFunctionArgumentsParameter.ActualName = "MaxFunctionArguments";
     160      creator.MaxFunctionDefinitionsParameter.ActualName = "MaxFunctionDefiningBranches";
    157161      evaluator.QualityParameter.ActualName = "TrainingMeanSquaredError";
    158162      DataAnalysisProblemDataParameter.ValueChanged += new EventHandler(DataAnalysisProblemDataParameter_ValueChanged);
    159       DataAnalysisProblemData.InputVariablesChanged += new EventHandler(DataAnalysisProblemData_InputVariablesChanged);
     163      DataAnalysisProblemData.ProblemDataChanged += new EventHandler(DataAnalysisProblemData_Changed);
    160164      ParameterizeSolutionCreator();
    161165      ParameterizeEvaluator();
     
    166170
    167171    void DataAnalysisProblemDataParameter_ValueChanged(object sender, EventArgs e) {
    168       DataAnalysisProblemData.InputVariablesChanged += new EventHandler(DataAnalysisProblemData_InputVariablesChanged);
    169     }
    170 
    171     void DataAnalysisProblemData_InputVariablesChanged(object sender, EventArgs e) {
    172       FunctionTreeGrammar.VariableNames = DataAnalysisProblemData.InputVariables.Select(x => x.Value);
     172      DataAnalysisProblemData.ProblemDataChanged += new EventHandler(DataAnalysisProblemData_Changed);
     173    }
     174
     175    void DataAnalysisProblemData_Changed(object sender, EventArgs e) {
     176      foreach (var varSymbol in FunctionTreeGrammar.Symbols.OfType<HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable>()) {
     177        varSymbol.VariableNames = DataAnalysisProblemData.InputVariables.Select(x => x.Value);
     178      }
    173179    }
    174180
     
    268274    private void ParameterizeVisualizer() {
    269275      if (Visualizer != null) {
    270         //Visualizer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
    271         //var antTrailVisualizer = Visualizer as IAntTrailVisualizer;
    272         //if (antTrailVisualizer != null) {
    273         //  antTrailVisualizer.SymbolicExpressionTreeParameter.ActualName = SolutionCreator.SymbolicExpressionTreeParameter.ActualName;
    274         //  antTrailVisualizer.WorldParameter.ActualName = WorldParameter.Name;
    275         //  antTrailVisualizer.MaxTimeStepsParameter.ActualName = MaxTimeStepsParameter.Name;
    276         //}
    277         //var bestSymExpressionVisualizer = Visualizer as BestSymbolicExpressionTreeVisualizer;
    278         //if (bestSymExpressionVisualizer != null) {
    279         //  bestSymExpressionVisualizer.SymbolicExpressionTreeParameter.ActualName = SolutionCreator.SymbolicExpressionTreeParameter.ActualName;
    280         //}
     276        var solutionVisualizer = Visualizer as BestValidationSymbolicRegressionSolutionVisualizer;
     277        if (solutionVisualizer != null) {
     278          solutionVisualizer.SymbolicExpressionTreeParameter.ActualName = SolutionCreator.SymbolicExpressionTreeParameter.ActualName;
     279          solutionVisualizer.DataAnalysisProblemDataParameter.ActualName = DataAnalysisProblemDataParameter.Name;
     280        }
    281281      }
    282282    }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/DataAnalysisProblemDataView.Designer.cs

    r3373 r3442  
    1 #region License Information
    2 /* HeuristicLab
    3  * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    4  *
    5  * This file is part of HeuristicLab.
    6  *
    7  * HeuristicLab is free software: you can redistribute it and/or modify
    8  * it under the terms of the GNU General Public License as published by
    9  * the Free Software Foundation, either version 3 of the License, or
    10  * (at your option) any later version.
    11  *
    12  * HeuristicLab is distributed in the hope that it will be useful,
    13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15  * GNU General Public License for more details.
    16  *
    17  * You should have received a copy of the GNU General Public License
    18  * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
    19  */
    20 #endregion
    21 
    22 namespace HeuristicLab.Problems.DataAnalysis {
     1namespace HeuristicLab.Problems.DataAnalysis.Views {
    232  partial class DataAnalysisProblemDataView {
    243    /// <summary>
     
    3211    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    3312    protected override void Dispose(bool disposing) {
    34       if (disposing) {
    35         if (openFileDialog != null) openFileDialog.Dispose();
    36         if (components != null) components.Dispose();
     13      if (disposing && (components != null)) {
     14        components.Dispose();
    3715      }
    3816      base.Dispose(disposing);
     
    4624    /// </summary>
    4725    private void InitializeComponent() {
     26      this.variableCollectionView = new HeuristicLab.Core.Views.VariableCollectionView();
    4827      this.importButton = new System.Windows.Forms.Button();
    49       this.datasetView = new HeuristicLab.Data.Views.StringConvertibleMatrixView();
    5028      ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
    5129      this.SuspendLayout();
     
    5533      this.errorProvider.SetIconAlignment(this.nameTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
    5634      this.errorProvider.SetIconPadding(this.nameTextBox, 2);
    57       this.nameTextBox.Size = new System.Drawing.Size(457, 20);
    5835      //
    59       // descriptionTextBox
     36      // variableCollectionView
    6037      //
    61       this.descriptionTextBox.Size = new System.Drawing.Size(457, 20);
     38      this.variableCollectionView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     39                  | System.Windows.Forms.AnchorStyles.Left)
     40                  | System.Windows.Forms.AnchorStyles.Right)));
     41      this.variableCollectionView.Caption = "VariableCollection";
     42      this.variableCollectionView.Content = null;
     43      this.variableCollectionView.Location = new System.Drawing.Point(0, 52);
     44      this.variableCollectionView.Name = "variableCollectionView";
     45      this.variableCollectionView.ReadOnly = false;
     46      this.variableCollectionView.Size = new System.Drawing.Size(588, 366);
     47      this.variableCollectionView.TabIndex = 0;
    6248      //
    6349      // importButton
     
    6551      this.importButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
    6652                  | System.Windows.Forms.AnchorStyles.Right)));
    67       this.importButton.Location = new System.Drawing.Point(0, 399);
     53      this.importButton.Location = new System.Drawing.Point(6, 424);
    6854      this.importButton.Name = "importButton";
    69       this.importButton.Size = new System.Drawing.Size(529, 23);
    70       this.importButton.TabIndex = 5;
    71       this.importButton.Text = "&Import from CSV file";
     55      this.importButton.Size = new System.Drawing.Size(579, 23);
     56      this.importButton.TabIndex = 4;
     57      this.importButton.Text = "Import from CSV file";
    7258      this.importButton.UseVisualStyleBackColor = true;
    7359      this.importButton.Click += new System.EventHandler(this.importButton_Click);
    7460      //
    75       // datasetView
    76       //
    77       this.datasetView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    78                   | System.Windows.Forms.AnchorStyles.Left)
    79                   | System.Windows.Forms.AnchorStyles.Right)));
    80       this.datasetView.Caption = "StringConvertibleMatrix View";
    81       this.datasetView.Content = null;
    82       this.datasetView.Location = new System.Drawing.Point(0, 52);
    83       this.datasetView.Name = "datasetView";
    84       this.datasetView.Size = new System.Drawing.Size(526, 341);
    85       this.datasetView.TabIndex = 6;
    86       //
    87       // RegressionProblemDataView
     61      // ProblemDataView
    8862      //
    8963      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    9064      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
     65      this.Controls.Add(this.variableCollectionView);
    9166      this.Controls.Add(this.importButton);
    92       this.Controls.Add(this.datasetView);
    93       this.Name = "RegressionProblemDataView";
    94       this.Size = new System.Drawing.Size(529, 422);
    95       this.Controls.SetChildIndex(this.datasetView, 0);
     67      this.Name = "ProblemDataView";
     68      this.Size = new System.Drawing.Size(588, 450);
    9669      this.Controls.SetChildIndex(this.importButton, 0);
     70      this.Controls.SetChildIndex(this.variableCollectionView, 0);
    9771      this.Controls.SetChildIndex(this.nameLabel, 0);
    9872      this.Controls.SetChildIndex(this.descriptionLabel, 0);
     
    10781    #endregion
    10882
     83    private HeuristicLab.Core.Views.VariableCollectionView variableCollectionView;
    10984    private System.Windows.Forms.Button importButton;
    110     private HeuristicLab.Data.Views.StringConvertibleMatrixView datasetView;
    111 
    11285  }
    11386}
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/DataAnalysisProblemDataView.cs

    r3376 r3442  
    1 #region License Information
    2 /* HeuristicLab
    3  * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    4  *
    5  * This file is part of HeuristicLab.
    6  *
    7  * HeuristicLab is free software: you can redistribute it and/or modify
    8  * it under the terms of the GNU General Public License as published by
    9  * the Free Software Foundation, either version 3 of the License, or
    10  * (at your option) any later version.
    11  *
    12  * HeuristicLab is distributed in the hope that it will be useful,
    13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15  * GNU General Public License for more details.
    16  *
    17  * You should have received a copy of the GNU General Public License
    18  * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
    19  */
    20 #endregion
    21 
    22 using System;
     1using System;
     2using System.Collections.Generic;
     3using System.ComponentModel;
     4using System.Drawing;
     5using System.Data;
     6using System.Linq;
     7using System.Text;
    238using System.Windows.Forms;
    24 using HeuristicLab.Common;
    25 using HeuristicLab.Core;
    269using HeuristicLab.Core.Views;
    2710using HeuristicLab.MainForm;
    2811
    29 namespace HeuristicLab.Problems.DataAnalysis {
    30   [View("Data-Analysis Data View")]
    31   [Content(typeof(DataAnalysisProblemData), true)]
     12namespace HeuristicLab.Problems.DataAnalysis.Views {
     13  [View("Data-Analysis Problem View")]
     14  [Content(typeof(DataAnalysisProblemData))]
    3215  public partial class DataAnalysisProblemDataView : NamedItemView {
    3316    private OpenFileDialog openFileDialog;
    34 
    3517    public new DataAnalysisProblemData Content {
    3618      get { return (DataAnalysisProblemData)base.Content; }
    37       set { base.Content = value; }
     19      set {
     20        base.Content = value;
     21      }
    3822    }
    3923
     
    4529      : this() {
    4630      Content = content;
     31      variableCollectionView.Content = content.Variables.AsReadOnly();
    4732    }
    4833
    49     protected override void RegisterContentEvents() {
    50       base.RegisterContentEvents();
    51       if (Content != null)
    52         Content.DatasetChanged += new EventHandler(Content_DatasetChanged);
    53     }
    54 
    55     protected override void DeregisterContentEvents() {
    56       base.DeregisterContentEvents();
    57       if(Content != null)
    58         Content.DatasetChanged -= new EventHandler(Content_DatasetChanged);
    59     }
    60 
    61     private void Content_DatasetChanged(object sender, EventArgs e) {
    62       this.datasetView.Content = this.Content.Dataset;
    63     }
    64 
    65     protected override void OnContentChanged() {
    66       base.OnContentChanged();
    67       if (Content == null) {
    68         importButton.Enabled = false;
    69       } else {
    70         importButton.Enabled = true;
    71         this.datasetView.Content = this.Content.Dataset;
    72       }
    73     }
    74 
    75     private void importButton_Click(object sender, System.EventArgs e) {
     34    private void importButton_Click(object sender, EventArgs e) {
    7635      if (openFileDialog == null) openFileDialog = new OpenFileDialog();
    7736
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/HeuristicLab.Problems.DataAnalysis.Views-3.3.csproj

    r3437 r3442  
    7272    <Reference Include="System.Drawing" />
    7373    <Reference Include="System.Windows.Forms" />
     74    <Reference Include="System.Windows.Forms.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
    7475    <Reference Include="System.Xml.Linq">
    7576      <RequiredTargetFramework>3.5</RequiredTargetFramework>
     
    8485    <None Include="HeuristicLab.snk" />
    8586    <None Include="Properties\AssemblyInfo.frame" />
     87    <Compile Include="EstimatedValuesView.cs">
     88      <SubType>UserControl</SubType>
     89    </Compile>
     90    <Compile Include="EstimatedValuesView.Designer.cs">
     91      <DependentUpon>EstimatedValuesView.cs</DependentUpon>
     92    </Compile>
    8693    <Compile Include="DataAnalysisProblemDataView.cs">
    8794      <SubType>UserControl</SubType>
     
    9198    </Compile>
    9299    <Compile Include="HeuristicLabProblemsDataAnalysisViewsPlugin.cs" />
     100    <Compile Include="LineChartView.cs">
     101      <SubType>UserControl</SubType>
     102    </Compile>
     103    <Compile Include="LineChartView.Designer.cs">
     104      <DependentUpon>LineChartView.cs</DependentUpon>
     105    </Compile>
    93106    <Compile Include="Properties\AssemblyInfo.cs" />
     107    <Compile Include="ScatterPlotView.cs">
     108      <SubType>UserControl</SubType>
     109    </Compile>
     110    <Compile Include="ScatterPlotView.Designer.cs">
     111      <DependentUpon>ScatterPlotView.cs</DependentUpon>
     112    </Compile>
     113    <Compile Include="Symbolic\SimplifiedSymbolicExpressionModelView.cs">
     114      <SubType>UserControl</SubType>
     115    </Compile>
     116    <Compile Include="Symbolic\SimplifiedSymbolicExpressionModelView.designer.cs">
     117      <DependentUpon>SimplifiedSymbolicExpressionModelView.cs</DependentUpon>
     118    </Compile>
     119    <Compile Include="Symbolic\SymbolicExpressionModelView.cs">
     120      <SubType>UserControl</SubType>
     121    </Compile>
     122    <Compile Include="Symbolic\SymbolicExpressionModelView.designer.cs">
     123      <DependentUpon>SymbolicExpressionModelView.cs</DependentUpon>
     124    </Compile>
    94125  </ItemGroup>
    95126  <ItemGroup>
     
    118149      <Name>HeuristicLab.Data-3.3</Name>
    119150    </ProjectReference>
     151    <ProjectReference Include="..\..\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views\3.3\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.3.csproj">
     152      <Project>{6F42C5F8-16CD-43EE-8208-FD4573A69D85}</Project>
     153      <Name>HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.3</Name>
     154    </ProjectReference>
    120155    <ProjectReference Include="..\..\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding\3.3\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.3.csproj">
    121156      <Project>{125D3006-67F5-48CB-913E-73C0548F17FA}</Project>
     
    146181      <Name>HeuristicLab.PluginInfrastructure</Name>
    147182    </ProjectReference>
     183    <ProjectReference Include="..\..\HeuristicLab.Problems.DataAnalysis.Regression\3.3\HeuristicLab.Problems.DataAnalysis.Regression-3.3.csproj">
     184      <Project>{BDF86B1D-630E-4CE2-8A49-8C90B1BDE4C9}</Project>
     185      <Name>HeuristicLab.Problems.DataAnalysis.Regression-3.3</Name>
     186    </ProjectReference>
    148187    <ProjectReference Include="..\..\HeuristicLab.Problems.DataAnalysis\3.3\HeuristicLab.Problems.DataAnalysis-3.3.csproj">
    149188      <Project>{70DFD984-B1D9-46FE-8EB7-4DE92D71A9FC}</Project>
    150189      <Name>HeuristicLab.Problems.DataAnalysis-3.3</Name>
    151190    </ProjectReference>
     191  </ItemGroup>
     192  <ItemGroup>
     193    <EmbeddedResource Include="EstimatedValuesView.resx">
     194      <DependentUpon>EstimatedValuesView.cs</DependentUpon>
     195    </EmbeddedResource>
     196    <EmbeddedResource Include="DataAnalysisProblemDataView.resx">
     197      <DependentUpon>DataAnalysisProblemDataView.cs</DependentUpon>
     198    </EmbeddedResource>
     199    <EmbeddedResource Include="LineChartView.resx">
     200      <DependentUpon>LineChartView.cs</DependentUpon>
     201    </EmbeddedResource>
     202    <EmbeddedResource Include="ScatterPlotView.resx">
     203      <DependentUpon>ScatterPlotView.cs</DependentUpon>
     204    </EmbeddedResource>
     205    <EmbeddedResource Include="Symbolic\SimplifiedSymbolicExpressionModelView.resx">
     206      <DependentUpon>SimplifiedSymbolicExpressionModelView.cs</DependentUpon>
     207    </EmbeddedResource>
     208    <EmbeddedResource Include="Symbolic\SymbolicExpressionModelView.resx">
     209      <DependentUpon>SymbolicExpressionModelView.cs</DependentUpon>
     210    </EmbeddedResource>
    152211  </ItemGroup>
    153212  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/LineChartView.Designer.cs

    r3408 r3442  
    1919 */
    2020#endregion
    21 namespace HeuristicLab.Problem.DataAnalysis.Views {
     21namespace HeuristicLab.Problems.DataAnalysis.Views {
    2222  partial class LineChartView {
    2323    /// <summary>
     
    6363      this.chart.Size = new System.Drawing.Size(358, 225);
    6464      this.chart.TabIndex = 0;
    65       this.chart.MouseMove += new System.Windows.Forms.MouseEventHandler(this.chart_MouseMove);
    66       this.chart.MouseDown += new System.Windows.Forms.MouseEventHandler(this.chart_MouseDown);
    6765      //
    6866      // QualityLineChart
     
    7472      this.Name = "QualityLineChart";
    7573      this.Size = new System.Drawing.Size(358, 225);
    76       this.DragDrop += new System.Windows.Forms.DragEventHandler(this.ModelLineChart_DragDrop);
    77       this.DragEnter += new System.Windows.Forms.DragEventHandler(this.ModelLineChart_DragEnter);
    7874      ((System.ComponentModel.ISupportInitialize)(this.chart)).EndInit();
    7975      this.ResumeLayout(false);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/LineChartView.cs

    r3408 r3442  
    3232using HeuristicLab.Problems.DataAnalysis;
    3333using HeuristicLab.MainForm.WindowsForms;
     34using System.Windows.Forms.DataVisualization.Charting;
    3435
    35 namespace HeuristicLab.Problems.DataAnalysis {
     36namespace HeuristicLab.Problems.DataAnalysis.Views {
    3637  [View("Line Chart View")]
    3738  [Content(typeof(DataAnalysisSolution))]
    38   public partial class LineChartView : ContentView {
    39    
     39  public partial class LineChartView : AsynchronousContentView {
     40    private const string TARGETVARIABLE_SERIES_NAME = "TargetVariable";
     41    private const string ESTIMATEDVALUES_SERIES_NAME = "EstimatedValues";
     42
     43    public new DataAnalysisSolution Content {
     44      get { return (DataAnalysisSolution)base.Content; }
     45      set {
     46        base.Content = value;
     47      }
     48    }
     49
    4050    public LineChartView()
    4151      : base() {
     
    4959      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
    5060      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
    51       this.chart.ChartAreas[0].CursorY.Interval = 0;     
     61      this.chart.ChartAreas[0].CursorY.Interval = 0;
    5262    }
    5363
    5464    public LineChartView(DataAnalysisSolution dataAnalysisSolution)
    5565      : this() {
    56      
     66      Content = dataAnalysisSolution;
     67      DrawTargetVariableValues();
     68      DrawEstimatedValues();
    5769    }
    5870
    59     private void model_Changed(object sender, EventArgs e) {
    60       if (InvokeRequired) {
    61         Action<object, EventArgs> action = new Action<object, EventArgs>(model_Changed);
    62         this.Invoke(action, sender, e);
    63       } else {
    64         IVisualModel model = (IVisualModel)sender;
    65         Series s = this.chart.Series.Single(x => x.Tag == model);
    66         s.Points.DataBindY(model.PredictedValues.ToArray());
    67         s.LegendText = model.ModelName;
    68         this.UpdateStripLines();
    69       }
     71    private void DrawEstimatedValues() {
     72      this.chart.Series.Add(ESTIMATEDVALUES_SERIES_NAME);
     73      this.chart.Series[ESTIMATEDVALUES_SERIES_NAME].LegendText = Content.ItemName;
     74      this.chart.Series[ESTIMATEDVALUES_SERIES_NAME].ChartType = SeriesChartType.FastLine;
     75      this.chart.Series[ESTIMATEDVALUES_SERIES_NAME].Points.DataBindY(Content.EstimatedValues.ToArray());
     76      this.chart.Series[ESTIMATEDVALUES_SERIES_NAME].Tag = Content;
    7077    }
    7178
    72     protected override void ModelsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
    73       base.ModelsCollectionChanged(sender, e);
    74       if (InvokeRequired) {
    75         Action<object, NotifyCollectionChangedEventArgs> action = new Action<object, NotifyCollectionChangedEventArgs>(ModelsCollectionChanged);
    76         this.Invoke(action, sender, e);
    77       } else {
    78         if (e.Action == NotifyCollectionChangedAction.Remove) {
    79           foreach (IVisualModel model in e.OldItems) {
    80             if (this.chart.Series.Any(x => x.Tag == model))
    81               this.RemoveModel(model);
    82           }
    83           this.UpdateStripLines();
    84         } else if (e.Action == NotifyCollectionChangedAction.Reset)
    85           this.RemoveAllModels();
    86       }
    87     }
    88 
    89     private void AddModel(IVisualModel model) {
    90       if (this.targetVariableName != model.TargetVariableName) {
    91         this.RemoveAllModels();
    92         this.chart.Series.Clear();
    93         this.chart.Series.Add(TARGETVARIABLE);
    94         this.chart.Series[TARGETVARIABLE].LegendText = model.TargetVariableName;
    95         this.chart.Series[TARGETVARIABLE].ChartType = SeriesChartType.FastLine;
    96         this.chart.Series[TARGETVARIABLE].Points.DataBindY(model.Dataset.GetVariableValues(model.TargetVariableName));
    97         this.targetVariableName = model.TargetVariableName;
    98         this.Caption = this.targetVariableName + " Model Line Chart";
    99       }
    100       string seriesName = model.GetHashCode().ToString();
    101       this.chart.Series.Add(seriesName);
    102       this.chart.Series[seriesName].Tag = model;
    103       this.chart.Series[seriesName].LegendText = model.ModelName;
    104       this.chart.Series[seriesName].ChartType = SeriesChartType.FastLine;
    105       this.chart.Series[seriesName].Points.DataBindY(model.PredictedValues.ToArray());
    106       model.Changed += new EventHandler(model_Changed);
     79    private void DrawTargetVariableValues() {
     80      this.chart.Series.Clear();
     81      this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
     82      this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = Content.ProblemData.TargetVariable.Value;
     83      this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
     84      this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindY(Content.ProblemData.Dataset[Content.ProblemData.TargetVariable.Value]);
    10785      this.UpdateStripLines();
    10886    }
    10987
    110     private void RemoveModel(IVisualModel model) {
    111       Series s = this.chart.Series.Single(x => x.Tag == model);
    112       this.chart.Series.Remove(s);
    113       model.Changed -= new EventHandler(model_Changed);
     88    #region events
     89    protected override void RegisterContentEvents() {
     90      base.RegisterContentEvents();
     91      Content.ModelChanged += new EventHandler(Content_ModelChanged);
     92      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
    11493    }
    11594
    116     private void RemoveAllModels() {
    117       var models = (from s in chart.Series
    118                     let m = s.Tag as IVisualModel
    119                     where m != null
    120                     select m).ToArray(); // select and copy currently displayed models
    121       foreach (var m in models) {
    122         this.RemoveModel(m);
    123       }
    124       this.UpdateStripLines();
     95    protected override void DeregisterContentEvents() {
     96      base.DeregisterContentEvents();
     97      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
     98      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
    12599    }
    126100
    127     private void chart_MouseDown(object sender, MouseEventArgs e) {
    128       HitTestResult result = this.chart.HitTest(e.X, e.Y);
    129       if (result.ChartElementType == ChartElementType.LegendItem) {
    130         if (result.Series.Name != TARGETVARIABLE) {
    131           this.RemoveModel(result.Series.Tag as IVisualModel);
    132           this.UpdateStripLines();
     101    void Content_ProblemDataChanged(object sender, EventArgs e) {
     102      OnContentChanged();
     103    }
     104
     105    void Content_ModelChanged(object sender, EventArgs e) {
     106      OnContentChanged();
     107    }
     108
     109    protected override void OnContentChanged() {
     110      base.OnContentChanged();
     111      UpdateEstimatedValuesLineChart();
     112    }
     113
     114    private void UpdateEstimatedValuesLineChart() {
     115      if (InvokeRequired) Invoke((Action)UpdateEstimatedValuesLineChart);
     116      else {
     117        if (this.chart.Series.Count > 0) {
     118          Series s = this.chart.Series.SingleOrDefault(x => x.Tag == Content);
     119          if (s != null) {
     120            s.Points.DataBindY(Content.EstimatedValues.ToArray());
     121            s.LegendText = Content.ItemName;
     122            this.UpdateStripLines();
     123          }
    133124        }
    134125      }
    135126    }
    136 
    137     private void chart_MouseMove(object sender, MouseEventArgs e) {
    138       HitTestResult result = this.chart.HitTest(e.X, e.Y);
    139       if (result.ChartElementType == ChartElementType.LegendItem) {
    140         if (result.Series.Name != TARGETVARIABLE)
    141           this.Cursor = Cursors.Hand;
    142       } else
    143         this.Cursor = Cursors.Default;
    144     }
     127    #endregion
    145128
    146129    private void UpdateStripLines() {
    147130      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
    148       IEnumerable<IVisualModel> visualModels = from Series s in this.chart.Series
    149                                                where s.Tag is IVisualModel
    150                                                select (IVisualModel)s.Tag;
    151       if (visualModels.Count() > 0) {
    152         IVisualModel model = visualModels.ElementAt(0);
    153         if (visualModels.All(x => x.TrainingSamplesStart == model.TrainingSamplesStart && x.TrainingSamplesEnd == model.TrainingSamplesEnd))
    154           this.CreateAndAddStripLine("Training", Color.FromArgb(20, Color.Green), model.TrainingSamplesStart, model.TrainingSamplesEnd);
    155         if (visualModels.All(x => x.ValidationSamplesStart == model.ValidationSamplesStart && x.ValidationSamplesEnd == model.ValidationSamplesEnd))
    156           this.CreateAndAddStripLine("Validation", Color.FromArgb(20, Color.Yellow), model.ValidationSamplesStart, model.ValidationSamplesEnd);
    157         if (visualModels.All(x => x.TestSamplesStart == model.TestSamplesStart && x.TestSamplesEnd == model.TestSamplesEnd))
    158           this.CreateAndAddStripLine("Test", Color.FromArgb(20, Color.Red), model.TestSamplesStart, model.TestSamplesEnd);
    159       }
     131      this.CreateAndAddStripLine("Training", Color.FromArgb(20, Color.Green),
     132        Content.ProblemData.TrainingSamplesStart.Value,
     133        Content.ProblemData.TrainingSamplesEnd.Value);
     134      this.CreateAndAddStripLine("Test", Color.FromArgb(20, Color.Red),
     135        Content.ProblemData.TestSamplesStart.Value,
     136        Content.ProblemData.TestSamplesEnd.Value);
    160137    }
    161138
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/ScatterPlotView.Designer.cs

    r3408 r3442  
    7575      this.AllowDrop = true;
    7676      this.Size = new System.Drawing.Size(527, 392);
    77       this.DragDrop += new System.Windows.Forms.DragEventHandler(this.ScatterPlotView_DragDrop);
    78       this.DragEnter += new System.Windows.Forms.DragEventHandler(this.ScatterPlotView_DragEnter);
    7977      ((System.ComponentModel.ISupportInitialize)(this.chart)).EndInit();
    8078      this.ResumeLayout(false);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/ScatterPlotView.cs

    r3408 r3442  
    3232using HeuristicLab.MainForm;
    3333using HeuristicLab.Problems.DataAnalysis;
    34 
    35 namespace HeuristicLab.Problems.DataAnalyis.Views {
     34using HeuristicLab.MainForm.WindowsForms;
     35
     36namespace HeuristicLab.Problems.DataAnalysis.Views {
    3637  [View("Scatter Plot View")]
    3738  [Content(typeof(DataAnalysisSolution))]
    38   public partial class ScatterPlotView : ContentView {
     39  public partial class ScatterPlotView : AsynchronousContentView {
    3940    private const string DEFAULT_CAPTION = "Scatter Plot";
    4041    private const string ALL_SERIES = "All Samples";
    4142    private const string TRAINING_SERIES = "Training Samples";
    42     private const string validationSeries = "Validation Samples";
    4343    private const string TEST_SERIES = "Test Samples";
     44
     45    public new DataAnalysisSolution Content {
     46      get { return (DataAnalysisSolution)base.Content; }
     47      set { base.Content = value; }
     48    }
    4449
    4550    public ScatterPlotView()
     
    5560      this.chart.Series[TRAINING_SERIES].LegendText = TRAINING_SERIES;
    5661      this.chart.Series[TRAINING_SERIES].ChartType = SeriesChartType.FastPoint;
    57 
    58       this.chart.Series.Add(validationSeries);
    59       this.chart.Series[validationSeries].LegendText = validationSeries;
    60       this.chart.Series[validationSeries].ChartType = SeriesChartType.FastPoint;
    6162
    6263      this.chart.Series.Add(TEST_SERIES);
     
    8081    }
    8182
    82     public ScatterPlotView(IVisualModel visualModel)
     83    public ScatterPlotView(DataAnalysisSolution dataAnalysisSolution)
    8384      : this() {
    84       this.VisualModel = visualModel;
    85     }
    86 
    87     private IVisualModel visualModel;
    88     public IVisualModel VisualModel {
    89       get { return this.visualModel; }
    90       private set {
    91         if (this.visualModel != null) {
    92           this.visualModel.Changed -= new EventHandler(model_Changed);                 
    93         }
    94         this.visualModel = value;
    95         if (this.visualModel != null) {
    96           this.Caption = this.visualModel.ModelName + " " + DEFAULT_CAPTION;
    97           this.visualModel.Changed += new EventHandler(model_Changed);
     85      Content = dataAnalysisSolution;
     86    }
     87
     88    protected override void RegisterContentEvents() {
     89      base.RegisterContentEvents();
     90      Content.ModelChanged += new EventHandler(Content_ModelChanged);
     91      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
     92    }
     93    protected override void DeregisterContentEvents() {
     94      base.DeregisterContentEvents();
     95      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
     96      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
     97    }
     98
     99
     100    void Content_ProblemDataChanged(object sender, EventArgs e) {
     101      OnContentChanged();
     102    }
     103
     104    void Content_ModelChanged(object sender, EventArgs e) {
     105      OnContentChanged();
     106    }
     107
     108    protected override void OnContentChanged() {
     109      base.OnContentChanged();
     110      UpdateChart();
     111    }
     112
     113    private void UpdateChart() {
     114      if (InvokeRequired) Invoke((Action)UpdateChart);
     115      else {
     116        if (Content != null) {
     117          this.Caption = Content.ItemName + " " + DEFAULT_CAPTION;
    98118          this.UpdateSeries();
    99119          if (!this.chart.Series.Any(s => s.Points.Count > 0))
     
    107127
    108128    private void UpdateSeries() {
     129      string targetVariableName = Content.ProblemData.TargetVariable.Value;
     130      Dataset dataset = Content.ProblemData.Dataset;
     131      int trainingStart = Content.ProblemData.TrainingSamplesStart.Value;
     132      int trainingEnd = Content.ProblemData.TrainingSamplesEnd.Value;
     133      int testStart = Content.ProblemData.TestSamplesStart.Value;
     134      int testEnd = Content.ProblemData.TestSamplesEnd.Value;
    109135      if (this.chart.Series[ALL_SERIES].Points.Count > 0)
    110         this.chart.Series[ALL_SERIES].Points.DataBindXY(this.visualModel.PredictedValues.ToArray(), "",
    111           this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName), "");
     136        this.chart.Series[ALL_SERIES].Points.DataBindXY(Content.EstimatedValues.ToArray(), "",
     137          dataset[targetVariableName], "");
    112138      if (this.chart.Series[TRAINING_SERIES].Points.Count > 0)
    113         this.chart.Series[TRAINING_SERIES].Points.DataBindXY(this.visualModel.PredictedTrainingValues.ToArray(), "",
    114           this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName, this.visualModel.TrainingSamplesStart, this.visualModel.TrainingSamplesEnd), "");
    115       if (this.chart.Series[validationSeries].Points.Count > 0)
    116         this.chart.Series[validationSeries].Points.DataBindXY(this.visualModel.PredictedValidationValues.ToArray(), "",
    117           this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName, this.visualModel.ValidationSamplesStart, this.visualModel.ValidationSamplesEnd), "");
     139        this.chart.Series[TRAINING_SERIES].Points.DataBindXY(Content.EstimatedTrainingValues.ToArray(), "",
     140          dataset.GetVariableValues(targetVariableName, trainingStart, trainingEnd), "");
    118141      if (this.chart.Series[TEST_SERIES].Points.Count > 0)
    119         this.chart.Series[TEST_SERIES].Points.DataBindXY(this.visualModel.PredictedTestValues.ToArray(), "",
    120           this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName, this.visualModel.TestSamplesStart, this.visualModel.TestSamplesEnd), "");
    121 
    122       double x = this.visualModel.PredictedValues.Max();
    123       double y = this.visualModel.Dataset.GetMaximum(this.visualModel.TargetVariableName);
    124       double max = x > y ? x : y;
    125       x = this.visualModel.PredictedValues.Min();
    126       y = this.visualModel.Dataset.GetMinimum(this.visualModel.TargetVariableName);
    127       double min = x < y ? x : y;
     142        this.chart.Series[TEST_SERIES].Points.DataBindXY(Content.EstimatedTestValues.ToArray(), "",
     143          dataset.GetVariableValues(targetVariableName, testStart, testEnd), "");
     144
     145      double max = Math.Max(Content.EstimatedValues.Max(), dataset.GetMax(targetVariableName));
     146      double min = Math.Min(Content.EstimatedValues.Min(), dataset.GetMin(targetVariableName));
    128147
    129148      max = Math.Ceiling(max) * 1.2;
     
    139158      this.chart.Series[ALL_SERIES].Points.Clear();
    140159      this.chart.Series[TRAINING_SERIES].Points.Clear();
    141       this.chart.Series[validationSeries].Points.Clear();
    142160      this.chart.Series[TEST_SERIES].Points.Clear();
    143161    }
    144 
    145 
    146     private void model_Changed(object sender, EventArgs e) {
    147       if (InvokeRequired) {
    148         Action<object, EventArgs> action = new Action<object, EventArgs>(model_Changed);
    149         this.Invoke(action, sender, e);
    150       } else {
    151         this.Caption = this.visualModel.ModelName + " " + DEFAULT_CAPTION;
    152         this.UpdateSeries();
    153       }
    154     }
    155 
    156     protected override void OnClosed(FormClosedEventArgs e) {
    157       base.OnClosed( e);
    158       this.VisualModel = null;
    159     }
    160 
    161     protected override void ModelsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
    162       if (InvokeRequired) {
    163         Action<object, NotifyCollectionChangedEventArgs> action = new Action<object, NotifyCollectionChangedEventArgs>(ModelsCollectionChanged);
    164         this.Invoke(action, sender, e);
    165       } else {
    166         if (e.Action == NotifyCollectionChangedAction.Remove) {
    167           if (e.OldItems.Contains(this.visualModel))
    168             this.VisualModel = null;
    169         }
    170         if(e.Action == NotifyCollectionChangedAction.Reset)
    171           this.VisualModel = null;
    172       }
    173     } 
    174162
    175163    private void ToggleSeriesData(Series series) {
    176164      if (series.Points.Count > 0) {  //checks if series is shown
    177165        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
    178           series.Points.Clear();   
     166          series.Points.Clear();
    179167        }
    180       } else if (this.visualModel != null) {
     168      } else if (Content != null) {
     169        string targetVariableName = Content.ProblemData.TargetVariable.Value;
     170        Dataset dataset = Content.ProblemData.Dataset;
     171        int trainingStart = Content.ProblemData.TrainingSamplesStart.Value;
     172        int trainingEnd = Content.ProblemData.TrainingSamplesEnd.Value;
     173        int testStart = Content.ProblemData.TestSamplesStart.Value;
     174        int testEnd = Content.ProblemData.TestSamplesEnd.Value;
     175
    181176        IEnumerable<double> predictedValues = null;
    182177        IEnumerable<double> targetValues = null;
    183178        switch (series.Name) {
    184179          case ALL_SERIES:
    185             predictedValues = this.visualModel.PredictedValues;
    186             targetValues = this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName);
     180            predictedValues = Content.EstimatedValues;
     181            targetValues = dataset[targetVariableName];
    187182            break;
    188183          case TRAINING_SERIES:
    189             predictedValues = this.visualModel.PredictedTrainingValues;
    190             targetValues = this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName, this.visualModel.TrainingSamplesStart, this.visualModel.TrainingSamplesEnd);
    191             break;
    192           case validationSeries:
    193             predictedValues = this.visualModel.PredictedValidationValues;
    194             targetValues = this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName, this.visualModel.ValidationSamplesStart, this.visualModel.ValidationSamplesEnd);
     184            predictedValues = Content.EstimatedTrainingValues;
     185            targetValues = dataset.GetVariableValues(targetVariableName, trainingStart, trainingEnd);
    195186            break;
    196187          case TEST_SERIES:
    197             predictedValues = this.visualModel.PredictedTestValues;
    198             targetValues = this.visualModel.Dataset.GetVariableValues(this.visualModel.TargetVariableName, this.visualModel.TestSamplesStart, this.visualModel.TestSamplesEnd);
     188            predictedValues = Content.EstimatedTestValues;
     189            targetValues = dataset.GetVariableValues(targetVariableName, testStart, testEnd);
    199190            break;
    200191        }
    201         series.Points.DataBindXY(predictedValues.ToArray(), "", targetValues, "");
     192        series.Points.DataBindXY(predictedValues, "", targetValues, "");
    202193        this.chart.Legends[series.Legend].ForeColor = Color.Black;
    203194      }
     
    227218      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[ALL_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
    228219      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[TRAINING_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
    229       e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[validationSeries].Points.Count == 0 ? Color.Gray : Color.Black;
    230       e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[TEST_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
    231     }
    232 
    233 
    234     private void ScatterPlotView_DragDrop(object sender, DragEventArgs e) {
    235       IVisualModel model = this.ExtractModel(e.Data);
    236       if (model != null) {
    237         this.VisualModel = model;
    238       }
    239     }
    240 
    241     private void ScatterPlotView_DragEnter(object sender, DragEventArgs e) {
    242       IVisualModel model = this.ExtractModel(e.Data);
    243       if (model != null)
    244         e.Effect = DragDropEffects.Link;
    245       else
    246         e.Effect = DragDropEffects.None;
     220      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[TEST_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
    247221    }
    248222  }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/DataAnalysisProblemData.cs

    r3376 r3442  
    3636  [StorableClass]
    3737  public class DataAnalysisProblemData : NamedItem {
     38    [Storable]
     39    private VariableCollection variables;
     40    public VariableCollection Variables {
     41      get { return variables; }
     42    }
     43
     44    #region variable properties
     45    public IVariable DatasetVariable {
     46      get { return variables["Dataset"]; }
     47    }
     48
     49    public IVariable TargetVariableVariable {
     50      get { return variables["TargetVariable"]; }
     51    }
     52
     53    public IVariable InputVariablesVariable {
     54      get { return variables["InputVariables"]; }
     55    }
     56
     57    public IVariable TrainingSamplesStartVariable {
     58      get { return variables["TrainingSamplesStart"]; }
     59    }
     60    public IVariable TrainingSamplesEndVariable {
     61      get { return variables["TrainingSamplesEnd"]; }
     62    }
     63
     64    public IVariable TestSamplesStartVariable {
     65      get { return variables["TestSamplesStart"]; }
     66    }
     67    public IVariable TestSamplesEndVariable {
     68      get { return variables["TestSamplesEnd"]; }
     69    }
     70    #endregion
     71
    3872    #region properties
    39     private Dataset dataset;
    40     [Storable]
    4173    public Dataset Dataset {
    42       get { return dataset; }
    43       set {
    44         if (dataset != value) {
    45           if (value == null) throw new ArgumentNullException();
    46           else {
    47             dataset = value;
    48             OnDatasetChanged(EventArgs.Empty);
    49           }
    50         }
    51       }
    52     }
    53     private StringValue targetVariable;
    54     [Storable]
     74      get { return (Dataset)DatasetVariable.Value; }
     75      set {
     76        if (value != Dataset) {
     77          if (value == null) throw new ArgumentNullException();
     78          if (Dataset != null) DeregisterDatasetEventHandlers();
     79          DatasetVariable.Value = value;
     80          RegisterDatasetEventHandlers();
     81          OnProblemDataChanged(EventArgs.Empty);
     82        }
     83      }
     84    }
    5585    public StringValue TargetVariable {
    56       get { return targetVariable; }
    57       set { targetVariable = value; }
    58     }
    59     private ItemList<StringValue> inputVariables;
    60     [Storable]
     86      get { return (StringValue)TargetVariableVariable.Value; }
     87      set {
     88        if (value != TargetVariableVariable) {
     89          if (value == null) throw new ArgumentNullException();
     90          if (TargetVariable != null) DeregisterStringValueEventHandlers(TargetVariable);
     91          TargetVariableVariable.Value = value;
     92          RegisterStringValueEventHandlers(TargetVariable);
     93          OnProblemDataChanged(EventArgs.Empty);
     94        }
     95      }
     96    }
    6197    public ItemList<StringValue> InputVariables {
    62       get { return inputVariables; }
    63       set {
    64         if (inputVariables != value) {
    65           if (value == null) throw new ArgumentNullException();
    66           else {
    67             inputVariables = value;
    68             OnInputVariablesChanged(EventArgs.Empty);
    69           }
    70         }
    71       }
    72     }
    73     private IntValue trainingSamplesStart;
    74     [Storable]
     98      get { return (ItemList<StringValue>)InputVariablesVariable.Value; }
     99      set {
     100        if (value != InputVariables) {
     101          if (value == null) throw new ArgumentNullException();
     102          if (InputVariables != null) DeregisterInputVariablesEventHandlers();
     103          InputVariablesVariable.Value = value;
     104          RegisterInputVariablesEventHandlers();
     105          OnProblemDataChanged(EventArgs.Empty);
     106        }
     107      }
     108    }
    75109    public IntValue TrainingSamplesStart {
    76       get { return trainingSamplesStart; }
    77       set { trainingSamplesStart = value; }
    78     }
    79     private IntValue trainingSamplesEnd;
    80     [Storable]
     110      get { return (IntValue)TrainingSamplesStartVariable.Value; }
     111      set {
     112        if (value != TrainingSamplesStart) {
     113          if (value == null) throw new ArgumentNullException();
     114          if (TrainingSamplesStart != null) DeregisterValueTypeEventHandlers(TrainingSamplesStart);
     115          TrainingSamplesStartVariable.Value = value;
     116          RegisterValueTypeEventHandlers(TrainingSamplesStart);
     117          OnProblemDataChanged(EventArgs.Empty);
     118        }
     119      }
     120    }
    81121    public IntValue TrainingSamplesEnd {
    82       get { return trainingSamplesEnd; }
    83       set { trainingSamplesEnd = value; }
    84     }
    85     private IntValue validationSamplesStart;
    86     [Storable]
    87     public IntValue ValidationSamplesStart {
    88       get { return validationSamplesStart; }
    89       set { validationSamplesStart = value; }
    90     }
    91     private IntValue validationSamplesEnd;
    92     [Storable]
    93     public IntValue ValidationSamplesEnd {
    94       get { return validationSamplesEnd; }
    95       set { validationSamplesEnd = value; }
    96     }
    97     private IntValue testSamplesStart;
    98     [Storable]
     122      get { return (IntValue)TrainingSamplesEndVariable.Value; }
     123      set {
     124        if (value != TrainingSamplesEnd) {
     125          if (value == null) throw new ArgumentNullException();
     126          if (TrainingSamplesEnd != null) DeregisterValueTypeEventHandlers(TrainingSamplesEnd);
     127          TrainingSamplesEndVariable.Value = value;
     128          RegisterValueTypeEventHandlers(TrainingSamplesEnd);
     129          OnProblemDataChanged(EventArgs.Empty);
     130        }
     131      }
     132    }
    99133    public IntValue TestSamplesStart {
    100       get { return testSamplesStart; }
    101       set { testSamplesStart = value; }
    102     }
    103     private IntValue testSamplesEnd;
    104     [Storable]
     134      get { return (IntValue)TestSamplesStartVariable.Value; }
     135      set {
     136        if (value != TestSamplesStart) {
     137          if (value == null) throw new ArgumentNullException();
     138          if (TestSamplesStart != null) DeregisterValueTypeEventHandlers(TestSamplesStart);
     139          TestSamplesStartVariable.Value = value;
     140          RegisterValueTypeEventHandlers(TestSamplesStart);
     141          OnProblemDataChanged(EventArgs.Empty);
     142        }
     143      }
     144    }
    105145    public IntValue TestSamplesEnd {
    106       get { return testSamplesEnd; }
    107       set { testSamplesEnd = value; }
     146      get { return (IntValue)TestSamplesEndVariable.Value; }
     147      set {
     148        if (value != TestSamplesEnd) {
     149          if (value == null) throw new ArgumentNullException();
     150          if (TestSamplesEnd != null) DeregisterValueTypeEventHandlers(TestSamplesEnd);
     151          TestSamplesEndVariable.Value = value;
     152          RegisterValueTypeEventHandlers(TestSamplesEnd);
     153          OnProblemDataChanged(EventArgs.Empty);
     154        }
     155      }
    108156    }
    109157    #endregion
     
    111159    public DataAnalysisProblemData()
    112160      : base() {
    113       dataset = new Dataset();
    114       targetVariable = new StringValue();
    115       inputVariables = new ItemList<StringValue>();
    116       trainingSamplesStart = new IntValue();
    117       trainingSamplesEnd = new IntValue();
    118       validationSamplesStart = new IntValue();
    119       validationSamplesEnd = new IntValue();
    120       testSamplesStart = new IntValue();
    121       testSamplesEnd = new IntValue();
     161      variables = new VariableCollection();
     162      variables.Add(new Variable("Dataset", new Dataset()));
     163      variables.Add(new Variable("InputVariables", new ItemList<StringValue>()));
     164      variables.Add(new Variable("TargetVariable", new StringValue()));
     165      variables.Add(new Variable("TrainingSamplesStart", new IntValue()));
     166      variables.Add(new Variable("TrainingSamplesEnd", new IntValue()));
     167      variables.Add(new Variable("TestSamplesStart", new IntValue()));
     168      variables.Add(new Variable("TestSamplesEnd", new IntValue()));
     169      RegisterEventHandlers();
    122170    }
    123171
     
    125173    private DataAnalysisProblemData(bool deserializing) : base() { }
    126174
     175    [StorableHook(HookType.AfterDeserialization)]
     176    private void AfterDeserializationHook() {
     177      RegisterEventHandlers();
     178    }
     179
    127180    #region events
    128     public event EventHandler InputVariablesChanged;
    129     protected virtual void OnInputVariablesChanged(EventArgs e) {
    130       var listeners = InputVariablesChanged;
     181    private void RegisterEventHandlers() {
     182      RegisterDatasetEventHandlers();
     183      RegisterInputVariablesEventHandlers();
     184      RegisterStringValueEventHandlers(TargetVariable);
     185      RegisterValueTypeEventHandlers(TrainingSamplesStart);
     186      RegisterValueTypeEventHandlers(TrainingSamplesEnd);
     187      RegisterValueTypeEventHandlers(TestSamplesStart);
     188      RegisterValueTypeEventHandlers(TestSamplesEnd);
     189    }
     190
     191    public event EventHandler ProblemDataChanged;
     192    protected virtual void OnProblemDataChanged(EventArgs e) {
     193      var listeners = ProblemDataChanged;
    131194      if (listeners != null) listeners(this, e);
    132195    }
    133196
    134     public event EventHandler DatasetChanged;
    135     protected virtual void OnDatasetChanged(EventArgs e) {
    136       EventHandler handler = DatasetChanged;
    137       if (handler != null) handler(this, e);
    138     }
     197
     198    private void RegisterValueTypeEventHandlers<T>(ValueTypeValue<T> value) where T : struct {
     199      value.ValueChanged += new EventHandler(value_ValueChanged);
     200    }
     201
     202    private void DeregisterValueTypeEventHandlers<T>(ValueTypeValue<T> value) where T : struct {
     203      value.ValueChanged -= new EventHandler(value_ValueChanged);
     204    }
     205
     206    void value_ValueChanged(object sender, EventArgs e) {
     207      OnProblemDataChanged(e);
     208    }
     209
     210    private void RegisterStringValueEventHandlers(StringValue value) {
     211      value.ValueChanged += new EventHandler(value_ValueChanged);
     212    }
     213
     214    private void DeregisterStringValueEventHandlers(StringValue value) {
     215      value.ValueChanged -= new EventHandler(value_ValueChanged);
     216    }
     217
     218    private void RegisterDatasetEventHandlers() {
     219      Dataset.DataChanged += new EventHandler<EventArgs<int, int>>(Dataset_DataChanged);
     220      Dataset.Reset += new EventHandler(Dataset_Reset);
     221      Dataset.ColumnNamesChanged += new EventHandler(Dataset_ColumnNamesChanged);
     222    }
     223
     224    private void DeregisterDatasetEventHandlers() {
     225      Dataset.DataChanged -= new EventHandler<EventArgs<int, int>>(Dataset_DataChanged);
     226      Dataset.Reset -= new EventHandler(Dataset_Reset);
     227      Dataset.ColumnNamesChanged -= new EventHandler(Dataset_ColumnNamesChanged);
     228    }
     229
     230    void Dataset_ColumnNamesChanged(object sender, EventArgs e) {
     231      OnProblemDataChanged(e);
     232    }
     233
     234    void Dataset_Reset(object sender, EventArgs e) {
     235      OnProblemDataChanged(e);
     236    }
     237
     238    void Dataset_DataChanged(object sender, EventArgs<int, int> e) {
     239      OnProblemDataChanged(e);
     240    }
     241
     242    private void RegisterInputVariablesEventHandlers() {
     243      InputVariables.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_CollectionReset);
     244      InputVariables.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsAdded);
     245      InputVariables.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsRemoved);
     246      InputVariables.ItemsReplaced += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsReplaced);
     247      foreach (var item in InputVariables)
     248        item.ValueChanged += new EventHandler(InputVariables_Value_ValueChanged);
     249    }
     250
     251    private void DeregisterInputVariablesEventHandlers() {
     252      InputVariables.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_CollectionReset);
     253      InputVariables.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsAdded);
     254      InputVariables.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsRemoved);
     255      InputVariables.ItemsReplaced -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsReplaced);
     256      foreach (var item in InputVariables) {
     257        item.ValueChanged -= new EventHandler(InputVariables_Value_ValueChanged);
     258      }
     259    }
     260
     261    void InputVariables_ItemsReplaced(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
     262      foreach (var indexedItem in e.OldItems)
     263        indexedItem.Value.ValueChanged -= new EventHandler(InputVariables_Value_ValueChanged);
     264      foreach (var indexedItem in e.Items)
     265        indexedItem.Value.ValueChanged += new EventHandler(InputVariables_Value_ValueChanged);
     266      OnProblemDataChanged(e);
     267    }
     268
     269    void InputVariables_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
     270      foreach (var indexedItem in e.Items)
     271        indexedItem.Value.ValueChanged -= new EventHandler(InputVariables_Value_ValueChanged);
     272      OnProblemDataChanged(e);
     273    }
     274
     275    void InputVariables_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
     276      foreach (var indexedItem in e.Items)
     277        indexedItem.Value.ValueChanged += new EventHandler(InputVariables_Value_ValueChanged);
     278      OnProblemDataChanged(e);
     279    }
     280
     281    void InputVariables_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
     282      foreach (var indexedItem in e.OldItems)
     283        indexedItem.Value.ValueChanged -= new EventHandler(InputVariables_Value_ValueChanged);
     284
     285      OnProblemDataChanged(e);
     286    }
     287    void InputVariables_Value_ValueChanged(object sender, EventArgs e) {
     288      OnProblemDataChanged(e);
     289    }
     290
    139291    #endregion
    140292
     
    147299      TargetVariable = new StringValue(Dataset.VariableNames.First());
    148300      InputVariables = new ItemList<StringValue>(Dataset.VariableNames.Skip(1).Select(s => new StringValue(s)));
     301      int middle = (int)(csvFileParser.Rows * 0.5);
    149302      TrainingSamplesStart = new IntValue(0);
    150       TrainingSamplesEnd = new IntValue(csvFileParser.Rows);
    151       TestSamplesStart = new IntValue(0);
     303      TrainingSamplesEnd = new IntValue(middle);
     304      TestSamplesStart = new IntValue(middle);
    152305      TestSamplesEnd = new IntValue(csvFileParser.Rows);
     306    }
     307
     308    public override IDeepCloneable Clone(Cloner cloner) {
     309      DataAnalysisProblemData clone = (DataAnalysisProblemData)base.Clone(cloner);
     310      clone.variables = (VariableCollection)variables.Clone(cloner);
     311
     312      clone.RegisterEventHandlers();
     313      return clone;
    153314    }
    154315  }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/DataAnalysisSolution.cs

    r3431 r3442  
    2626using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2727using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     28using System.Collections.Generic;
     29using System.Linq;
    2830
    2931namespace HeuristicLab.Problems.DataAnalysis {
     
    3335  [Item("DataAnalysisSolution", "Represents a solution for a data analysis problem which can be visualized in the GUI.")]
    3436  [StorableClass]
    35   public sealed class DataAnalysisSolution : Item {
     37  public class DataAnalysisSolution : Item {
    3638    [Storable]
    37     private IPredictor predictor;
    38     public IPredictor Predictor {
    39       get { return predictor; }
     39    private IModel model;
     40    public IModel Model {
     41      get { return model; }
    4042      set {
    41         if (predictor != value) {
    42           predictor = value;
    43           OnPredictorChanged();
     43        if (model != value) {
     44          model = value;
     45          OnModelChanged();
    4446        }
    4547      }
     
    5254      set {
    5355        if (problemData != value) {
     56          if (value == null) throw new ArgumentNullException();
    5457          if (problemData != null) DeregisterProblemDataEvents();
    5558          problemData = value;
    56           if (problemData != null) RegisterProblemDataEvents();
     59          RegisterProblemDataEvents();
    5760          OnProblemDataChanged();
    5861        }
    5962      }
    6063    }
    61    
     64
     65    private List<double> estimatedValues;
     66    public IEnumerable<double> EstimatedValues {
     67      get {
     68        return estimatedValues;
     69      }
     70    }
     71
     72    private List<double> estimatedTrainingValues;
     73    public IEnumerable<double> EstimatedTrainingValues {
     74      get {
     75        return estimatedTrainingValues;
     76      }
     77    }
     78
     79    private List<double> estimatedTestValues;
     80    public IEnumerable<double> EstimatedTestValues {
     81      get {
     82        return estimatedTestValues;
     83      }
     84    }
     85
    6286    public DataAnalysisSolution() : base() { }
    63     public DataAnalysisSolution(DataAnalysisProblemData problemData, IPredictor predictor)
     87    public DataAnalysisSolution(DataAnalysisProblemData problemData, IModel model)
    6488      : this() {
    6589      this.problemData = problemData;
    66       this.predictor = predictor;
     90      this.model = model;
    6791      Initialize();
    6892    }
     93
    6994    [StorableConstructor]
    7095    private DataAnalysisSolution(bool deserializing) : base(deserializing) { }
     
    75100    }
    76101
     102    private void RecalculateEstimatedValues() {
     103      estimatedValues = GetEstimatedValues(0, problemData.Dataset.Rows).ToList();
     104      int nTrainingValues = problemData.TrainingSamplesEnd.Value - problemData.TrainingSamplesStart.Value;
     105      estimatedTrainingValues = estimatedValues.Skip(problemData.TrainingSamplesStart.Value).Take(nTrainingValues).ToList();
     106      int nTestValues = problemData.TestSamplesEnd.Value - problemData.TestSamplesStart.Value;
     107      estimatedTestValues = estimatedValues.Skip(problemData.TestSamplesStart.Value).Take(nTestValues).ToList();
     108    }
     109
     110    private IEnumerable<double> GetEstimatedValues(int start, int end) {
     111      double[] xs = new double[ProblemData.InputVariables.Count];
     112      for (int row = 0; row < ProblemData.Dataset.Rows; row++) {
     113        for (int i = 0; i < xs.Length; i++) {
     114          var variableIndex = ProblemData.Dataset.GetVariableIndex(ProblemData.InputVariables[i].Value);
     115          xs[i] = ProblemData.Dataset[row, variableIndex];
     116        }
     117        yield return model.GetValue(xs);
     118      }
     119    }
     120
    77121    public override IDeepCloneable Clone(Cloner cloner) {
    78122      DataAnalysisSolution clone = new DataAnalysisSolution();
    79123      cloner.RegisterClonedObject(this, clone);
    80       clone.predictor = (IPredictor)cloner.Clone(predictor);
     124      clone.model = (IModel)cloner.Clone(model);
    81125      clone.problemData = problemData;
    82126      clone.Initialize();
     
    85129
    86130    #region Events
    87     public event EventHandler PredictorChanged;
    88     private void OnPredictorChanged() {
    89       var changed = PredictorChanged;
     131    public event EventHandler ModelChanged;
     132    private void OnModelChanged() {
     133      RecalculateEstimatedValues();
     134      var changed = ModelChanged;
    90135      if (changed != null)
    91136        changed(this, EventArgs.Empty);
     
    93138    public event EventHandler ProblemDataChanged;
    94139    private void OnProblemDataChanged() {
     140      RecalculateEstimatedValues();
    95141      var changed = ProblemDataChanged;
    96142      if (changed != null)
     
    99145
    100146    private void RegisterProblemDataEvents() {
    101       ProblemData.DatasetChanged += new EventHandler(ProblemData_DataSetChanged);
     147      ProblemData.ProblemDataChanged += new EventHandler(ProblemData_Changed);
    102148    }
    103149    private void DeregisterProblemDataEvents() {
    104       ProblemData.DatasetChanged += new EventHandler(ProblemData_DataSetChanged);
     150      ProblemData.ProblemDataChanged += new EventHandler(ProblemData_Changed);
    105151    }
    106152
    107     private void ProblemData_DataSetChanged(object sender, EventArgs e) {
     153    private void ProblemData_Changed(object sender, EventArgs e) {
    108154      OnProblemDataChanged();
    109155    }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Dataset.cs

    r3431 r3442  
    3636  public sealed class Dataset : NamedItem, IStringConvertibleMatrix {
    3737    public Dataset()
    38       : this(new string[0], new double[,] { { } }) {
     38      : this(new string[1] { "y" }, new double[,] { { 0.0 } }) {
    3939    }
    4040
     
    4545        throw new ArgumentException("Number of variable names doesn't match the number of columns of data");
    4646      }
    47       Data = data;
    48       this.VariableNames = variableNames;
     47      this.data = data;
     48      this.variableNames = variableNames.ToArray();
    4949      this.SortableView = false;
    5050    }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/HeuristicLab.Problems.DataAnalysis-3.3.csproj

    r3408 r3442  
    9393    <Compile Include="Evaluators\SimpleMSEEvaluator.cs" />
    9494    <Compile Include="HeuristicLabProblemsDataAnalysisPlugin.cs" />
    95     <Compile Include="Interfaces\IPredictor.cs" />
     95    <Compile Include="Interfaces\IModel.cs" />
    9696    <Compile Include="MatrixExtensions.cs" />
    9797    <Compile Include="Properties\AssemblyInfo.cs" />
    9898    <Compile Include="Symbolic\ArithmeticExpressionGrammar.cs" />
    9999    <Compile Include="Symbolic\SimpleArithmeticExpressionEvaluator.cs" />
     100    <Compile Include="Symbolic\SymbolicSimplifier.cs" />
    100101    <Compile Include="Symbolic\Symbols\Constant.cs" />
    101102    <Compile Include="Symbolic\Symbols\ConstantTreeNode.cs" />
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Interfaces/IModel.cs

    r3409 r3442  
    3131
    3232namespace HeuristicLab.Problems.DataAnalysis {
    33   public interface IPredictor : IDeepCloneable {
    34     double Estimate(double[] xs);
     33  public interface IModel : IDeepCloneable {
     34    double GetValue(double[] xs);
    3535  }
    3636}
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/ArithmeticExpressionGrammar.cs

    r3376 r3442  
    3535  public class ArithmeticExpressionGrammar : DefaultSymbolicExpressionGrammar {
    3636    [Storable]
    37     private List<string> variableNames = new List<string>();
    38     public IEnumerable<string> VariableNames {
    39       get { return variableNames; }
    40       set {
    41         variableNames = new List<string>(value);
    42         variableSymbol.VariableNames = variableNames;
    43       }
    44     }
    45 
    46     [Storable]
    4737    private HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable variableSymbol;
    4838
     
    5848      var div = new Division();
    5949      var constant = new Constant();
     50      constant.MinValue = -20;
     51      constant.MaxValue = 20;
    6052      variableSymbol = new HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable();
    6153
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/SimpleArithmeticExpressionEvaluator.cs

    r3409 r3442  
    4444        this.row = row;
    4545        pc = 0;
    46         arguments.Clear();
     46        argumentStack.Clear();
    4747        var estimatedValue = Evaluate();
    4848        if (double.IsNaN(estimatedValue) || double.IsInfinity(estimatedValue)) yield return 0.0;
     
    5151    }
    5252
    53     private List<double> arguments = new List<double>();
     53    private Stack<List<double>> argumentStack = new Stack<List<double>>();
    5454    public double Evaluate() {
    5555      var currentInstr = code[pc++];
     
    8585        case CodeSymbol.Call: {
    8686            // save current arguments
    87             var oldArgs = new List<double>(arguments);
    88             arguments.Clear();
     87            List<double> arguments = new List<double>();
    8988            // evaluate sub-trees
    9089            for (int i = 0; i < currentInstr.nArguments; i++) {
    9190              arguments.Add(Evaluate());
    9291            }
     92            argumentStack.Push(arguments);
    9393            // save the pc
    9494            int nextPc = pc;
     
    9797            // evaluate the function
    9898            double v = Evaluate();
     99            argumentStack.Pop();
    99100            // restore the pc => evaluation will continue at point after my subtrees 
    100101            pc = nextPc;
    101             // restore arguments
    102             arguments = oldArgs;
    103102            return v;
    104103          }
    105104        case CodeSymbol.Arg: {
    106             return arguments[currentInstr.iArg0];
     105            return argumentStack.Peek()[currentInstr.iArg0];
    107106          }
    108107        case CodeSymbol.Dynamic: {
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/Symbols/ConstantTreeNode.cs

    r3376 r3442  
    3434      get { return (Constant)base.Symbol; }
    3535    }
    36     public override bool HasLocalParameters {
    37       get {
    38         return true;
    39       }
    40     }
    4136
    4237    private double constantValue;
     
    5449    public ConstantTreeNode(Constant constantSymbol) : base(constantSymbol) { }
    5550
     51    public override bool HasLocalParameters {
     52      get {
     53        return true;
     54      }
     55    }
    5656    public override void ResetLocalParameters(IRandom random) {
    5757      base.ResetLocalParameters(random);
     
    6363      return new ConstantTreeNode(this);
    6464    }
     65
     66    public override string ToString() {
     67      return constantValue.ToString("E5");
     68    }
    6569  }
    6670}
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/Symbols/Variable.cs

    r3376 r3442  
    5252    private List<string> variableNames;
    5353    [Storable]
    54     public ICollection<string> VariableNames {
     54    public IEnumerable<string> VariableNames {
    5555      get { return variableNames; }
    5656      set {
  • trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/Symbols/VariableTreeNode.cs

    r3376 r3442  
    5656    public VariableTreeNode(Variable variableSymbol) : base(variableSymbol) { }
    5757
     58    public override bool HasLocalParameters {
     59      get {
     60        return true;
     61      }
     62    }
     63
    5864    public override void ResetLocalParameters(IRandom random) {
    5965      base.ResetLocalParameters(random);
     
    6874      return new VariableTreeNode(this);
    6975    }
     76
     77    public override string ToString() {
     78      return weight.ToString("E5") + " * " + variableName;
     79    }
    7080  }
    7181}
Note: See TracChangeset for help on using the changeset viewer.