Free cookie consent management tool by TermsFeed Policy Generator

Changeset 18175


Ignore:
Timestamp:
01/03/22 11:49:24 (3 years ago)
Author:
gkronber
Message:

#3140: merged r18136:18138,r18153,r18165:18174 from trunk to branch

Location:
branches/3140_NumberSymbol
Files:
37 edited

Legend:

Unmodified
Added
Removed
  • branches/3140_NumberSymbol

  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views

  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonDateTimeFilterView.cs

    r17180 r18175  
    5252
    5353    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    54       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     54      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    5555        label.Focus();  // set focus on label to validate data
    56       if (e.KeyCode == Keys.Escape) {
     56        e.SuppressKeyPress = true;
     57      } else if (e.KeyCode == Keys.Escape) {
    5758        valueTextBox.Text = Content.Value.ToString();
    5859        label.Focus();  // set focus on label to validate data
     60        e.SuppressKeyPress = true;
    5961      }
    6062    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonDoubleFilterView.cs

    r17180 r18175  
    5151
    5252    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    53       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     53      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    5454        label.Focus();  // set focus on label to validate data
    55       if (e.KeyCode == Keys.Escape) {
     55        e.SuppressKeyPress = true;
     56      } else if (e.KeyCode == Keys.Escape) {
    5657        valueTextBox.Text = Content.Value.ToString();
    5758        label.Focus();  // set focus on label to validate data
     59        e.SuppressKeyPress = true;
    5860      }
    5961    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonFloatFilterView.cs

    r17180 r18175  
    5151
    5252    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    53       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     53      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    5454        label.Focus();  // set focus on label to validate data
    55       if (e.KeyCode == Keys.Escape) {
     55        e.SuppressKeyPress = true;
     56      } else if (e.KeyCode == Keys.Escape) {
    5657        valueTextBox.Text = Content.Value.ToString();
    5758        label.Focus();  // set focus on label to validate data
     59        e.SuppressKeyPress = true;
    5860      }
    5961    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonIntFilterView.cs

    r17180 r18175  
    5151
    5252    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    53       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     53      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    5454        label.Focus();  // set focus on label to validate data
    55       if (e.KeyCode == Keys.Escape) {
     55        e.SuppressKeyPress = true;
     56      } else if (e.KeyCode == Keys.Escape) {
    5657        valueTextBox.Text = Content.Value.ToString();
    5758        label.Focus();  // set focus on label to validate data
     59        e.SuppressKeyPress = true;
    5860      }
    5961    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonLongFilterView.cs

    r17180 r18175  
    5151
    5252    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    53       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     53      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    5454        label.Focus();  // set focus on label to validate data
    55       if (e.KeyCode == Keys.Escape) {
     55        e.SuppressKeyPress = true;
     56      } else if (e.KeyCode == Keys.Escape) {
    5657        valueTextBox.Text = Content.Value.ToString();
    5758        label.Focus();  // set focus on label to validate data
     59        e.SuppressKeyPress = true;
    5860      }
    5961    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonPercentFilterView.cs

    r17180 r18175  
    5858
    5959    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    60       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     60      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    6161        label.Focus();  // set focus on label to validate data
    62       if (e.KeyCode == Keys.Escape) {
     62        e.SuppressKeyPress = true;
     63      } else if (e.KeyCode == Keys.Escape) {
    6364        valueTextBox.Text = Content.Value.ToString();
    6465        label.Focus();  // set focus on label to validate data
     66        e.SuppressKeyPress = true;
    6567      }
    6668    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/OrdinalComparisonTimeSpanFilterView.cs

    r17180 r18175  
    5959
    6060    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    61       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     61      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    6262        label.Focus();  // set focus on label to validate data
    63       if (e.KeyCode == Keys.Escape) {
     63        e.SuppressKeyPress = true;
     64      } else if (e.KeyCode == Keys.Escape) {
    6465        valueTextBox.Text = Content.Value.ToString();
    6566        label.Focus();  // set focus on label to validate data
     67        e.SuppressKeyPress = true;
    6668      }
    6769    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/StringComparisonAvailableValuesFilterView.cs

    r17180 r18175  
    8282
    8383    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    84       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     84      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    8585        label.Focus();  // set focus on label to validate data
    86       if (e.KeyCode == Keys.Escape) {
     86        e.SuppressKeyPress = true;
     87      } else if (e.KeyCode == Keys.Escape) {
    8788        valueComboBox.Text = Content.Value;
    8889        label.Focus();  // set focus on label to validate data
     90        e.SuppressKeyPress = true;
    8991      }
    9092    }
  • branches/3140_NumberSymbol/HeuristicLab.Clients.OKB.Views/3.3/Query/Views/StringComparisonFilterView.cs

    r17180 r18175  
    8282
    8383    private void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    84       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     84      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    8585        label.Focus();  // set focus on label to validate data
    86       if (e.KeyCode == Keys.Escape) {
     86        e.SuppressKeyPress = true;
     87      } else if (e.KeyCode == Keys.Escape) {
    8788        valueTextBox.Text = Content.Value;
    8889        label.Focus();  // set focus on label to validate data
     90        e.SuppressKeyPress = true;
    8991      }
    9092    }
  • branches/3140_NumberSymbol/HeuristicLab.Core.Views

  • branches/3140_NumberSymbol/HeuristicLab.Core.Views/3.3/NamedItemView.cs

    r17180 r18175  
    119119    }
    120120    protected virtual void nameTextBox_KeyDown(object sender, KeyEventArgs e) {
    121       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     121      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    122122        nameLabel.Focus();  // set focus on label to validate data
    123       if (e.KeyCode == Keys.Escape) {
     123        e.SuppressKeyPress = true;
     124      } else if (e.KeyCode == Keys.Escape) {
    124125        nameTextBox.Text = Content.Name;
    125126        nameLabel.Focus();  // set focus on label to validate data
     127        e.SuppressKeyPress = true;
    126128      }
    127129    }
  • branches/3140_NumberSymbol/HeuristicLab.Data.Views

  • branches/3140_NumberSymbol/HeuristicLab.Data.Views/3.3

  • branches/3140_NumberSymbol/HeuristicLab.Data.Views/3.3/StringConvertibleArrayView.cs

    r17180 r18175  
    156156    }
    157157    private void lengthTextBox_KeyDown(object sender, KeyEventArgs e) {
    158       if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
     158      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
    159159        lengthLabel.Focus();  // set focus on label to validate data
    160       if (e.KeyCode == Keys.Escape) {
     160        e.SuppressKeyPress = true;
     161      } else if (e.KeyCode == Keys.Escape) {
    161162        lengthTextBox.Text = Content.Length.ToString();
    162163        lengthLabel.Focus();  // set focus on label to validate data
     164        e.SuppressKeyPress = true;
    163165      }
    164166    }
     
    249251        clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
    250252
    251       var lines = clipboardText.Split(new [] { Environment.NewLine }, StringSplitOptions.None);
     253      var lines = clipboardText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
    252254      var tabSep = new[] { '\t' };
    253255      if (lines.Length > 2) {
  • branches/3140_NumberSymbol/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs

    r17921 r18175  
    227227    }
    228228    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
    229       if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
     229      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
    230230        rowsLabel.Focus();  // set focus on label to validate data
    231       if (e.KeyCode == Keys.Escape) {
     231        e.SuppressKeyPress = true;
     232      } else if (e.KeyCode == Keys.Escape) {
    232233        rowsTextBox.Text = Content.Rows.ToString();
    233234        rowsLabel.Focus();  // set focus on label to validate data
     235        e.SuppressKeyPress = true;
    234236      }
    235237    }
     
    249251    }
    250252    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
    251       if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
     253      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
    252254        columnsLabel.Focus();  // set focus on label to validate data
    253       if (e.KeyCode == Keys.Escape) {
     255        e.SuppressKeyPress = true;
     256      } else if (e.KeyCode == Keys.Escape) {
    254257        columnsTextBox.Text = Content.Columns.ToString();
    255258        columnsLabel.Focus();  // set focus on label to validate data
     259        e.SuppressKeyPress = true;
    256260      }
    257261    }
  • branches/3140_NumberSymbol/HeuristicLab.Data.Views/3.3/StringConvertibleValueView.cs

    r17180 r18175  
    8686
    8787    protected virtual void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    88       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     88      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    8989        valueLabel.Select();  // select label to validate data
    90 
    91       if (e.KeyCode == Keys.Escape) {
     90        e.SuppressKeyPress = true;
     91      } else if (e.KeyCode == Keys.Escape) {
    9292        valueTextBox.Text = Content.GetValue();
    9393        valueLabel.Select();  // select label to validate data
     94        e.SuppressKeyPress = true;
    9495      }
    9596    }
  • branches/3140_NumberSymbol/HeuristicLab.Data.Views/3.3/TextValueView.cs

    r17180 r18175  
    8686
    8787    protected virtual void valueTextBox_KeyDown(object sender, KeyEventArgs e) {
    88       if (e.Shift && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return))
     88      if (e.Shift && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)) {
    8989        valueLabel.Select();  // select label to validate data
    90 
    91       if (e.KeyCode == Keys.Escape) {
     90        e.SuppressKeyPress = true;
     91      } else if (e.KeyCode == Keys.Escape) {
    9292        valueTextBox.Text = Content.GetValue();
    9393        valueLabel.Select();  // select label to validate data
     94        e.SuppressKeyPress = true;
    9495      }
    9596    }
  • branches/3140_NumberSymbol/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views

  • branches/3140_NumberSymbol/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.cs

    r17180 r18175  
    7070    #region control event handlers
    7171    private void initialFrequencyTextBox_KeyDown(object sender, KeyEventArgs e) {
    72       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     72      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    7373        initialFrequencyLabel.Select();  // select label to validate data
    74 
    75       if (e.KeyCode == Keys.Escape) {
     74        e.SuppressKeyPress = true;
     75      } else  if (e.KeyCode == Keys.Escape) {
    7676        initialFrequencyTextBox.Text = Content.InitialFrequency.ToString();
    7777        initialFrequencyLabel.Select();  // select label to validate data
     78        e.SuppressKeyPress = true;
    7879      }
    7980    }
  • branches/3140_NumberSymbol/HeuristicLab.Optimization

  • branches/3140_NumberSymbol/HeuristicLab.Optimization/3.3/BasicProblems/Operators/MultiEncodingOperator.cs

    r17180 r18175  
    3131namespace HeuristicLab.Optimization {
    3232  [StorableType("43619638-9D00-4951-8138-8CCD0786E784")]
    33   public abstract class MultiEncodingOperator<T> : Operator, IMultiEncodingOperator where T : class,IOperator {
     33  public abstract class MultiEncodingOperator<T> : Operator, IMultiEncodingOperator where T : class, IOperator {
    3434    private List<IEncoding> encodings = new List<IEncoding>();
    3535    [Storable(Name = "Encodings")]
     
    7171
    7272    public override IOperation Apply() {
    73       var operations = Parameters.Select(p => p.ActualValue).OfType<IOperator>().Select(op => ExecutionContext.CreateChildOperation(op));
     73      var operators = Parameters.OrderBy(p => p.Name).Select(p => p.ActualValue).OfType<IOperator>();
     74      var operations = operators.Select(op => ExecutionContext.CreateChildOperation(op));
    7475      return new OperationCollection(operations);
    7576    }
  • branches/3140_NumberSymbol/HeuristicLab.Parameters.Views/3.3/ScopeTreeLookupParameterView.cs

    r17180 r18175  
    106106    }
    107107    protected virtual void depthTextBox_KeyDown(object sender, KeyEventArgs e) {
    108       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     108      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    109109        depthLabel.Focus();  // set focus on label to validate data
    110       if (e.KeyCode == Keys.Escape) {
     110        e.SuppressKeyPress = true;
     111      } else if (e.KeyCode == Keys.Escape) {
    111112        depthTextBox.Text = Content.Depth.ToString();
    112113        depthLabel.Focus();  // set focus on label to validate data
     114        e.SuppressKeyPress = true;
    113115      }
    114116    }
  • branches/3140_NumberSymbol/HeuristicLab.Parameters/3.3/ValueLookupParameter.cs

    r17180 r18175  
    151151    }
    152152
     153    protected override IItem GetActualValue() {
     154      if (ExecutionContext == null)
     155        return Value;
     156      return base.GetActualValue();
     157    }
     158
    153159    public override string ToString() {
    154160      if (Value != null)
  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic

  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Converters/DerivativeCalculator.cs

    r18142 r18175  
    158158          var newExponent = (NumberTreeNode)numberSy.CreateTreeNode();
    159159          newExponent.Value = ((NumberTreeNode)newPower.GetSubtree(1)).Value - 1;
     160          newPower.RemoveSubtree(1);
     161          newPower.AddSubtree(newExponent);
    160162          return Product(Product(CreateNumber(exponent.Value), newPower), Derive(f, variableName));
    161163        } else throw new NotSupportedException("Cannot derive non-integer powers");
  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs

    r18115 r18175  
    3737        var token = GetToken(node.Symbol);
    3838        // operators
    39         if (token == "+" || token == "-" || token == "OR" || token == "XOR" ||
    40             token == "*" || token == "/" || token == "AND") {
    41           strBuilder.Append("(");
     39        if (token == "+" || token == "-" || token == "OR" || token == "XOR") {
     40          var parenthesisRequired = false;
     41          if (node.Parent != null && node.Parent.SubtreeCount > 1) {
     42            var parentOp = GetToken(node.Parent.Symbol);
     43            if (parentOp != "+" && parentOp != "-" && parentOp != "OR" && parentOp != "XOR")
     44              parenthesisRequired = true;
     45          }
     46          if (parenthesisRequired) strBuilder.Append("(");
    4247          FormatRecursively(node.Subtrees.First(), strBuilder, numberFormat, formatString, parameters);
    4348
     
    4752          }
    4853
    49           strBuilder.Append(")");
     54          if (parenthesisRequired) strBuilder.Append(")");
     55        } else if (token == "*" || token == "/" || token == "AND") {
     56          FormatRecursively(node.Subtrees.First(), strBuilder, numberFormat, formatString, parameters);
     57
     58          foreach (var subtree in node.Subtrees.Skip(1)) {
     59            strBuilder.Append(" ").Append(token).Append(" ");
     60            // a / b * c => a / (b * C)
     61            if (subtree.SubtreeCount > 1 && token == "/" && GetToken(subtree.Symbol) == "*") {
     62              strBuilder.Append("(");
     63              FormatRecursively(subtree, strBuilder, numberFormat, formatString, parameters);
     64              strBuilder.Append(")");
     65            } else {
     66              FormatRecursively(subtree, strBuilder, numberFormat, formatString, parameters);
     67            }
     68          }
    5069        } else if (token == "^") {
    5170          // handle integer powers directly
    52           strBuilder.Append("(");
    5371          FormatRecursively(node.Subtrees.First(), strBuilder, numberFormat, formatString, parameters);
    5472
    5573          var power = node.GetSubtree(1);
    56           if(power is INumericTreeNode numNode && Math.Truncate(numNode.Value) == numNode.Value) {
     74          if (power is INumericTreeNode numNode && Math.Truncate(numNode.Value) == numNode.Value) {
    5775            strBuilder.Append(" ").Append(token).Append(" ").Append(numNode.Value.ToString(formatString, numberFormat));
    5876          } else {
     
    6078            FormatRecursively(power, strBuilder, numberFormat, formatString, parameters);
    6179          }
    62 
    63           strBuilder.Append(")");
    6480        } else {
    6581          // function with multiple arguments
     
    7692        var token = GetToken(node.Symbol);
    7793        if (token == "-" || token == "NOT") {
    78           strBuilder.Append("(").Append(token).Append("(");
    79           FormatRecursively(node.GetSubtree(0), strBuilder, numberFormat, formatString, parameters);
    80           strBuilder.Append("))");
     94          strBuilder.Append(token);
     95          FormatRecursively(node.GetSubtree(0), strBuilder, numberFormat, formatString, parameters);
    8196        } else if (token == "/") {
    8297          strBuilder.Append("1/");
     
    95110          var varNode = node as LaggedVariableTreeNode;
    96111          if (!varNode.Weight.IsAlmost(1.0)) {
    97             strBuilder.Append("(");
    98112            AppendNumber(strBuilder, parameters, varNode.Weight, formatString, numberFormat);
    99113            strBuilder.Append("*");
     
    105119                    .AppendFormat(numberFormat, "{0}", varNode.Lag)
    106120                    .Append(")");
    107           if (!varNode.Weight.IsAlmost(1.0)) strBuilder.Append(")");
    108121        } else if (node.Symbol is Variable) {
    109122          var varNode = node as VariableTreeNode;
    110123          if (!varNode.Weight.IsAlmost(1.0)) {
    111             strBuilder.Append("(");
    112124            AppendNumber(strBuilder, parameters, varNode.Weight, formatString, numberFormat);
    113125            strBuilder.Append("*");
    114126          }
    115 
    116127          AppendVariableName(strBuilder, varNode.VariableName);
    117 
    118           if (!varNode.Weight.IsAlmost(1.0)) strBuilder.Append(")");
    119128        } else if (node.Symbol is FactorVariable) {
    120129          var factorNode = node as FactorVariableTreeNode;
     
    130139          var factorNode = node as BinaryFactorVariableTreeNode;
    131140          if (!factorNode.Weight.IsAlmost(1.0)) {
    132             strBuilder.Append("(");
    133141            AppendNumber(strBuilder, parameters, factorNode.Weight, formatString, numberFormat);
    134 
    135142            strBuilder.Append("*");
    136143          }
    137 
    138144          AppendVariableName(strBuilder, factorNode.VariableName);
    139145          strBuilder.Append(" = ");
    140146          AppendVariableName(strBuilder, factorNode.VariableValue);
    141 
    142           if (!factorNode.Weight.IsAlmost(1.0)) strBuilder.Append(")");
    143147        } else if (node is INumericTreeNode numNode) {
    144148          if (parameters == null && numNode.Value < 0) {
    145149            // negative value
    146             strBuilder.Append("(").Append(numNode.Value.ToString(formatString, numberFormat))
    147                       .Append(")");
     150            strBuilder.Append(numNode.Value.ToString(formatString, numberFormat));
    148151          } else {
    149152            AppendNumber(strBuilder, parameters, numNode.Value, formatString, numberFormat);
  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Importer/InfixExpressionParser.cs

    r18118 r18175  
    4040  ///
    4141  /// S             = Expr EOF
    42   /// Expr          = ['-' | '+'] Term { '+' Term | '-' Term }
     42  /// Expr          = Term { '+' Term | '-' Term }
    4343  /// Term          = Fact { '*' Fact | '/' Fact }
    4444  /// Fact          = SimpleFact [ '^' SimpleFact ]
     
    4949  ///                 | VarExpr
    5050  ///                 | number
     51  ///                 | ['+' | '-'] SimpleFact
    5152  /// ArgList       = Expr { ',' Expr }
    5253  /// VarExpr       = varId OptFactorPart
    53   /// OptFactorPart = [ ('=' varVal | '[' ['+' | '-' ] number {',' ['+' | '-' ] number } ']' ) ]
     54  /// OptFactorPart = [ ('=' varVal | '[' ['+' | '-' ]  number {',' ['+' | '-' ] number } ']' ) ]
    5455  /// varId         =  ident | ' ident ' | " ident "
    5556  /// varVal        =  ident | ' ident ' | " ident "
     
    8384
    8485    private Number number = new Number();
    85     private Constant constant = new Constant();
     86    private Constant minusOne = new Constant() { Value = -1 };
    8687    private Variable variable = new Variable();
    8788    private BinaryFactorVariable binaryFactorVar = new BinaryFactorVariable();
     
    162163      int pos = 0;
    163164      while (true) {
    164         while (pos < str.Length && Char.IsWhiteSpace(str[pos])) pos++;
     165        while (pos < str.Length && char.IsWhiteSpace(str[pos])) pos++;
    165166        if (pos >= str.Length) {
    166167          yield return new Token { TokenType = TokenType.End, strVal = "" };
     
    168169        }
    169170        if (char.IsDigit(str[pos])) {
    170           // read number (=> read until white space or operator or comma)
     171          // read number (=> read until white space or other symbol)
    171172          var sb = new StringBuilder();
    172173          sb.Append(str[pos]);
     
    269270        } else if (str[pos] == '<') {
    270271          pos++;
    271           yield return new Token {TokenType = TokenType.LeftAngleBracket, strVal = "<"};
     272          yield return new Token { TokenType = TokenType.LeftAngleBracket, strVal = "<" };
    272273        } else if (str[pos] == '>') {
    273274          pos++;
    274           yield return new Token {TokenType = TokenType.RightAngleBracket, strVal = ">"};
     275          yield return new Token { TokenType = TokenType.RightAngleBracket, strVal = ">" };
    275276        } else {
    276277          throw new ArgumentException("Invalid character: " + str[pos]);
     
    289290    }
    290291
    291     /// Expr          = ['-' | '+'] Term { '+' Term | '-' Term }
     292    /// Expr          = Term { '+' Term | '-' Term }
    292293    private ISymbolicExpressionTreeNode ParseExpr(Queue<Token> tokens) {
     294      // build tree from bottom to top and left to right
     295      // a + b - c => ((a + b) - c)
     296      // a - b - c => ((a - b) - c)
     297      // and then flatten as far as possible
     298      var left = ParseTerm(tokens);
     299
    293300      var next = tokens.Peek();
    294       var posTerms = new List<ISymbolicExpressionTreeNode>();
    295       var negTerms = new List<ISymbolicExpressionTreeNode>();
    296       bool negateFirstTerm = false;
    297       if (next.TokenType == TokenType.Operator && (next.strVal == "+" || next.strVal == "-")) {
    298         tokens.Dequeue();
    299         if (next.strVal == "-")
    300           negateFirstTerm = true;
    301       }
    302       var t = ParseTerm(tokens);
    303       if (negateFirstTerm) negTerms.Add(t);
    304       else posTerms.Add(t);
    305 
    306       next = tokens.Peek();
    307301      while (next.strVal == "+" || next.strVal == "-") {
    308302        switch (next.strVal) {
    309303          case "+": {
    310304              tokens.Dequeue();
    311               var term = ParseTerm(tokens);
    312               posTerms.Add(term);
     305              var right = ParseTerm(tokens);
     306              var op = GetSymbol("+").CreateTreeNode();
     307              op.AddSubtree(left);
     308              op.AddSubtree(right);
     309              left = op;
    313310              break;
    314311            }
    315312          case "-": {
    316313              tokens.Dequeue();
    317               var term = ParseTerm(tokens);
    318               negTerms.Add(term);
     314              var right = ParseTerm(tokens);
     315              var op = GetSymbol("-").CreateTreeNode();
     316              op.AddSubtree(left);
     317              op.AddSubtree(right);
     318              left = op;
    319319              break;
    320320            }
     
    323323      }
    324324
    325       var sum = GetSymbol("+").CreateTreeNode();
    326       foreach (var posTerm in posTerms) sum.AddSubtree(posTerm);
    327       if (negTerms.Any()) {
    328         if (negTerms.Count == 1) {
    329           var sub = GetSymbol("-").CreateTreeNode();
    330           sub.AddSubtree(negTerms.Single());
    331           sum.AddSubtree(sub);
    332         } else {
    333           var sumNeg = GetSymbol("+").CreateTreeNode();
    334           foreach (var negTerm in negTerms) sumNeg.AddSubtree(negTerm);
    335 
    336           var constNode = (NumberTreeNode)number.CreateTreeNode();
    337           constNode.Value = -1.0;
    338           var prod = GetSymbol("*").CreateTreeNode();
    339           prod.AddSubtree(constNode);
    340           prod.AddSubtree(sumNeg);
    341 
    342           sum.AddSubtree(prod);
    343         }
    344       }
    345       if (sum.SubtreeCount == 1) return sum.Subtrees.First();
    346       else return sum;
     325      FoldLeftRecursive(left);
     326      return left;
    347327    }
    348328
     
    355335    /// Term          = Fact { '*' Fact | '/' Fact }
    356336    private ISymbolicExpressionTreeNode ParseTerm(Queue<Token> tokens) {
    357       var factors = new List<ISymbolicExpressionTreeNode>();
    358       var firstFactor = ParseFact(tokens);
    359       factors.Add(firstFactor);
     337      // build tree from bottom to top and left to right
     338      // a / b * c => ((a / b) * c)
     339      // a / b / c => ((a / b) / c)
     340      // and then flatten as far as possible
     341
     342      var left = ParseFact(tokens);
    360343
    361344      var next = tokens.Peek();
     
    364347          case "*": {
    365348              tokens.Dequeue();
    366               var fact = ParseFact(tokens);
    367               factors.Add(fact);
     349              var right = ParseFact(tokens);
     350
     351              var op = GetSymbol("*").CreateTreeNode();
     352              op.AddSubtree(left);
     353              op.AddSubtree(right);
     354              left = op;
    368355              break;
    369356            }
    370357          case "/": {
    371358              tokens.Dequeue();
    372               var invFact = ParseFact(tokens);
    373               var divNode = GetSymbol("/").CreateTreeNode(); // 1/x
    374               divNode.AddSubtree(invFact);
    375               factors.Add(divNode);
     359              var right = ParseFact(tokens);
     360              var op = GetSymbol("/").CreateTreeNode();
     361              op.AddSubtree(left);
     362              op.AddSubtree(right);
     363              left = op;
    376364              break;
    377365            }
     
    380368        next = tokens.Peek();
    381369      }
    382       if (factors.Count == 1) return factors.First();
    383       else {
    384         var prod = GetSymbol("*").CreateTreeNode();
    385         foreach (var f in factors) prod.AddSubtree(f);
    386         return prod;
     370      // remove all nodes where the child op is the same as the parent op
     371      // (a * b) * c) => (a * b * c)
     372      // (a / b) / c) => (a / b / c)
     373
     374      FoldLeftRecursive(left);
     375      return left;
     376    }
     377
     378    private void FoldLeftRecursive(ISymbolicExpressionTreeNode parent) {
     379      if (parent.SubtreeCount > 1) {
     380        var child = parent.GetSubtree(0);
     381        FoldLeftRecursive(child);
     382        if (parent.Symbol == child.Symbol && IsAssociative(parent.Symbol)) {
     383          parent.RemoveSubtree(0);
     384          for (int i = 0; i < child.SubtreeCount; i++) {
     385            parent.InsertSubtree(i, child.GetSubtree(i));
     386          }
     387        }
    387388      }
    388389    }
     
    409410    ///                 | funcId '(' ArgList ')
    410411    ///                 | VarExpr
     412    ///                 | '<' 'num' [ '=' [ '+' | '-' ] number ] '>'
    411413    ///                 | number
     414    ///                 | ['+' | '-' ] SimpleFact
    412415    /// ArgList       = Expr { ',' Expr }
    413416    /// VarExpr       = varId OptFactorPart
     
    433436        if (tokens.Peek().TokenType == TokenType.LeftPar) {
    434437          // function identifier or LAG
    435           var funcId = idTok.strVal.ToUpperInvariant();
    436 
    437           var funcNode = GetSymbol(funcId).CreateTreeNode();
    438           var lPar = tokens.Dequeue();
    439           if (lPar.TokenType != TokenType.LeftPar)
    440             throw new ArgumentException("expected (");
    441 
    442           // handle 'lag' specifically
    443           if (funcNode.Symbol is LaggedVariable) {
    444             var varId = tokens.Dequeue();
    445             if (varId.TokenType != TokenType.Identifier) throw new ArgumentException("Identifier expected. Format for lagged variables: \"lag(x, -1)\"");
    446             var comma = tokens.Dequeue();
    447             if (comma.TokenType != TokenType.Comma) throw new ArgumentException("',' expected, Format for lagged variables: \"lag(x, -1)\"");
    448             double sign = 1.0;
    449             if (tokens.Peek().strVal == "+" || tokens.Peek().strVal == "-") {
    450               // read sign
    451               var signTok = tokens.Dequeue();
    452               if (signTok.strVal == "-") sign = -1.0;
    453             }
    454             var lagToken = tokens.Dequeue();
    455             if (lagToken.TokenType != TokenType.Number) throw new ArgumentException("Number expected, Format for lagged variables: \"lag(x, -1)\"");
    456             if (!lagToken.doubleVal.IsAlmost(Math.Round(lagToken.doubleVal)))
    457               throw new ArgumentException("Time lags must be integer values");
    458             var laggedVarNode = funcNode as LaggedVariableTreeNode;
    459             laggedVarNode.VariableName = varId.strVal;
    460             laggedVarNode.Lag = (int)Math.Round(sign * lagToken.doubleVal);
    461             laggedVarNode.Weight = 1.0;
     438          return ParseFunctionOrLaggedVariable(tokens, idTok);
     439        } else {
     440          return ParseVariable(tokens, idTok);
     441        }
     442      } else if (next.TokenType == TokenType.LeftAngleBracket) {
     443        // '<' 'num' [ '=' ['+'|'-'] number ] '>'
     444        return ParseNumber(tokens);
     445      } else if (next.TokenType == TokenType.Operator && (next.strVal == "-" || next.strVal == "+")) {
     446        // ['+' | '-' ] SimpleFact
     447        if (tokens.Dequeue().strVal == "-") {
     448          var arg = ParseSimpleFact(tokens);
     449          if (arg is NumberTreeNode numNode) {
     450            numNode.Value *= -1;
     451            return numNode;
     452          } else if (arg is ConstantTreeNode constNode) {
     453            var constSy = new Constant { Value = -constNode.Value };
     454            return constSy.CreateTreeNode();
     455          } else if (arg is VariableTreeNode varNode) {
     456            varNode.Weight *= -1;
     457            return varNode;
    462458          } else {
    463             // functions
    464             var args = ParseArgList(tokens);
    465             // check number of arguments
    466             if (funcNode.Symbol.MinimumArity > args.Length || funcNode.Symbol.MaximumArity < args.Length) {
    467               throw new ArgumentException(string.Format("Symbol {0} requires between {1} and  {2} arguments.", funcId,
    468                 funcNode.Symbol.MinimumArity, funcNode.Symbol.MaximumArity));
    469             }
    470             foreach (var arg in args) funcNode.AddSubtree(arg);
     459            var mul = GetSymbol("*").CreateTreeNode();
     460            var neg = minusOne.CreateTreeNode();
     461            mul.AddSubtree(neg);
     462            mul.AddSubtree(arg);
     463            return mul;
    471464          }
    472 
    473           var rPar = tokens.Dequeue();
    474           if (rPar.TokenType != TokenType.RightPar)
    475             throw new ArgumentException("expected )");
    476 
    477 
    478           return funcNode;
    479465        } else {
    480           // variable
    481           if (tokens.Peek().TokenType == TokenType.Eq) {
    482             // binary factor
    483             tokens.Dequeue(); // skip Eq
    484             var valTok = tokens.Dequeue();
    485             if (valTok.TokenType != TokenType.Identifier) throw new ArgumentException("expected identifier");
    486             var binFactorNode = (BinaryFactorVariableTreeNode)binaryFactorVar.CreateTreeNode();
    487             binFactorNode.Weight = 1.0;
    488             binFactorNode.VariableName = idTok.strVal;
    489             binFactorNode.VariableValue = valTok.strVal;
    490             return binFactorNode;
    491           } else if (tokens.Peek().TokenType == TokenType.LeftBracket) {
    492             // factor variable
    493             var factorVariableNode = (FactorVariableTreeNode)factorVar.CreateTreeNode();
    494             factorVariableNode.VariableName = idTok.strVal;
    495 
    496             tokens.Dequeue(); // skip [
    497             var weights = new List<double>();
    498             // at least one weight is necessary
    499             var sign = 1.0;
    500             if (tokens.Peek().TokenType == TokenType.Operator) {
    501               var opToken = tokens.Dequeue();
    502               if (opToken.strVal == "+") sign = 1.0;
    503               else if (opToken.strVal == "-") sign = -1.0;
    504               else throw new ArgumentException();
    505             }
    506             if (tokens.Peek().TokenType != TokenType.Number) throw new ArgumentException("number expected");
    507             var weightTok = tokens.Dequeue();
    508             weights.Add(sign * weightTok.doubleVal);
    509             while (tokens.Peek().TokenType == TokenType.Comma) {
    510               // skip comma
    511               tokens.Dequeue();
    512               if (tokens.Peek().TokenType == TokenType.Operator) {
    513                 var opToken = tokens.Dequeue();
    514                 if (opToken.strVal == "+") sign = 1.0;
    515                 else if (opToken.strVal == "-") sign = -1.0;
    516                 else throw new ArgumentException();
    517               }
    518               weightTok = tokens.Dequeue();
    519               if (weightTok.TokenType != TokenType.Number) throw new ArgumentException("number expected");
    520               weights.Add(sign * weightTok.doubleVal);
    521             }
    522             var rightBracketToken = tokens.Dequeue();
    523             if (rightBracketToken.TokenType != TokenType.RightBracket) throw new ArgumentException("closing bracket ] expected");
    524             factorVariableNode.Weights = weights.ToArray();
    525             return factorVariableNode;
    526           } else {
    527             // variable
    528             var varNode = (VariableTreeNode)variable.CreateTreeNode();
    529             varNode.Weight = 1.0;
    530             varNode.VariableName = idTok.strVal;
    531             return varNode;
    532           }
    533         }
    534       } else if (next.TokenType == TokenType.LeftAngleBracket) {
    535         Token numberTok = null;
    536         var leftAngleBracket = tokens.Dequeue();
    537         if (leftAngleBracket.TokenType != TokenType.LeftAngleBracket)
    538           throw new ArgumentException("opening bracket < expected");
    539 
    540         var idTok = tokens.Dequeue();
    541         if (idTok.TokenType != TokenType.Identifier || idTok.strVal.ToLower() != "num")
    542           throw new ArgumentException("string 'num' expected");
    543 
    544         if (tokens.Peek().TokenType == TokenType.Eq) {
    545           var equalTok = tokens.Dequeue();
    546           if (tokens.Peek().TokenType != TokenType.Number)
    547             throw new ArgumentException("No value for number specified.");
    548 
    549           numberTok = tokens.Dequeue();
    550         }
    551 
    552         var rightAngleBracket = tokens.Dequeue();
    553         if (rightAngleBracket.TokenType != TokenType.RightAngleBracket)
    554           throw new ArgumentException("closing bracket > expected");
    555         var numNode = (NumberTreeNode)number.CreateTreeNode();
    556         if (numberTok != null) numNode.Value = numberTok.doubleVal;
    557         return numNode;
     466          return ParseSimpleFact(tokens);
     467        }
    558468      } else if (next.TokenType == TokenType.Number) {
     469        // number
    559470        var numTok = tokens.Dequeue();
    560         var constSy = new Constant {Value = numTok.doubleVal};
     471        var constSy = new Constant { Value = numTok.doubleVal };
    561472        return constSy.CreateTreeNode();
    562         /*var constNode = (ConstantTreeNode)constant.CreateTreeNode();
    563         constNode.Value = numTok.doubleVal;
    564         return constNode;*/
    565473      } else {
    566474        throw new ArgumentException(string.Format("unexpected token in expression {0}", next.strVal));
    567475      }
     476    }
     477
     478    private ISymbolicExpressionTreeNode ParseNumber(Queue<Token> tokens) {
     479      // we distinguish parameters and constants. The values of parameters can be changed.
     480      // a parameter is written as '<' 'num' [ '=' ['+'|'-'] number ] '>' with an optional initialization
     481      Token numberTok = null;
     482      var leftAngleBracket = tokens.Dequeue();
     483      if (leftAngleBracket.TokenType != TokenType.LeftAngleBracket)
     484        throw new ArgumentException("opening bracket < expected");
     485
     486      var idTok = tokens.Dequeue();
     487      if (idTok.TokenType != TokenType.Identifier || idTok.strVal.ToLower() != "num")
     488        throw new ArgumentException("string 'num' expected");
     489
     490      var numNode = (NumberTreeNode)number.CreateTreeNode();
     491
     492      if (tokens.Peek().TokenType == TokenType.Eq) {
     493        tokens.Dequeue(); // skip "="
     494        var next = tokens.Peek();
     495        if (next.strVal != "+" && next.strVal != "-" && next.TokenType != TokenType.Number)
     496          throw new ArgumentException("Expected '+', '-' or number.");
     497
     498        var sign = 1.0;
     499        if (next.strVal == "+" || next.strVal == "-") {
     500          if (tokens.Dequeue().strVal == "-") sign = -1.0;
     501        }
     502        if (tokens.Peek().TokenType != TokenType.Number) {
     503          throw new ArgumentException("Expected number.");
     504        }
     505        numberTok = tokens.Dequeue();
     506        numNode.Value = sign * numberTok.doubleVal;
     507      }
     508
     509      var rightAngleBracket = tokens.Dequeue();
     510      if (rightAngleBracket.TokenType != TokenType.RightAngleBracket)
     511        throw new ArgumentException("closing bracket > expected");
     512
     513      return numNode;
     514    }
     515
     516    private ISymbolicExpressionTreeNode ParseVariable(Queue<Token> tokens, Token idTok) {
     517      // variable
     518      if (tokens.Peek().TokenType == TokenType.Eq) {
     519        // binary factor
     520        tokens.Dequeue(); // skip Eq
     521        var valTok = tokens.Dequeue();
     522        if (valTok.TokenType != TokenType.Identifier) throw new ArgumentException("expected identifier");
     523        var binFactorNode = (BinaryFactorVariableTreeNode)binaryFactorVar.CreateTreeNode();
     524        binFactorNode.Weight = 1.0;
     525        binFactorNode.VariableName = idTok.strVal;
     526        binFactorNode.VariableValue = valTok.strVal;
     527        return binFactorNode;
     528      } else if (tokens.Peek().TokenType == TokenType.LeftBracket) {
     529        // factor variable
     530        var factorVariableNode = (FactorVariableTreeNode)factorVar.CreateTreeNode();
     531        factorVariableNode.VariableName = idTok.strVal;
     532
     533        tokens.Dequeue(); // skip [
     534        var weights = new List<double>();
     535        // at least one weight is necessary
     536        var sign = 1.0;
     537        if (tokens.Peek().TokenType == TokenType.Operator) {
     538          var opToken = tokens.Dequeue();
     539          if (opToken.strVal == "+") sign = 1.0;
     540          else if (opToken.strVal == "-") sign = -1.0;
     541          else throw new ArgumentException();
     542        }
     543        if (tokens.Peek().TokenType != TokenType.Number) throw new ArgumentException("number expected");
     544        var weightTok = tokens.Dequeue();
     545        weights.Add(sign * weightTok.doubleVal);
     546        while (tokens.Peek().TokenType == TokenType.Comma) {
     547          // skip comma
     548          tokens.Dequeue();
     549          if (tokens.Peek().TokenType == TokenType.Operator) {
     550            var opToken = tokens.Dequeue();
     551            if (opToken.strVal == "+") sign = 1.0;
     552            else if (opToken.strVal == "-") sign = -1.0;
     553            else throw new ArgumentException();
     554          }
     555          weightTok = tokens.Dequeue();
     556          if (weightTok.TokenType != TokenType.Number) throw new ArgumentException("number expected");
     557          weights.Add(sign * weightTok.doubleVal);
     558        }
     559        var rightBracketToken = tokens.Dequeue();
     560        if (rightBracketToken.TokenType != TokenType.RightBracket) throw new ArgumentException("closing bracket ] expected");
     561        factorVariableNode.Weights = weights.ToArray();
     562        return factorVariableNode;
     563      } else {
     564        // variable
     565        var varNode = (VariableTreeNode)variable.CreateTreeNode();
     566        varNode.Weight = 1.0;
     567        varNode.VariableName = idTok.strVal;
     568        return varNode;
     569      }
     570    }
     571
     572    private ISymbolicExpressionTreeNode ParseFunctionOrLaggedVariable(Queue<Token> tokens, Token idTok) {
     573      var funcId = idTok.strVal.ToUpperInvariant();
     574
     575      var funcNode = GetSymbol(funcId).CreateTreeNode();
     576      var lPar = tokens.Dequeue();
     577      if (lPar.TokenType != TokenType.LeftPar)
     578        throw new ArgumentException("expected (");
     579
     580      // handle 'lag' specifically
     581      if (funcNode.Symbol is LaggedVariable) {
     582        ParseLaggedVariable(tokens, funcNode);
     583      } else {
     584        // functions
     585        var args = ParseArgList(tokens);
     586        // check number of arguments
     587        if (funcNode.Symbol.MinimumArity > args.Length || funcNode.Symbol.MaximumArity < args.Length) {
     588          throw new ArgumentException(string.Format("Symbol {0} requires between {1} and  {2} arguments.", funcId,
     589            funcNode.Symbol.MinimumArity, funcNode.Symbol.MaximumArity));
     590        }
     591        foreach (var arg in args) funcNode.AddSubtree(arg);
     592      }
     593
     594      var rPar = tokens.Dequeue();
     595      if (rPar.TokenType != TokenType.RightPar)
     596        throw new ArgumentException("expected )");
     597
     598
     599      return funcNode;
     600    }
     601
     602    private static void ParseLaggedVariable(Queue<Token> tokens, ISymbolicExpressionTreeNode funcNode) {
     603      var varId = tokens.Dequeue();
     604      if (varId.TokenType != TokenType.Identifier) throw new ArgumentException("Identifier expected. Format for lagged variables: \"lag(x, -1)\"");
     605      var comma = tokens.Dequeue();
     606      if (comma.TokenType != TokenType.Comma) throw new ArgumentException("',' expected, Format for lagged variables: \"lag(x, -1)\"");
     607      double sign = 1.0;
     608      if (tokens.Peek().strVal == "+" || tokens.Peek().strVal == "-") {
     609        // read sign
     610        var signTok = tokens.Dequeue();
     611        if (signTok.strVal == "-") sign = -1.0;
     612      }
     613      var lagToken = tokens.Dequeue();
     614      if (lagToken.TokenType != TokenType.Number) throw new ArgumentException("Number expected, Format for lagged variables: \"lag(x, -1)\"");
     615      if (!lagToken.doubleVal.IsAlmost(Math.Round(lagToken.doubleVal)))
     616        throw new ArgumentException("Time lags must be integer values");
     617      var laggedVarNode = funcNode as LaggedVariableTreeNode;
     618      laggedVarNode.VariableName = varId.strVal;
     619      laggedVarNode.Lag = (int)Math.Round(sign * lagToken.doubleVal);
     620      laggedVarNode.Weight = 1.0;
    568621    }
    569622
     
    579632      return exprList.ToArray();
    580633    }
     634
     635    private bool IsAssociative(ISymbol sy) {
     636      return sy == GetSymbol("+") || sy == GetSymbol("-") ||
     637             sy == GetSymbol("*") || sy == GetSymbol("/") ||
     638             sy == GetSymbol("AND") || sy == GetSymbol("OR") || sy == GetSymbol("XOR");
     639    }
    581640  }
    582641}
  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Views

  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Views/3.4/FeatureCorrelation/TimeframeFeatureCorrelationView.cs

    r17180 r18175  
    7070      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
    7171        timeFrameLabel.Select();  // select label to validate data
    72       }
    73 
    74       if (e.KeyCode == Keys.Escape) {
     72        e.SuppressKeyPress = true;
     73      } else  if (e.KeyCode == Keys.Escape) {
    7574        timeframeTextbox.Text = lastFramesValue;
    7675        timeFrameLabel.Select();  // select label to validate data
     76        e.SuppressKeyPress = true;
    7777      }
    7878    }
  • branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Views/3.4/TimeSeriesPrognosis/TimeSeriesPrognosisResultsView.cs

    r17180 r18175  
    107107
    108108    private void TrainingHorizonTextBox_KeyDown(object sender, KeyEventArgs e) {
    109       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     109      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    110110        TrainingHorizonLabel.Select();  // select label to validate data
    111 
    112       if (e.KeyCode == Keys.Escape) {
     111        e.SuppressKeyPress = true;
     112      } else if (e.KeyCode == Keys.Escape) {
    113113        TrainingHorizonTextBox.Text = Content.TrainingHorizon.ToString();
    114114        TrainingHorizonLabel.Select();  // select label to validate data
     115        e.SuppressKeyPress = true;
    115116      }
    116117    }
     
    132133
    133134    private void TestHorizonTextBox_KeyDown(object sender, KeyEventArgs e) {
    134       if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
     135      if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) {
    135136        TestHorizonLabel.Select();  // select label to validate data
    136 
    137       if (e.KeyCode == Keys.Escape) {
     137        e.SuppressKeyPress = true;
     138      } else if (e.KeyCode == Keys.Escape) {
    138139        TestHorizonTextBox.Text = Content.TestHorizon.ToString();
    139140        TestHorizonLabel.Select();  // select label to validate data
     141        e.SuppressKeyPress = true;
    140142      }
    141143    }
  • branches/3140_NumberSymbol/HeuristicLab.Problems.GrammaticalEvolution

  • branches/3140_NumberSymbol/HeuristicLab.Tests

  • branches/3140_NumberSymbol/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/DeriveTest.cs

    r18120 r18175  
    3434    public void DeriveExpressions() {
    3535      var formatter = new InfixExpressionFormatter();
    36       var parser = new InfixExpressionParser();
    3736      Assert.AreEqual("0", Derive("<num=3>", "x"));
    3837      Assert.AreEqual("1", Derive("x", "x"));
    3938      Assert.AreEqual("10", Derive("<num=10>*x", "x"));
    4039      Assert.AreEqual("10", Derive("x*<num=10>", "x"));
    41       Assert.AreEqual("(2*'x')", Derive("x*x", "x"));
    42       Assert.AreEqual("((('x' * 'x') * 2) + ('x' * 'x'))", Derive("x*x*x", "x")); // simplifier does not merge (x*x)*2 + x*x  to 3*x*x
     40      Assert.AreEqual("2*'x'", Derive("x*x", "x"));
     41      Assert.AreEqual("'x' * 'x' * 2 + 'x' * 'x'", Derive("x*x*x", "x")); // simplifier does not merge (x*x)*2 + x*x  to 3*x*x
    4342      Assert.AreEqual("0", Derive("<num=10>*x", "y"));
    4443      Assert.AreEqual("20", Derive("<num=10>*x+<num=20>*y", "y"));
    4544      Assert.AreEqual("6", Derive("<num=2>*<num=3>*x", "x"));
    46       Assert.AreEqual("(10*'y')", Derive("<num=10>*x*y+<num=20>*y", "x"));
    47       Assert.AreEqual("(1 / (SQR('x') * (-1)))", Derive("1/x", "x"));
    48       Assert.AreEqual("('y' / (SQR('x') * (-1)))", Derive("y/x", "x"));
    49       Assert.AreEqual("((((-2*'x') + (-1)) * ('a' + 'b')) / SQR(('x' + ('x' * 'x'))))",
     45      Assert.AreEqual("10*'y'", Derive("<num=10>*x*y+<num=20>*y", "x"));
     46      Assert.AreEqual("1 * -1 / SQR('x')", Derive("1/x", "x"));
     47      Assert.AreEqual("-1*'y' / SQR('x')", Derive("y/x", "x"));
     48      Assert.AreEqual("('a' + 'b') * (-2*'x' + -1) / SQR('x' + 'x' * 'x')",
    5049        Derive("(a+b)/(x+x*x)", "x"));
    51       Assert.AreEqual("((((-2*'x') + (-1)) * ('a' + 'b')) / SQR(('x' + SQR('x'))))", Derive("(a+b)/(x+SQR(x))", "x"));
     50      Assert.AreEqual("('a' + 'b') * (-2*'x' + -1) / SQR('x' + SQR('x'))", Derive("(a+b)/(x+SQR(x))", "x"));
    5251      Assert.AreEqual("EXP('x')", Derive("exp(x)", "x"));
    53       Assert.AreEqual("(EXP((3*'x')) * 3)", Derive("exp(<num=3>*x)", "x"));
    54       Assert.AreEqual("(1 / 'x')", Derive("log(x)", "x"));
    55       Assert.AreEqual("(1 / 'x')", Derive("log(<num=3>*x)", "x"));   // 3 * 1/(3*x)
    56       Assert.AreEqual("(1 / ('x' + (0.333333333333333*'y')))", Derive("log(<num=3>*x+y)", "x"));  // simplifier does not try to keep fractions
    57       Assert.AreEqual("(1 / (SQRT(((3*'x') + 'y')) * 0.666666666666667))", Derive("sqrt(<num=3>*x+y)", "x"));   // 3 / (2 * sqrt(3*x+y)) = 1 / ((2/3) * sqrt(3*x+y))
    58       Assert.AreEqual("(COS((3*'x')) * 3)", Derive("sin(<num=3>*x)", "x"));
    59       Assert.AreEqual("(SIN((3*'x')) * (-3))", Derive("cos(<num=3>*x)", "x"));
    60       Assert.AreEqual("(1 / (SQR(COS((3*'x'))) * 0.333333333333333))", Derive("tan(<num=3>*x)", "x")); // diff(tan(f(x)), x) = 1.0 / cos²(f(x)), simplifier puts constant factor into the denominator
     52      Assert.AreEqual("EXP(3*'x') * 3", Derive("exp(<num=3>*x)", "x"));
     53      Assert.AreEqual("1 / 'x'", Derive("log(x)", "x"));
     54      Assert.AreEqual("1 / 'x'", Derive("log(<num=3>*x)", "x"));   // 3 * 1/(3*x)
     55      Assert.AreEqual("1 / ('x' + 0.333333333333333*'y')", Derive("log(<num=3>*x+y)", "x"));  // simplifier does not try to keep fractions
     56      Assert.AreEqual("1 / (SQRT(3*'x' + 'y') * 0.666666666666667)", Derive("sqrt(<num=3>*x+y)", "x"));   // 3 / (2 * sqrt(3*x+y)) = 1 / ((2/3) * sqrt(3*x+y))
     57      Assert.AreEqual("COS(3*'x') * 3", Derive("sin(<num=3>*x)", "x"));
     58      Assert.AreEqual("SIN(3*'x') * -3", Derive("cos(<num=3>*x)", "x"));
     59      Assert.AreEqual("1 / (SQR(COS(3*'x')) * 0.333333333333333)", Derive("tan(<num=3>*x)", "x")); // diff(tan(f(x)), x) = 1.0 / cos²(f(x)), simplifier puts constant factor into the denominator
    6160
    62       Assert.AreEqual("((9*'x') / ABS((3*'x')))", Derive("abs(<num=3>*x)", "x"));
    63       Assert.AreEqual("(SQR('x') * 3)", Derive("cube(x)", "x"));
    64       Assert.AreEqual("(1 / (SQR(CUBEROOT('x')) * 3))", Derive("cuberoot(x)", "x"));
     61      Assert.AreEqual("9*'x' / ABS(3*'x')", Derive("abs(<num=3>*x)", "x"));
     62      Assert.AreEqual("SQR('x') * 3", Derive("cube(x)", "x"));
     63      Assert.AreEqual("1 / (SQR(CUBEROOT('x')) * 3)", Derive("cuberoot(x)", "x"));
    6564
    6665      Assert.AreEqual("0", Derive("(a+b)/(x+SQR(x))", "y")); // df(a,b,x) / dy = 0
    6766
    6867
    69       Assert.AreEqual("('a' * 'b' * 'c')", Derive("a*b*c*d", "d"));
    70       Assert.AreEqual("('a' / ('b' * 'c' * SQR('d') * (-1)))", Derive("a/b/c/d", "d"));
     68      Assert.AreEqual("'a' * 'b' * 'c'", Derive("a*b*c*d", "d"));
     69      Assert.AreEqual("'b' * 'c' * -1*'a' / (SQR('b') * SQR('c') * SQR('d'))", Derive("a/b/c/d", "d")); // TODO simplifier should be able to simplify this
    7170
    72       Assert.AreEqual("('x' * ((SQR(TANH(SQR('x'))) * (-1)) + 1) * 2)", Derive("tanh(sqr(x))", "x")); // (2*'x'*(1 - SQR(TANH(SQR('x'))))
     71      Assert.AreEqual("'x' * (SQR(TANH(SQR('x'))) * -1 + 1) * 2", Derive("tanh(sqr(x))", "x")); // (2*'x'*(1 - SQR(TANH(SQR('x'))))
    7372
    7473      {
     
    8584        root.AddSubtree(start);
    8685        var t = new SymbolicExpressionTree(root);
    87         Assert.AreEqual("(1 / (SQR('x') * (-1)))",
     86        Assert.AreEqual("1 / (SQR('x') * -1)",
    8887          formatter.Format(DerivativeCalculator.Derive(t, "x")));
    8988      }
     
    125124        var t = new SymbolicExpressionTree(root);
    126125
    127         Assert.AreEqual("(('y' * 'z' * 60) / (SQR('y') * SQR('z') * 400))", // actually 3 / (4y  5z) but simplifier is not smart enough to cancel numerator and denominator
     126        Assert.AreEqual("'y' * 'z' * 60 / (SQR('y') * SQR('z') * 400)", // actually 3 / (4y  5z) but simplifier is not smart enough to cancel numerator and denominator
    128127                                                                            // 60 y z / y² z² 20² == 6 / y z 40 == 3 / y z 20
    129128          formatter.Format(DerivativeCalculator.Derive(t, "x")));
    130         Assert.AreEqual("(('x' * 'z' * (-60)) / (SQR('y') * SQR('z') * 400))", // actually 3x * -(4 5 z) / (4y 5z)² = -3x / (20 y² z)
     129        Assert.AreEqual("'x' * 'z' * -60 / (SQR('y') * SQR('z') * 400)", // actually 3x * -(4 5 z) / (4y 5z)² = -3x / (20 y² z)
    131130                                                                               // -3 4 5 x z / 4² y² 5² z² = -60 x z / 20² z² y² ==    -60 x z / y² z² 20²
    132131          formatter.Format(DerivativeCalculator.Derive(t, "y")));
    133         Assert.AreEqual("(('x' * 'y' * (-60)) / (SQR('y') * SQR('z') * 400))",
     132        Assert.AreEqual("'x' * 'y' * -60 / (SQR('y') * SQR('z') * 400)",
    134133          formatter.Format(DerivativeCalculator.Derive(t, "z")));
    135134      }
  • branches/3140_NumberSymbol/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/InfixExpressionParserTest.cs

    r17180 r18175  
    3434      var formatter = new InfixExpressionFormatter();
    3535      var parser = new InfixExpressionParser();
    36       Console.WriteLine(formatter.Format(parser.Parse("3")));
    37       Console.WriteLine(formatter.Format(parser.Parse("3*3")));
    38       Console.WriteLine(formatter.Format(parser.Parse("3 * 4")));
    39       Console.WriteLine(formatter.Format(parser.Parse("123E-03")));
    40       Console.WriteLine(formatter.Format(parser.Parse("123e-03")));
    41       Console.WriteLine(formatter.Format(parser.Parse("123e+03")));
    42       Console.WriteLine(formatter.Format(parser.Parse("123E+03")));
    43       Console.WriteLine(formatter.Format(parser.Parse("123.0E-03")));
    44       Console.WriteLine(formatter.Format(parser.Parse("123.0e-03")));
    45       Console.WriteLine(formatter.Format(parser.Parse("123.0e+03")));
    46       Console.WriteLine(formatter.Format(parser.Parse("123.0E+03")));
    47       Console.WriteLine(formatter.Format(parser.Parse("123.0E-3")));
    48       Console.WriteLine(formatter.Format(parser.Parse("123.0e-3")));
    49       Console.WriteLine(formatter.Format(parser.Parse("123.0e+3")));
    50       Console.WriteLine(formatter.Format(parser.Parse("123.0E+3")));
     36      Assert.AreEqual("3", formatter.Format(parser.Parse("3")));
     37      Assert.AreEqual("3 * 3", formatter.Format(parser.Parse("3*3")));
     38      Assert.AreEqual("3 * 4",formatter.Format(parser.Parse("3 * 4")));
     39      Assert.AreEqual("0.123",formatter.Format(parser.Parse("123E-03")));
     40      Assert.AreEqual("0.123",formatter.Format(parser.Parse("123e-03")));
     41      Assert.AreEqual("123000",formatter.Format(parser.Parse("123e+03")));
     42      Assert.AreEqual("123000",formatter.Format(parser.Parse("123E+03")));
     43      Assert.AreEqual("0.123",formatter.Format(parser.Parse("123.0E-03")));
     44      Assert.AreEqual("0.123",formatter.Format(parser.Parse("123.0e-03")));
     45      Assert.AreEqual("123000",formatter.Format(parser.Parse("123.0e+03")));
     46      Assert.AreEqual("123000",formatter.Format(parser.Parse("123.0E+03")));
     47      Assert.AreEqual("0.123",formatter.Format(parser.Parse("123.0E-3")));
     48      Assert.AreEqual("0.123",formatter.Format(parser.Parse("123.0e-3")));
     49      Assert.AreEqual("123000",formatter.Format(parser.Parse("123.0e+3")));
     50      Assert.AreEqual("123000",formatter.Format(parser.Parse("123.0E+3")));
    5151
    52       Console.WriteLine(formatter.Format(parser.Parse("3.1415+2.0")));
    53       Console.WriteLine(formatter.Format(parser.Parse("3.1415/2.0")));
    54       Console.WriteLine(formatter.Format(parser.Parse("3.1415*2.0")));
    55       Console.WriteLine(formatter.Format(parser.Parse("3.1415-2.0")));
     52      Assert.AreEqual("3.1415 + 2",formatter.Format(parser.Parse("3.1415+2.0")));
     53      Assert.AreEqual("3.1415 / 2",formatter.Format(parser.Parse("3.1415/2.0")));
     54      Assert.AreEqual("3.1415 * 2",formatter.Format(parser.Parse("3.1415*2.0")));
     55      Assert.AreEqual("3.1415 - 2", formatter.Format(parser.Parse("3.1415-2.0")));
    5656      // round-trip
    57       Console.WriteLine(formatter.Format(parser.Parse(formatter.Format(parser.Parse("3.1415-2.0")))));
    58       Console.WriteLine(formatter.Format(parser.Parse("3.1415+(2.0)")));
    59       Console.WriteLine(formatter.Format(parser.Parse("(3.1415+(2.0))")));
     57      Assert.AreEqual("3.1415 - 2",formatter.Format(parser.Parse(formatter.Format(parser.Parse("3.1415-2.0")))));
     58      Assert.AreEqual("3.1415 + 2",formatter.Format(parser.Parse("3.1415+(2.0)")));
     59      Assert.AreEqual("3.1415 + 2", formatter.Format(parser.Parse("(3.1415+(2.0))")));
    6060
    6161
    62       Console.WriteLine(formatter.Format(parser.Parse("log(3)")));
    63       Console.WriteLine(formatter.Format(parser.Parse("log(-3)")));   // should produce log(-3) as output
    64       Console.WriteLine(formatter.Format(parser.Parse("exp(3)")));
    65       Console.WriteLine(formatter.Format(parser.Parse("exp(-3)")));  // should produce exp(-3) as output
    66       Console.WriteLine(formatter.Format(parser.Parse("sqrt(3)")));
     62      Assert.AreEqual("LOG(3)",formatter.Format(parser.Parse("log(3)")));
     63      Assert.AreEqual("LOG(-3)",formatter.Format(parser.Parse("log(-3)")));
     64      Assert.AreEqual("EXP(3)",formatter.Format(parser.Parse("exp(3)")));
     65      Assert.AreEqual("EXP(-3)",formatter.Format(parser.Parse("exp(-3)")));
     66      Assert.AreEqual("SQRT(3)", formatter.Format(parser.Parse("sqrt(3)")));
    6767
    68       Console.WriteLine(formatter.Format(parser.Parse("sqr((-3))")));  // should produce sqr((-3)) as output
     68      Assert.AreEqual("SQR(-3)", formatter.Format(parser.Parse("sqr((-3))")));
    6969
    70       Console.WriteLine(formatter.Format(parser.Parse("3/3+2/2+1/1"))); // ((3 * 1 / 3) + (2 * 1 / 2) + (1 * 1 / 1))
    71       Console.WriteLine(formatter.Format(parser.Parse("-3+30-2+20-1+10")));   //  not (30 + 20 + 10 + ((-1) * (3 + 2 + 1)))
    72       // round trip
    73       Console.WriteLine(formatter.Format(parser.Parse(formatter.Format(parser.Parse("-3+30-2+20-1+10")))));   // not (30 + 20 + 10 + ((-(1)) * (3 + 2 + 1)))
     70      Assert.AreEqual("3 / 3 + 2 / 2 + 1 / 1",formatter.Format(parser.Parse("3/3+2/2+1/1")));
     71      Assert.AreEqual("-3 + 30 - 2 + 20 - 1 + 10", formatter.Format(parser.Parse("-3+30-2+20-1+10")));
    7472
    75       Console.WriteLine(formatter.Format(parser.Parse("\"x1\"")));
    76       Console.WriteLine(formatter.Format(parser.Parse("\'var name\'")));
    77       Console.WriteLine(formatter.Format(parser.Parse("\"var name\"")));
    78       Console.WriteLine(formatter.Format(parser.Parse("\"1\"")));
     73      // 'flattening' of nested addition, subtraction, multiplication, or division
     74      Assert.AreEqual("1 + 2 + 3 + 4", formatter.Format(parser.Parse("1 + 2 + 3 + 4")));
     75      Assert.AreEqual("1 - 2 - 3 - 4", formatter.Format(parser.Parse("1 - 2 - 3 - 4")));
     76      Assert.AreEqual("1 * 2 * 3 * 4", formatter.Format(parser.Parse("1 * 2 * 3 * 4")));
     77      Assert.AreEqual("1 / 2 / 3 / 4", formatter.Format(parser.Parse("1 / 2 / 3 / 4")));
    7978
    80       Console.WriteLine(formatter.Format(parser.Parse("'var \" name\'")));
    81       Console.WriteLine(formatter.Format(parser.Parse("\"var \' name\"")));
     79      // signed variables / constants
     80      Assert.AreEqual("-1*'x1'", formatter.Format(parser.Parse("-x1")));
     81      Assert.AreEqual("1", formatter.Format(parser.Parse("--1.0")));
     82      Assert.AreEqual("1", formatter.Format(parser.Parse("----1.0")));
     83      Assert.AreEqual("1", formatter.Format(parser.Parse("-+-1.0")));
     84      Assert.AreEqual("1", formatter.Format(parser.Parse("+-+-1.0")));
     85      Assert.AreEqual("-3 + -1", formatter.Format(parser.Parse("-3 + -1.0")));
    8286
    8387
    84       Console.WriteLine(formatter.Format(parser.Parse("\"x1\"*\"x2\"")));
    85       Console.WriteLine(formatter.Format(parser.Parse("\"x1\"*\"x2\"+\"x3\"*\"x4\"")));
    86       Console.WriteLine(formatter.Format(parser.Parse("x1*x2+x3*x4")));
     88      Assert.AreEqual("'x1'",formatter.Format(parser.Parse("\"x1\"")));
     89      Assert.AreEqual("'var name'",formatter.Format(parser.Parse("\'var name\'")));
     90      Assert.AreEqual("'var name'",formatter.Format(parser.Parse("\"var name\"")));
     91      Assert.AreEqual("'1'",formatter.Format(parser.Parse("\"1\"")));
     92
     93      Assert.AreEqual("'var \" name'",formatter.Format(parser.Parse("'var \" name\'")));
     94      Assert.AreEqual("\"var ' name\"", formatter.Format(parser.Parse("\"var \' name\"")));
    8795
    8896
    89       Console.WriteLine(formatter.Format(parser.Parse("POW(3, 2)")));
    90       Console.WriteLine(formatter.Format(parser.Parse("POW(3.1, 2.1)")));
    91       Console.WriteLine(formatter.Format(parser.Parse("POW(3.1 , 2.1)")));
    92       Console.WriteLine(formatter.Format(parser.Parse("POW(3.1 ,2.1)")));
    93       Console.WriteLine(formatter.Format(parser.Parse("POW(-3.1 , - 2.1)")));
    94       Console.WriteLine(formatter.Format(parser.Parse("ROOT(3, 2)")));
    95       Console.WriteLine(formatter.Format(parser.Parse("ROOT(3.1, 2.1)")));
    96       Console.WriteLine(formatter.Format(parser.Parse("ROOT(3.1 , 2.1)")));
    97       Console.WriteLine(formatter.Format(parser.Parse("ROOT(3.1 ,2.1)")));
    98       Console.WriteLine(formatter.Format(parser.Parse("ROOT(-3.1 , - 2.1)")));
     97      Assert.AreEqual("'x1' * 'x2'",formatter.Format(parser.Parse("\"x1\"*\"x2\"")));
     98      Assert.AreEqual("'x1' * 'x2' + 'x3' * 'x4'",formatter.Format(parser.Parse("\"x1\"*\"x2\"+\"x3\"*\"x4\"")));
     99      Assert.AreEqual("'x1' * 'x2' + 'x3' * 'x4'", formatter.Format(parser.Parse("x1*x2+x3*x4")));
    99100
    100       Console.WriteLine(formatter.Format(parser.Parse("IF(GT( 0, 1), 1, 0)")));
    101       Console.WriteLine(formatter.Format(parser.Parse("IF(LT(0,1), 1 , 0)")));
    102101
    103       Console.WriteLine(formatter.Format(parser.Parse("LAG(x, 1)")));
    104       Console.WriteLine(formatter.Format(parser.Parse("LAG(x, -1)")));
    105       Console.WriteLine(formatter.Format(parser.Parse("LAG(x, +1)")));
    106       Console.WriteLine(formatter.Format(parser.Parse("x * LAG('x', +1)")));
     102      Assert.AreEqual("3 ^ 2",formatter.Format(parser.Parse("POW(3, 2)")));
     103      Assert.AreEqual("3.1 ^ 2.1",formatter.Format(parser.Parse("POW(3.1, 2.1)")));
     104      Assert.AreEqual("3.1 ^ 2.1",formatter.Format(parser.Parse("POW(3.1 , 2.1)")));
     105      Assert.AreEqual("3.1 ^ 2.1",formatter.Format(parser.Parse("POW(3.1 ,2.1)")));
     106      Assert.AreEqual("-3.1 ^ -2.1",formatter.Format(parser.Parse("POW(-3.1 , - 2.1)")));
     107      Assert.AreEqual("ROOT(3, 2)",formatter.Format(parser.Parse("ROOT(3, 2)")));
     108      Assert.AreEqual("ROOT(3.1, 2.1)",formatter.Format(parser.Parse("ROOT(3.1, 2.1)")));
     109      Assert.AreEqual("ROOT(3.1, 2.1)",formatter.Format(parser.Parse("ROOT(3.1 , 2.1)")));
     110      Assert.AreEqual("ROOT(3.1, 2.1)",formatter.Format(parser.Parse("ROOT(3.1 ,2.1)")));
     111      Assert.AreEqual("ROOT(-3.1, -2.1)", formatter.Format(parser.Parse("ROOT(-3.1 , -2.1)")));
    107112
    108       Console.WriteLine(formatter.Format(parser.Parse("x [1.0] * y")));
    109       Console.WriteLine(formatter.Format(parser.Parse("x [1.0, 2.0] * y [1.0, 2.0]")));
    110       Console.WriteLine(formatter.Format(parser.Parse("x[1] * y")));
    111       Console.WriteLine(formatter.Format(parser.Parse("x[1, 2] * y [1, 2]")));
     113      Assert.AreEqual("IF(GT(0, 1), 1, 0)",formatter.Format(parser.Parse("IF(GT( 0, 1), 1, 0)")));
     114      Assert.AreEqual("IF(LT(0, 1), 1, 0)",formatter.Format(parser.Parse("IF(LT(0,1), 1 , 0)")));
     115      Assert.AreEqual("LAG('x', 1)",formatter.Format(parser.Parse("LAG(x, 1)")));
     116      Assert.AreEqual("LAG('x', -1)",formatter.Format(parser.Parse("LAG(x, -1)")));
     117      Assert.AreEqual("LAG('x', 1)",formatter.Format(parser.Parse("LAG(x, +1)")));
     118      Assert.AreEqual("'x' * LAG('x', 1)", formatter.Format(parser.Parse("x * LAG('x', +1)")));
    112119
    113       Console.WriteLine(formatter.Format(parser.Parse("x [+1.0] * y")));
    114       Console.WriteLine(formatter.Format(parser.Parse("x [-1.0] * y")));
    115       Console.WriteLine(formatter.Format(parser.Parse("x [-1.0, -2.0] * y [+1.0, +2.0]")));
     120      // factor variables
     121      Assert.AreEqual("'x'[1] * 'y'",formatter.Format(parser.Parse("x [1.0] * y")));
     122      Assert.AreEqual("'x'[1, 2] * 'y'[1, 2]",formatter.Format(parser.Parse("x [1.0, 2.0] * y [1.0, 2.0]")));
     123      Assert.AreEqual("'x'[1] * 'y'",formatter.Format(parser.Parse("x[1] * y")));
     124      Assert.AreEqual("'x'[1, 2] * 'y'[1, 2]",formatter.Format(parser.Parse("x[1, 2] * y [1, 2]")));
     125      Assert.AreEqual("'x'[1] * 'y'",formatter.Format(parser.Parse("x [+1.0] * y")));
     126      Assert.AreEqual("'x'[-1] * 'y'",formatter.Format(parser.Parse("x [-1.0] * y")));
     127      Assert.AreEqual("'x'[-1, -2] * 'y'[1, 2]", formatter.Format(parser.Parse("x [-1.0, -2.0] * y [+1.0, +2.0]")));
    116128
    117       Console.WriteLine(formatter.Format(parser.Parse("x='bla' * y")));
    118       Console.WriteLine(formatter.Format(parser.Parse("x = 'bla'")));
    119       Console.WriteLine(formatter.Format(parser.Parse("x = \"bla\"")));
    120       Console.WriteLine(formatter.Format(parser.Parse("1.0 * x = bla")));
    121       Console.WriteLine(formatter.Format(parser.Parse("-1.0 * x = bla")));
    122       Console.WriteLine(formatter.Format(parser.Parse("+1.0 * \"x\" = bla + y = \"bla2\"")));
     129      // one-hot for factor
     130      Assert.AreEqual("'x' = 'val' * 'y'",formatter.Format(parser.Parse("x='val' * y")));
     131      Assert.AreEqual("'x' = 'val'",formatter.Format(parser.Parse("x = 'val'")));
     132      Assert.AreEqual("'x' = 'val'",formatter.Format(parser.Parse("x = \"val\"")));
     133      Assert.AreEqual("1 * 'x' = 'val'",formatter.Format(parser.Parse("1.0 * x = val")));
     134      Assert.AreEqual("-1 * 'x' = 'val'",formatter.Format(parser.Parse("-1.0 * x = val")));
     135      Assert.AreEqual("1 * 'x' = 'val1' + 'y' = 'val2'", formatter.Format(parser.Parse("+1.0 * \"x\" = val1 + y = \"val2\"")));
     136
     137      // numeric parameters
     138      Assert.AreEqual("0", formatter.Format(parser.Parse("<num>"))); // default initial value is zero
     139      Assert.AreEqual("0", formatter.Format(parser.Parse("< num >")));
     140      Assert.AreEqual("1", formatter.Format(parser.Parse("< num=1.0>")));
     141      Assert.AreEqual("1", formatter.Format(parser.Parse("< num = 1.0>")));
     142      Assert.AreEqual("-1", formatter.Format(parser.Parse("< num =-1.0>")));
     143      Assert.AreEqual("-1", formatter.Format(parser.Parse("< num = - 1.0>")));
     144     
     145      // numeric parameter with sign
     146      Assert.AreEqual("1", formatter.Format(parser.Parse("-<num=-1.0>")));
     147
     148      // nested functions
     149      Assert.AreEqual("SIN(SIN(SIN('X1')))", formatter.Format(parser.Parse("SIN(SIN(SIN(X1)))")));
    123150    }
    124151  }
  • branches/3140_NumberSymbol/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicExpressionTreeBottomUpSimilarityCalculatorTest.cs

    r18145 r18175  
    77  [TestClass]
    88  public class BottomUpSimilarityCalculatorTest {
    9     private readonly SymbolicExpressionImporter importer = new SymbolicExpressionImporter();
    109    private readonly InfixExpressionParser parser = new InfixExpressionParser();
    1110
     
    1312    private const int Rows = 1;
    1413    private const int Columns = 10;
    15 
    16     public BottomUpSimilarityCalculatorTest() {
    17       var parser = new InfixExpressionParser();
    18     }
    1914
    2015    [TestMethod]
     
    2823
    2924      TestMatchedNodes("1 - 1", "2 - 2", 0, strict: true);
    30       TestMatchedNodes("1 - 1", "2 - 2", 4, strict: false); // 4, because of the way strings are parsed into trees by the infix parser
     25      TestMatchedNodes("1 - 1", "2 - 2", 3, strict: false);
    3126
    3227      TestMatchedNodes("2 - 1", "1 - 2", 2, strict: true);
    33       TestMatchedNodes("2 - 1", "1 - 2", 4, strict: false);
     28      TestMatchedNodes("2 - 1", "1 - 2", 3, strict: false);
    3429
    35       TestMatchedNodes("(X1 * X2) + (X3 * X4)", "(X1 * X2) + (X3 * X4)", 7, strict: true);
    36       TestMatchedNodes("(X1 * X2) + (X3 * X4)", "(X1 * X2) + (X3 * X4)", 7, strict: false);
     30      TestMatchedNodes("X1 * X2 + X3 * X4", "X1 * X2 + X3 * X4", 7, strict: true);
     31      TestMatchedNodes("X1 * X2 + X3 * X4", "X1 * X2 + X3 * X4", 7, strict: false);
    3732
    38       TestMatchedNodes("(X1 * X2) + (X3 * X4)", "(X1 * X2) + (X5 * X6)", 3, strict: true);
    39       TestMatchedNodes("(X1 * X2) + (X3 * X4)", "(X1 * X2) + (X5 * X6)", 3, strict: false);
     33      TestMatchedNodes("X1 * X2 + X3 * X4", "X1 * X2 + X5 * X6", 3, strict: true);
     34      TestMatchedNodes("X1 * X2 + X3 * X4", "X1 * X2 + X5 * X6", 3, strict: false);
    4035
    41       TestMatchedNodes("(X1 * X2) + (X3 * X4)", "(X1 * X2) - (X5 * X6)", 3, strict: true);
    42       TestMatchedNodes("(X1 * X2) + (X3 * X4)", "(X1 * X2) - (X5 * X6)", 3, strict: false);
     36      TestMatchedNodes("X1 * X2 + X3 * X4", "X1 * X2 - X5 * X6", 3, strict: true);
     37      TestMatchedNodes("X1 * X2 + X3 * X4", "X1 * X2 - X5 * X6", 3, strict: false);
    4338
    4439      TestMatchedNodes("SIN(SIN(SIN(X1)))", "SIN(SIN(SIN(X1)))", 4, strict: true);
     
    4742      TestMatchedNodes("SIN(SIN(SIN(X1)))", "COS(COS(COS(X1)))", 1, strict: true);
    4843
    49       const string lhs = "(0.006153 + (X9 * X7 * X2 * 0.229506) + (X6 * X10 * X3 * 0.924598) + (X2 * X1 * 0.951272) + (X4 * X3 * 0.992570) + (X6 * X5 * 1.027299))";
    50       const string rhs = "(0.006153 + (X10 * X7 * X2 * 0.229506) + (X6 * X10 * X3 * 0.924598) + (X2 * X1 * 0.951272) + (X4 * X3 * 0.992570) + (X6 * X5 * 1.027299))";
     44      const string lhs = "0.006153 + X9 * X7 * X2 * 0.229506 + X6 * X10 * X3 * 0.924598 + X2 * X1 * 0.951272 + X4 * X3 * 0.992570 + X6 * X5 * 1.027299";
     45      const string rhs = "0.006153 + X10 * X7 * X2 * 0.229506 + X6 * X10 * X3 * 0.924598 + X2 * X1 * 0.951272 + X4 * X3 * 0.992570 + X6 * X5 * 1.027299";
    5146
    5247      TestMatchedNodes(lhs, lhs, 24, strict: true);
Note: See TracChangeset for help on using the changeset viewer.