Changeset 14576 for branches/HeuristicLab.EvolutionTracking
- Timestamp:
- 01/15/17 14:17:06 (8 years ago)
- Location:
- branches/HeuristicLab.EvolutionTracking
- Files:
-
- 23 edited
- 3 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding
- Property svn:mergeinfo changed
/trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding merged: 14340,14342,14344,14352-14357
- Property svn:mergeinfo changed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views
- Property svn:mergeinfo changed (with no actual effect on merging)
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Grammars/SymbolicExpressionGrammarBase.cs
r14312 r14576 82 82 protected SymbolicExpressionGrammarBase(bool deserializing) 83 83 : base(deserializing) { 84 cachedMinExpressionLength = new Dictionary<string, int>();85 cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();86 cachedMinExpressionDepth = new Dictionary<string, int>();87 cachedMaxExpressionDepth = new Dictionary<string, int>();88 89 cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>();90 cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>();91 84 92 85 symbols = new Dictionary<string, ISymbol>(); … … 100 93 protected SymbolicExpressionGrammarBase(SymbolicExpressionGrammarBase original, Cloner cloner) 101 94 : base(original, cloner) { 102 cachedMinExpressionLength = new Dictionary<string, int>();103 cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();104 cachedMinExpressionDepth = new Dictionary<string, int>();105 cachedMaxExpressionDepth = new Dictionary<string, int>();106 107 cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>();108 cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>();109 95 110 96 symbols = original.symbols.ToDictionary(x => x.Key, y => cloner.Clone(y.Value)); … … 124 110 protected SymbolicExpressionGrammarBase(string name, string description) 125 111 : base(name, description) { 126 cachedMinExpressionLength = new Dictionary<string, int>();127 cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();128 cachedMinExpressionDepth = new Dictionary<string, int>();129 cachedMaxExpressionDepth = new Dictionary<string, int>();130 131 cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>();132 cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>();133 134 112 symbols = new Dictionary<string, ISymbol>(); 135 113 symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(); … … 322 300 } 323 301 324 private readonly Dictionary<Tuple<string, string>, bool> cachedIsAllowedChildSymbol ;302 private readonly Dictionary<Tuple<string, string>, bool> cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>(); 325 303 public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) { 326 304 if (allowedChildSymbols.Count == 0) return false; … … 352 330 } 353 331 354 private readonly Dictionary<Tuple<string, string, int>, bool> cachedIsAllowedChildSymbolIndex ;332 private readonly Dictionary<Tuple<string, string, int>, bool> cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>(); 355 333 public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) { 356 334 if (!child.Enabled) return false; … … 412 390 } 413 391 414 private readonly Dictionary<string, int> cachedMinExpressionLength ;392 private readonly Dictionary<string, int> cachedMinExpressionLength = new Dictionary<string, int>(); 415 393 public int GetMinimumExpressionLength(ISymbol symbol) { 416 394 int res; … … 423 401 if (cachedMinExpressionLength.TryGetValue(symbol.Name, out res)) return res; 424 402 425 res = GetMinimumExpressionLengthRec(symbol); 426 foreach (var entry in cachedMinExpressionLength.Where(e => e.Value >= int.MaxValue).ToList()) { 427 if (entry.Key != symbol.Name) cachedMinExpressionLength.Remove(entry.Key); 428 } 429 return res; 430 } 431 } 432 433 private int GetMinimumExpressionLengthRec(ISymbol symbol) { 434 int temp; 435 if (!cachedMinExpressionLength.TryGetValue(symbol.Name, out temp)) { 436 cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion 437 long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol)) 438 let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex) 439 where s.InitialFrequency > 0.0 440 select GetMinimumExpressionLengthRec(s)).DefaultIfEmpty(0).Min() 441 select minForSlot).DefaultIfEmpty(0).Sum(); 442 443 cachedMinExpressionLength[symbol.Name] = (int)Math.Min(sumOfMinExpressionLengths, int.MaxValue); 403 GrammarUtils.CalculateMinimumExpressionLengths(this, cachedMinExpressionLength); 444 404 return cachedMinExpressionLength[symbol.Name]; 445 405 } 446 return temp;447 } 448 449 private readonly Dictionary<Tuple<string, int>, int> cachedMaxExpressionLength ;406 } 407 408 409 private readonly Dictionary<Tuple<string, int>, int> cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>(); 450 410 public int GetMaximumExpressionLength(ISymbol symbol, int maxDepth) { 451 411 int temp; … … 469 429 } 470 430 471 private readonly Dictionary<string, int> cachedMinExpressionDepth ;431 private readonly Dictionary<string, int> cachedMinExpressionDepth = new Dictionary<string, int>(); 472 432 public int GetMinimumExpressionDepth(ISymbol symbol) { 473 433 int res; … … 480 440 if (cachedMinExpressionDepth.TryGetValue(symbol.Name, out res)) return res; 481 441 482 res = GetMinimumExpressionDepthRec(symbol); 483 foreach (var entry in cachedMinExpressionDepth.Where(e => e.Value >= int.MaxValue).ToList()) { 484 if (entry.Key != symbol.Name) cachedMinExpressionDepth.Remove(entry.Key); 485 } 486 return res; 487 } 488 } 489 private int GetMinimumExpressionDepthRec(ISymbol symbol) { 490 int temp; 491 if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) { 492 cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion 493 long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol)) 494 let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex) 495 where s.InitialFrequency > 0.0 496 select GetMinimumExpressionDepthRec(s)).DefaultIfEmpty(0).Min() 497 select minForSlot).DefaultIfEmpty(0).Max(); 498 cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue); 442 GrammarUtils.CalculateMinimumExpressionDepth(this, cachedMinExpressionDepth); 499 443 return cachedMinExpressionDepth[symbol.Name]; 500 444 } 501 return temp; 502 } 503 504 private readonly Dictionary<string, int> cachedMaxExpressionDepth; 445 } 446 447 private readonly Dictionary<string, int> cachedMaxExpressionDepth = new Dictionary<string, int>(); 505 448 public int GetMaximumExpressionDepth(ISymbol symbol) { 506 449 int temp; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj
r13482 r14576 181 181 <Compile Include="ArchitectureManipulators\SubroutineDuplicater.cs" /> 182 182 <Compile Include="ArchitectureManipulators\SymbolicExpressionTreeArchitectureManipulator.cs" /> 183 <Compile Include="Grammars\GrammarUtils.cs" /> 183 184 <Compile Include="SymbolicExpressionTreeProblem.cs" /> 184 185 <Compile Include="Compiler\Instruction.cs" /> -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeEncoding.cs
r14312 r14576 164 164 public SymbolicExpressionTreeEncoding(string name, ISymbolicExpressionGrammar grammar, int maximumLength, int maximumDepth) 165 165 : base(name) { 166 treeLengthParameter = new FixedValueParameter<IntValue>( "Maximum Tree Length", "Maximal length of the symbolic expression.", new IntValue(maximumLength));167 treeDepthParameter = new FixedValueParameter<IntValue>( "Maximum Tree Depth", "Maximal depth of the symbolic expression. The minimum depth needed for the algorithm is 3 because two levels are reserved for the ProgramRoot and the Start symbol.", new IntValue(maximumDepth));168 grammarParameter = new ValueParameter<ISymbolicExpressionGrammar>( "Grammar", "The grammar that should be used for symbolic expression tree.", grammar);169 functionDefinitionsParameter = new FixedValueParameter<IntValue>( "Function Definitions", "Maximal number of automatically defined functions", new IntValue(0));170 functionArgumentsParameter = new FixedValueParameter<IntValue>( "Function Arguments", "Maximal number of arguments of automatically defined functions.", new IntValue(0));166 treeLengthParameter = new FixedValueParameter<IntValue>(Name + ".Maximum Tree Length", "Maximal length of the symbolic expression.", new IntValue(maximumLength)); 167 treeDepthParameter = new FixedValueParameter<IntValue>(Name + ".Maximum Tree Depth", "Maximal depth of the symbolic expression. The minimum depth needed for the algorithm is 3 because two levels are reserved for the ProgramRoot and the Start symbol.", new IntValue(maximumDepth)); 168 grammarParameter = new ValueParameter<ISymbolicExpressionGrammar>(Name + ".Grammar", "The grammar that should be used for symbolic expression tree.", grammar); 169 functionDefinitionsParameter = new FixedValueParameter<IntValue>(Name + ".Function Definitions", "Maximal number of automatically defined functions", new IntValue(0)); 170 functionArgumentsParameter = new FixedValueParameter<IntValue>(Name + ".Function Arguments", "Maximal number of arguments of automatically defined functions.", new IntValue(0)); 171 171 172 172 Parameters.Add(treeLengthParameter); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/SimpleSymbol.cs
r14312 r14576 61 61 } 62 62 63 public SimpleSymbol(string name, int arity) 64 : this(name, string.Empty, arity, arity) { 65 } 66 63 67 public SimpleSymbol(string name, string description, int minimumArity, int maximumArity) 64 68 : base(name, description) { -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic
- Property svn:mergeinfo changed
/trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic merged: 14319,14345,14347,14350,14353-14354,14367,14378,14390-14391,14400
- Property svn:mergeinfo changed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views
- Property svn:mergeinfo changed
/trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Views merged: 14390,14400,14432,14494
- Property svn:mergeinfo changed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs
r14312 r14576 112 112 treeChart.Tree = tree; 113 113 treeChart.Repaint(); 114 bool valid = !tree.IterateNodesPostfix().Any(node => node.SubtreeCount < GetMinArity(node.Symbol) || node.SubtreeCount > node.Symbol.MaximumArity); 114 // check if all nodes have a legal arity 115 var nodes = tree.IterateNodesPostfix().ToList(); 116 bool valid = !nodes.Any(node => node.SubtreeCount < GetMinArity(node.Symbol) || node.SubtreeCount > node.Symbol.MaximumArity); 117 118 if (valid) { 119 // check if all variables are contained in the dataset 120 var variables = new HashSet<string>(Content.ProblemData.Dataset.DoubleVariables); 121 valid = nodes.OfType<VariableTreeNode>().All(x => variables.Contains(x.VariableName)); 122 } 123 115 124 if (valid) { 116 125 btnOptimizeConstants.Enabled = true; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicExpressionTreeChart.cs
r14312 r14576 102 102 if (dialog.DialogResult != DialogResult.OK) return; 103 103 104 var symbol = dialog.SelectedSymbol ();104 var symbol = dialog.SelectedSymbol; 105 105 var node = symbol.CreateTreeNode(); 106 106 if (node is ConstantTreeNode) { … … 110 110 var variable = node as VariableTreeNode; 111 111 variable.Weight = double.Parse(dialog.variableWeightTextBox.Text); 112 variable.VariableName = dialog. variableNamesCombo.Text;112 variable.VariableName = dialog.SelectedVariableName; 113 113 } else if (node.Symbol.MinimumArity <= parent.SubtreeCount && node.Symbol.MaximumArity >= parent.SubtreeCount) { 114 114 for (int i = parent.SubtreeCount - 1; i >= 0; --i) { -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/TreeEditDialogs/SymbolicExpressionTreeNodeInsertDialog.Designer.cs
r14312 r14576 57 57 this.okButton = new System.Windows.Forms.Button(); 58 58 this.cancelButton = new System.Windows.Forms.Button(); 59 this.variableNameTextBox = new System.Windows.Forms.TextBox(); 59 60 ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit(); 60 61 this.SuspendLayout(); … … 168 169 this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); 169 170 // 171 // variableNameTextBox 172 // 173 this.variableNameTextBox.Location = new System.Drawing.Point(101, 63); 174 this.variableNameTextBox.Name = "variableNameTextBox"; 175 this.variableNameTextBox.Size = new System.Drawing.Size(127, 20); 176 this.variableNameTextBox.TabIndex = 11; 177 this.variableNameTextBox.Visible = false; 178 // 170 179 // InsertNodeDialog 171 180 // … … 175 184 this.ClientSize = new System.Drawing.Size(241, 133); 176 185 this.ControlBox = false; 186 this.Controls.Add(this.variableNameTextBox); 177 187 this.Controls.Add(this.cancelButton); 178 188 this.Controls.Add(this.okButton); … … 208 218 private System.Windows.Forms.Button cancelButton; 209 219 private System.Windows.Forms.Button okButton; 220 private System.Windows.Forms.TextBox variableNameTextBox; 210 221 } 211 222 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/TreeEditDialogs/SymbolicExpressionTreeNodeInsertDialog.cs
r14312 r14576 23 23 using System.Collections.Generic; 24 24 using System.ComponentModel; 25 using System.Linq; 25 26 using System.Text; 26 27 using System.Windows.Forms; … … 30 31 namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views { 31 32 public partial class InsertNodeDialog : Form { 33 public string SelectedVariableName { 34 get { 35 var variable = SelectedSymbol as Variable; 36 if (variable == null) 37 return string.Empty; 38 return variable.VariableNames.Any() ? variableNamesCombo.Text : variableNameTextBox.Text; 39 } 40 } 41 32 42 public InsertNodeDialog() { 33 43 InitializeComponent(); … … 40 50 } 41 51 42 public ISymbol SelectedSymbol (){43 return (ISymbol)allowedSymbolsCombo.SelectedItem;52 public ISymbol SelectedSymbol { 53 get { return (ISymbol)allowedSymbolsCombo.SelectedItem; } 44 54 } 45 55 … … 56 66 constantValueTextBox.Visible = true; 57 67 } else if (symbol is Variable) { 58 var variable = (Variable)symbol; 59 foreach (var name in variable.VariableNames) variableNamesCombo.Items.Add(name); 60 variableNamesCombo.SelectedIndex = 0; 68 var variableSymbol = (Variable)symbol; 69 if (variableSymbol.VariableNames.Any()) { 70 foreach (var name in variableSymbol.VariableNames) 71 variableNamesCombo.Items.Add(name); 72 variableNamesCombo.SelectedIndex = 0; 73 variableNamesCombo.Visible = true; 74 variableNameTextBox.Visible = false; 75 } else { 76 variableNamesCombo.Visible = false; 77 variableNameTextBox.Visible = true; 78 } 61 79 variableNameLabel.Visible = true; 62 variableNamesCombo.Visible = true;63 80 variableWeightLabel.Visible = true; 64 81 variableWeightTextBox.Visible = true; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/TreeEditDialogs/SymbolicExpressionTreeVariableNodeEditDialog.Designer.cs
r14312 r14576 55 55 this.okButton = new System.Windows.Forms.Button(); 56 56 this.cancelButton = new System.Windows.Forms.Button(); 57 this.variableNameTextBox = new System.Windows.Forms.TextBox(); 57 58 ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit(); 58 59 this.SuspendLayout(); … … 146 147 this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); 147 148 // 149 // variableNameTextBox 150 // 151 this.variableNameTextBox.Location = new System.Drawing.Point(101, 12); 152 this.variableNameTextBox.Name = "variableNameTextBox"; 153 this.variableNameTextBox.Size = new System.Drawing.Size(131, 20); 154 this.variableNameTextBox.TabIndex = 12; 155 this.variableNameTextBox.Visible = false; 156 // 148 157 // VariableNodeEditDialog 149 158 // … … 154 163 this.ClientSize = new System.Drawing.Size(244, 134); 155 164 this.ControlBox = false; 165 this.Controls.Add(this.variableNameTextBox); 156 166 this.Controls.Add(this.cancelButton); 157 167 this.Controls.Add(this.okButton); … … 188 198 public System.Windows.Forms.TextBox newValueTextBox; 189 199 public System.Windows.Forms.ComboBox variableNamesCombo; 200 private System.Windows.Forms.TextBox variableNameTextBox; 190 201 } 191 202 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/TreeEditDialogs/SymbolicExpressionTreeVariableNodeEditDialog.cs
r14312 r14576 22 22 using System; 23 23 using System.ComponentModel; 24 using System.Linq; 24 25 using System.Text; 25 26 using System.Windows.Forms; … … 40 41 } 41 42 43 public string SelectedVariableName { 44 get { return variableNamesCombo.Visible ? variableNamesCombo.Text : variableNameTextBox.Text; } 45 } 46 42 47 public VariableNodeEditDialog(ISymbolicExpressionTreeNode node) { 43 48 InitializeComponent(); 44 49 oldValueTextBox.TabStop = false; // cannot receive focus using tab key 45 46 50 NewNode = (VariableTreeNode)node; // will throw an invalid cast exception if node is not of the correct type 47 51 InitializeFields(); … … 57 61 variableNameLabel.Visible = true; 58 62 variableNamesCombo.Visible = true; 59 foreach (var name in variableTreeNode.Symbol.VariableNames) variableNamesCombo.Items.Add(name); 60 variableNamesCombo.SelectedIndex = variableNamesCombo.Items.IndexOf(variableTreeNode.VariableName); 63 if (variableTreeNode.Symbol.VariableNames.Any()) { 64 foreach (var name in variableTreeNode.Symbol.VariableNames) 65 variableNamesCombo.Items.Add(name); 66 variableNamesCombo.SelectedIndex = variableNamesCombo.Items.IndexOf(variableTreeNode.VariableName); 67 variableNamesCombo.Visible = true; 68 variableNameTextBox.Visible = false; 69 } else { 70 variableNamesCombo.Visible = false; 71 variableNameTextBox.Visible = true; 72 } 61 73 } 62 74 } … … 93 105 #region combo box validation and events 94 106 private void variableNamesCombo_Validating(object sender, CancelEventArgs e) { 107 if (variableNamesCombo.Items.Count == 0) return; 95 108 if (variableNamesCombo.Items.Contains(variableNamesCombo.SelectedItem)) return; 96 109 e.Cancel = true; … … 119 132 private void OnDialogValidated(object sender, EventArgs e) { 120 133 double weight = double.Parse(newValueTextBox.Text); 121 var variableName = (string)variableNamesCombo.SelectedItem;122 134 // we impose an extra validation condition: that the weight/value be different than the original ones 135 var variableName = SelectedVariableName; 123 136 if (variableTreeNode.Weight.Equals(weight) && variableTreeNode.VariableName.Equals(variableName)) return; 124 137 variableTreeNode.Weight = weight; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs
r14307 r14576 81 81 } 82 82 strBuilder.Append(")"); 83 } else { 84 // function with multiple arguments 85 strBuilder.Append(token).Append("("); 86 FormatRecursively(node.Subtrees.First(), strBuilder); 87 foreach (var subtree in node.Subtrees.Skip(1)) { 88 strBuilder.Append(", "); 89 FormatRecursively(subtree, strBuilder); 90 } 91 strBuilder.Append(")"); 83 92 } 84 93 } else if (node.SubtreeCount == 1) { … … 94 103 FormatRecursively(node.GetSubtree(0), strBuilder); 95 104 } else { 96 // function 105 // function with only one argument 97 106 strBuilder.Append(token).Append("("); 98 107 FormatRecursively(node.GetSubtree(0), strBuilder); … … 101 110 } else { 102 111 // no subtrees 103 if (node.Symbol is Variable) { 112 if (node.Symbol is LaggedVariable) { 113 var varNode = node as LaggedVariableTreeNode; 114 if (!varNode.Weight.IsAlmost(1.0)) { 115 strBuilder.Append("("); 116 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Weight); 117 strBuilder.Append("*"); 118 } 119 strBuilder.Append("LAG("); 120 if (varNode.VariableName.Contains("'")) { 121 strBuilder.AppendFormat("\"{0}\"", varNode.VariableName); 122 } else { 123 strBuilder.AppendFormat("'{0}'", varNode.VariableName); 124 } 125 strBuilder.Append(", ") 126 .AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Lag) 127 .Append(")"); 128 } else if (node.Symbol is Variable) { 104 129 var varNode = node as VariableTreeNode; 105 130 if (!varNode.Weight.IsAlmost(1.0)) { … … 121 146 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", constNode.Value); 122 147 else 123 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", constNode.Value); // (-1)148 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", constNode.Value); // (-1 124 149 } 125 150 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionLatexFormatter.cs
r14312 r14576 67 67 strBuilder.AppendLine(FormatRecursively(symbolicExpressionTree.Root)); 68 68 return strBuilder.ToString(); 69 } 70 catch (NotImplementedException ex) { 69 } catch (NotImplementedException ex) { 71 70 return ex.Message + Environment.NewLine + ex.StackTrace; 72 71 } … … 109 108 } else if (node.Symbol is Division) { 110 109 if (node.SubtreeCount == 1) { 111 strBuilder.Append(@" \cfrac{1 ");110 strBuilder.Append(@" \cfrac{1}{"); 112 111 } else { 113 112 strBuilder.Append(@" \cfrac{ "); … … 176 175 strBuilder.Append(@" \operatorname{if} \left( "); 177 176 } else if (node.Symbol is Constant) { 178 strBuilder.Append("c_{" + constants.Count + "} ");179 177 var constNode = node as ConstantTreeNode; 180 constants.Add(constNode.Value); 178 if (constNode.Value.IsAlmost(1.0)) { 179 strBuilder.Append("1 "); 180 } else { 181 strBuilder.Append("c_{" + constants.Count + "} "); 182 constants.Add(constNode.Value); 183 } 181 184 } else if (node.Symbol is LaggedVariable) { 182 185 var laggedVarNode = node as LaggedVariableTreeNode; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Importer/InfixExpressionParser.cs
r14307 r14576 26 26 using System.Text; 27 27 using HeuristicLab.Collections; 28 using HeuristicLab.Common; 28 29 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 29 30 … … 37 38 /// </summary> 38 39 public sealed class InfixExpressionParser { 39 private enum TokenType { Operator, Identifier, Number, LeftPar, RightPar, End, NA };40 private enum TokenType { Operator, Identifier, Number, LeftPar, RightPar, Comma, End, NA }; 40 41 private class Token { 41 42 internal double doubleVal; … … 102 103 { "MEAN", new Average()}, 103 104 { "IF", new IfThenElse()}, 104 { " >", new GreaterThan()},105 { " <", new LessThan()},105 { "GT", new GreaterThan()}, 106 { "LT", new LessThan()}, 106 107 { "AND", new And()}, 107 108 { "OR", new Or()}, … … 109 110 { "XOR", new Xor()}, 110 111 { "DIFF", new Derivative()}, 112 { "LAG", new LaggedVariable() }, 111 113 }; 112 114 … … 138 140 } 139 141 if (char.IsDigit(str[pos])) { 140 // read number (=> read until white space or operator )142 // read number (=> read until white space or operator or comma) 141 143 var sb = new StringBuilder(); 142 144 sb.Append(str[pos]); 143 145 pos++; 144 146 while (pos < str.Length && !char.IsWhiteSpace(str[pos]) 145 && (str[pos] != '+' || str[pos -1] == 'e' || str[pos-1] == 'E') // continue reading exponents147 && (str[pos] != '+' || str[pos - 1] == 'e' || str[pos - 1] == 'E') // continue reading exponents 146 148 && (str[pos] != '-' || str[pos - 1] == 'e' || str[pos - 1] == 'E') 147 && str[pos] != '*' 149 && str[pos] != '*' 148 150 && str[pos] != '/' 149 && str[pos] != ')') { 151 && str[pos] != ')' 152 && str[pos] != ',') { 150 153 sb.Append(str[pos]); 151 154 pos++; … … 211 214 pos++; 212 215 yield return new Token { TokenType = TokenType.RightPar, strVal = ")" }; 213 } 214 } 215 } 216 217 // S = Expr EOF 218 // Expr = ['-' | '+'] Term { '+' Term | '-' Term } 219 // Term = Fact { '*' Fact | '/' Fact } 220 // Fact = '(' Expr ')' | funcId '(' Expr ')' | varId | number 216 } else if (str[pos] == ',') { 217 pos++; 218 yield return new Token { TokenType = TokenType.Comma, strVal = "," }; 219 } else { 220 throw new ArgumentException("Invalid character: " + str[pos]); 221 } 222 } 223 } 224 225 // S = Expr EOF 226 // Expr = ['-' | '+'] Term { '+' Term | '-' Term } 227 // Term = Fact { '*' Fact | '/' Fact } 228 // Fact = '(' Expr ')' | funcId '(' ArgList ')' | varId | number 229 // ArgList = Expr { ',' Expr } 221 230 private ISymbolicExpressionTreeNode ParseS(Queue<Token> tokens) { 222 231 var expr = ParseExpr(tokens); … … 326 335 } 327 336 328 // Fact = '(' Expr ')' | funcId '(' Expr')' | varId | number337 // Fact = '(' Expr ')' | 'LAG' '(' varId ',' ['+' | '-'] number ')' | funcId '(' ArgList ')' | varId | number 329 338 private ISymbolicExpressionTreeNode ParseFact(Queue<Token> tokens) { 330 339 var next = tokens.Peek(); … … 346 355 if (lPar.TokenType != TokenType.LeftPar) 347 356 throw new ArgumentException("expected ("); 348 var expr = ParseExpr(tokens); 357 358 // handle 'lag' specifically 359 if (funcNode.Symbol is LaggedVariable) { 360 var varId = tokens.Dequeue(); 361 if (varId.TokenType != TokenType.Identifier) throw new ArgumentException("Identifier expected. Format for lagged variables: \"lag(x, -1)\""); 362 var comma = tokens.Dequeue(); 363 if (comma.TokenType != TokenType.Comma) throw new ArgumentException("',' expected, Format for lagged variables: \"lag(x, -1)\""); 364 double sign = 1.0; 365 if (tokens.Peek().strVal == "+" || tokens.Peek().strVal == "-") { 366 // read sign 367 var signTok = tokens.Dequeue(); 368 if (signTok.strVal == "-") sign = -1.0; 369 } 370 var lagToken = tokens.Dequeue(); 371 if (lagToken.TokenType != TokenType.Number) throw new ArgumentException("Number expected, Format for lagged variables: \"lag(x, -1)\""); 372 if (!lagToken.doubleVal.IsAlmost(Math.Round(lagToken.doubleVal))) 373 throw new ArgumentException("Time lags must be integer values"); 374 var laggedVarNode = funcNode as LaggedVariableTreeNode; 375 laggedVarNode.VariableName = varId.strVal; 376 laggedVarNode.Lag = (int)Math.Round(sign * lagToken.doubleVal); 377 laggedVarNode.Weight = 1.0; 378 } else { 379 // functions 380 var args = ParseArgList(tokens); 381 // check number of arguments 382 if (funcNode.Symbol.MinimumArity > args.Length || funcNode.Symbol.MaximumArity < args.Length) { 383 throw new ArgumentException(string.Format("Symbol {0} requires between {1} and {2} arguments.", funcId, 384 funcNode.Symbol.MinimumArity, funcNode.Symbol.MaximumArity)); 385 } 386 foreach (var arg in args) funcNode.AddSubtree(arg); 387 } 388 349 389 var rPar = tokens.Dequeue(); 350 390 if (rPar.TokenType != TokenType.RightPar) 351 391 throw new ArgumentException("expected )"); 352 392 353 funcNode.AddSubtree(expr);354 393 return funcNode; 355 394 } else { … … 369 408 } 370 409 } 410 411 // ArgList = Expr { ',' Expr } 412 private ISymbolicExpressionTreeNode[] ParseArgList(Queue<Token> tokens) { 413 var exprList = new List<ISymbolicExpressionTreeNode>(); 414 exprList.Add(ParseExpr(tokens)); 415 while (tokens.Peek().TokenType != TokenType.RightPar) { 416 var comma = tokens.Dequeue(); 417 if (comma.TokenType != TokenType.Comma) throw new ArgumentException("expected ',' "); 418 exprList.Add(ParseExpr(tokens)); 419 } 420 return exprList.ToArray(); 421 } 371 422 } 372 423 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Importer/SymbolicExpressionImporter.cs
r14312 r14576 35 35 private const string INVOKESTART = "CALL"; 36 36 private const string TIMELAGSTART = "LAG"; 37 private Dictionary<string, Symbol> knownSymbols = new Dictionary<string, Symbol>() 37 private Dictionary<string, Symbol> knownSymbols = new Dictionary<string, Symbol>() 38 38 { 39 39 {"+", new Addition()}, -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionCompiledTreeInterpreter.cs
r14312 r14576 614 614 case OpCodes.VariableCondition: { 615 615 var variableConditionTreeNode = (VariableConditionTreeNode)node; 616 if (variableConditionTreeNode.Symbol.IgnoreSlope) throw new NotSupportedException("Strict variable conditionals are not supported"); 616 617 var variableName = variableConditionTreeNode.VariableName; 617 618 var indexExpr = Expression.Constant(variableIndices[variableName]); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeInterpreter.cs
r14312 r14576 471 471 if (row < 0 || row >= dataset.Rows) return double.NaN; 472 472 var variableConditionTreeNode = (VariableConditionTreeNode)currentInstr.dynamicNode; 473 double variableValue = ((IList<double>)currentInstr.data)[row]; 474 double x = variableValue - variableConditionTreeNode.Threshold; 475 double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x)); 476 477 double trueBranch = Evaluate(dataset, ref row, state); 478 double falseBranch = Evaluate(dataset, ref row, state); 479 480 return trueBranch * p + falseBranch * (1 - p); 473 if (!variableConditionTreeNode.Symbol.IgnoreSlope) { 474 double variableValue = ((IList<double>)currentInstr.data)[row]; 475 double x = variableValue - variableConditionTreeNode.Threshold; 476 double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x)); 477 478 double trueBranch = Evaluate(dataset, ref row, state); 479 double falseBranch = Evaluate(dataset, ref row, state); 480 481 return trueBranch * p + falseBranch * (1 - p); 482 } else { 483 // strict threshold 484 double variableValue = ((IList<double>)currentInstr.data)[row]; 485 if (variableValue <= variableConditionTreeNode.Threshold) { 486 var left = Evaluate(dataset, ref row, state); 487 state.SkipInstructions(); 488 return left; 489 } else { 490 state.SkipInstructions(); 491 return Evaluate(dataset, ref row, state); 492 } 493 } 481 494 } 482 495 default: -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs
r14312 r14576 126 126 private readonly object syncRoot = new object(); 127 127 public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) { 128 if (!rows.Any()) return Enumerable.Empty<double>(); 128 129 if (CheckExpressionsWithIntervalArithmetic) 129 130 throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter."); … … 166 167 if (row < 0 || row >= dataset.Rows) instr.value = double.NaN; 167 168 var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode; 168 double variableValue = ((IList<double>)instr.data)[row]; 169 double x = variableValue - variableConditionTreeNode.Threshold; 170 double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x)); 171 172 double trueBranch = code[instr.childIndex].value; 173 double falseBranch = code[instr.childIndex + 1].value; 174 175 instr.value = trueBranch * p + falseBranch * (1 - p); 169 if (!variableConditionTreeNode.Symbol.IgnoreSlope) { 170 double variableValue = ((IList<double>)instr.data)[row]; 171 double x = variableValue - variableConditionTreeNode.Threshold; 172 double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x)); 173 174 double trueBranch = code[instr.childIndex].value; 175 double falseBranch = code[instr.childIndex + 1].value; 176 177 instr.value = trueBranch * p + falseBranch * (1 - p); 178 } else { 179 double variableValue = ((IList<double>)instr.data)[row]; 180 if (variableValue <= variableConditionTreeNode.Threshold) { 181 instr.value = code[instr.childIndex].value; 182 } else { 183 instr.value = code[instr.childIndex + 1].value; 184 } 185 } 176 186 } else if (instr.opCode == OpCodes.Add) { 177 187 double s = code[instr.childIndex].value; … … 420 430 for (int j = 1; j != seq.Length; ++j) 421 431 seq[j].skip = true; 422 }423 break;432 break; 433 } 424 434 } 425 435 #endregion -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/VariableCondition.cs
r14312 r14576 149 149 } 150 150 } 151 } 152 153 /// <summary> 154 /// Flag to indicate if the interpreter should ignore the slope parameter (introduced for representation of expression trees) 155 /// </summary> 156 [Storable] 157 private bool ignoreSlope; 158 public bool IgnoreSlope { 159 get { return ignoreSlope; } 160 set { ignoreSlope = value; } 151 161 } 152 162 -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/VariableConditionTreeNode.cs
r14312 r14576 96 96 97 97 public override string ToString() { 98 if (slope.IsAlmost(0.0)) 98 if (slope.IsAlmost(0.0) || Symbol.IgnoreSlope) { 99 return variableName + " < " + threshold.ToString("E4"); 100 } else { 99 101 return variableName + " > " + threshold.ToString("E4") + Environment.NewLine + 100 "slope: " + slope.ToString("E4"); 101 else 102 return variableName + " > " + threshold.ToString("E4"); 102 "slope: " + slope.ToString("E4"); 103 } 103 104 } 104 105 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.TravelingSalesman
- Property svn:mergeinfo changed (with no actual effect on merging)
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.TravelingSalesman.Views
- Property svn:mergeinfo changed (with no actual effect on merging)
Note: See TracChangeset
for help on using the changeset viewer.