Changeset 14878 for branches/HeuristicLab.EvolutionTracking
- Timestamp:
- 04/19/17 16:53:09 (7 years ago)
- Location:
- branches/HeuristicLab.EvolutionTracking
- Files:
-
- 3 deleted
- 45 edited
- 13 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs
r14312 r14878 111 111 } else { 112 112 var selectedBranch = SelectRandomBranch(random, allowedBranches, internalCrossoverPointProbability); 113 if (selectedBranch != null)114 selectedBranch = (ISymbolicExpressionTreeNode)selectedBranch.Clone();115 113 116 114 if (crossoverPoint0.Child != null) { -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic
- Property svn:mergeinfo changed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views
- Property svn:mergeinfo changed
-
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs
r14576 r14878 183 183 } 184 184 185 protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateReplacementValues(ISymbolicExpressionTree tree);186 protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateImpactValues(ISymbolicExpressionTree tree);187 185 protected abstract Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>> CalculateImpactAndReplacementValues(ISymbolicExpressionTree tree); 188 186 protected abstract void UpdateModel(ISymbolicExpressionTree tree); … … 268 266 269 267 private void btnSimplify_Click(object sender, EventArgs e) { 270 var simplifier = new SymbolicDataAnalysisExpressionTreeSimplifier();268 var simplifier = new TreeSimplifier(); 271 269 var simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree); 272 270 UpdateModel(simplifiedExpressionTree); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/Symbols/LaggedVariableView.Designer.cs
r14312 r14878 63 63 // weightInitializationMuTextBox 64 64 // 65 this.weightInitializationMuTextBox.Size = new System.Drawing.Size(293, 20); 65 66 this.toolTip.SetToolTip(this.weightInitializationMuTextBox, "The mu (mean) parameter of the normal distribution from which to sample the initi" + 66 67 "al weights."); … … 69 70 // 70 71 this.initializationGroupBox.Location = new System.Drawing.Point(6, 7); 71 this.initializationGroupBox.Size = new System.Drawing.Size(3 79, 73);72 this.initializationGroupBox.Size = new System.Drawing.Size(391, 73); 72 73 // 73 74 // weightSigmaLabel … … 77 78 // weightInitializationSigmaTextBox 78 79 // 80 this.weightInitializationSigmaTextBox.Size = new System.Drawing.Size(293, 20); 79 81 this.toolTip.SetToolTip(this.weightInitializationSigmaTextBox, "The sigma parameter for the normal distribution from which to sample the initial " + 80 82 "weights."); … … 83 85 // 84 86 this.mutationGroupBox.Location = new System.Drawing.Point(6, 86); 85 this.mutationGroupBox.Size = new System.Drawing.Size(3 79, 73);87 this.mutationGroupBox.Size = new System.Drawing.Size(391, 95); 86 88 // 87 89 // multiplicativeWeightChangeLabel 88 90 // 91 this.multiplicativeWeightChangeLabel.TabIndex = 4; 89 92 this.toolTip.SetToolTip(this.multiplicativeWeightChangeLabel, "The sigma parameter for the normal distribution to use to sample a multiplicative" + 90 93 " change in weight."); … … 92 95 // multiplicativeWeightChangeSigmaTextBox 93 96 // 97 this.multiplicativeWeightChangeSigmaTextBox.TabIndex = 5; 94 98 this.toolTip.SetToolTip(this.multiplicativeWeightChangeSigmaTextBox, "The sigma (std.dev.) parameter for the normal distribution to sample a multiplica" + 95 99 "tive change in weight."); … … 97 101 // additiveWeightChangeLabel 98 102 // 103 this.additiveWeightChangeLabel.TabIndex = 2; 99 104 this.toolTip.SetToolTip(this.additiveWeightChangeLabel, "The sigma (std.dev.) parameter for the normal distribution to sample an additive " + 100 105 "change in weight."); … … 102 107 // additiveWeightChangeSigmaTextBox 103 108 // 109 this.additiveWeightChangeSigmaTextBox.TabIndex = 3; 104 110 this.toolTip.SetToolTip(this.additiveWeightChangeSigmaTextBox, "The sigma (std.dev.) parameter for the normal distribution to sample an additive " + 105 111 "change in weight."); … … 111 117 // parametersTabPage 112 118 // 113 this.parametersTabPage.Size = new System.Drawing.Size(4 00, 149);119 this.parametersTabPage.Size = new System.Drawing.Size(412, 208); 114 120 // 115 121 // tabControl 116 122 // 117 123 this.tabControl.Location = new System.Drawing.Point(0, 179); 118 this.tabControl.Size = new System.Drawing.Size(408, 175); 119 this.tabControl.TabIndex = 9; 124 this.tabControl.Size = new System.Drawing.Size(420, 234); 125 this.tabControl.TabIndex = 13; 126 // 127 // varChangeProbTextBox 128 // 129 this.varChangeProbTextBox.TabIndex = 1; 130 this.toolTip.SetToolTip(this.varChangeProbTextBox, "The sigma (std.dev.) parameter for the normal distribution to sample an additive " + 131 "change in weight."); 132 // 133 // varChangeProbLabel 134 // 135 this.varChangeProbLabel.TabIndex = 0; 136 this.toolTip.SetToolTip(this.varChangeProbLabel, "The probability of changing the referenced variable in [0..1]. Variable reference" + 137 "s are sampled uniformly."); 120 138 // 121 139 // initialFrequencyLabel 122 140 // 141 this.initialFrequencyLabel.TabIndex = 2; 123 142 this.toolTip.SetToolTip(this.initialFrequencyLabel, "Relative frequency of the symbol in randomly created trees"); 124 143 // … … 126 145 // 127 146 this.errorProvider.SetIconAlignment(this.initialFrequencyTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft); 147 this.initialFrequencyTextBox.Size = new System.Drawing.Size(323, 20); 148 this.initialFrequencyTextBox.TabIndex = 3; 149 // 150 // enabledCheckBox 151 // 152 this.enabledCheckBox.TabIndex = 8; 153 // 154 // minimumArityLabel 155 // 156 this.minimumArityLabel.TabIndex = 4; 157 this.toolTip.SetToolTip(this.minimumArityLabel, "The minimum arity of the symbol"); 158 // 159 // maximumArityLabel 160 // 161 this.toolTip.SetToolTip(this.maximumArityLabel, "The maximum arity of the symbol"); 128 162 // 129 163 // minimumArityTextBox 130 164 // 131 165 this.errorProvider.SetIconAlignment(this.minimumArityTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft); 132 this.minimumArityTextBox.Size = new System.Drawing.Size(315, 20); 166 this.minimumArityTextBox.Size = new System.Drawing.Size(327, 20); 167 this.minimumArityTextBox.TabIndex = 5; 133 168 // 134 169 // maximumArityTextBox 135 170 // 136 171 this.errorProvider.SetIconAlignment(this.maximumArityTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft); 137 this.maximumArityTextBox.Size = new System.Drawing.Size(3 15, 20);172 this.maximumArityTextBox.Size = new System.Drawing.Size(327, 20); 138 173 // 139 174 // nameTextBox … … 141 176 this.errorProvider.SetIconAlignment(this.nameTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft); 142 177 this.errorProvider.SetIconPadding(this.nameTextBox, 2); 178 this.nameTextBox.Size = new System.Drawing.Size(302, 20); 179 // 180 // infoLabel 181 // 182 this.infoLabel.Location = new System.Drawing.Point(401, 3); 143 183 // 144 184 // minTimeOffsetLabel … … 148 188 this.minTimeOffsetLabel.Name = "minTimeOffsetLabel"; 149 189 this.minTimeOffsetLabel.Size = new System.Drawing.Size(81, 13); 150 this.minTimeOffsetLabel.TabIndex = 5;190 this.minTimeOffsetLabel.TabIndex = 9; 151 191 this.minTimeOffsetLabel.Text = "Min. time offset:"; 152 192 // … … 157 197 this.maxTimeOffsetLabel.Name = "maxTimeOffsetLabel"; 158 198 this.maxTimeOffsetLabel.Size = new System.Drawing.Size(84, 13); 159 this.maxTimeOffsetLabel.TabIndex = 7;199 this.maxTimeOffsetLabel.TabIndex = 11; 160 200 this.maxTimeOffsetLabel.Text = "Max. time offset:"; 161 201 // 162 202 // minTimeOffsetTextBox 163 203 // 164 this.minTimeOffsetTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 204 this.minTimeOffsetTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 165 205 | System.Windows.Forms.AnchorStyles.Right))); 166 206 this.minTimeOffsetTextBox.Location = new System.Drawing.Point(93, 127); 167 207 this.minTimeOffsetTextBox.Name = "minTimeOffsetTextBox"; 168 this.minTimeOffsetTextBox.Size = new System.Drawing.Size(3 15, 20);169 this.minTimeOffsetTextBox.TabIndex = 6;208 this.minTimeOffsetTextBox.Size = new System.Drawing.Size(327, 20); 209 this.minTimeOffsetTextBox.TabIndex = 10; 170 210 this.minTimeOffsetTextBox.TextChanged += new System.EventHandler(this.minTimeOffsetTextBox_TextChanged); 171 211 // 172 212 // maxTimeOffsetTextBox 173 213 // 174 this.maxTimeOffsetTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 214 this.maxTimeOffsetTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 175 215 | System.Windows.Forms.AnchorStyles.Right))); 176 216 this.maxTimeOffsetTextBox.Location = new System.Drawing.Point(93, 153); 177 217 this.maxTimeOffsetTextBox.Name = "maxTimeOffsetTextBox"; 178 this.maxTimeOffsetTextBox.Size = new System.Drawing.Size(3 15, 20);179 this.maxTimeOffsetTextBox.TabIndex = 8;218 this.maxTimeOffsetTextBox.Size = new System.Drawing.Size(327, 20); 219 this.maxTimeOffsetTextBox.TabIndex = 12; 180 220 this.maxTimeOffsetTextBox.TextChanged += new System.EventHandler(this.maxTimeOffsetTextBox_TextChanged); 181 221 // 182 222 // LaggedVariableView 183 223 // 184 this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);185 224 this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; 186 225 this.Controls.Add(this.minTimeOffsetTextBox); … … 189 228 this.Controls.Add(this.maxTimeOffsetTextBox); 190 229 this.Name = "LaggedVariableView"; 191 this.Size = new System.Drawing.Size(408, 352); 230 this.Size = new System.Drawing.Size(420, 411); 231 this.Controls.SetChildIndex(this.enabledCheckBox, 0); 192 232 this.Controls.SetChildIndex(this.maxTimeOffsetTextBox, 0); 193 233 this.Controls.SetChildIndex(this.minTimeOffsetLabel, 0); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/Symbols/VariableView.Designer.cs
r14312 r14878 51 51 this.weightInitializationSigmaTextBox = new System.Windows.Forms.TextBox(); 52 52 this.mutationGroupBox = new System.Windows.Forms.GroupBox(); 53 this.varChangeProbTextBox = new System.Windows.Forms.TextBox(); 54 this.varChangeProbLabel = new System.Windows.Forms.Label(); 53 55 this.multiplicativeWeightChangeLabel = new System.Windows.Forms.Label(); 54 56 this.multiplicativeWeightChangeSigmaTextBox = new System.Windows.Forms.TextBox(); … … 67 69 // initialFrequencyLabel 68 70 // 71 this.initialFrequencyLabel.TabIndex = 2; 69 72 this.toolTip.SetToolTip(this.initialFrequencyLabel, "Relative frequency of the symbol in randomly created trees"); 70 73 // … … 73 76 this.errorProvider.SetIconAlignment(this.initialFrequencyTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft); 74 77 this.initialFrequencyTextBox.Size = new System.Drawing.Size(311, 20); 78 this.initialFrequencyTextBox.TabIndex = 3; 79 // 80 // enabledCheckBox 81 // 82 this.enabledCheckBox.TabIndex = 8; 75 83 // 76 84 // minimumArityLabel 77 85 // 86 this.minimumArityLabel.TabIndex = 4; 78 87 this.toolTip.SetToolTip(this.minimumArityLabel, "The minimum arity of the symbol"); 79 88 // … … 86 95 this.errorProvider.SetIconAlignment(this.minimumArityTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft); 87 96 this.minimumArityTextBox.Size = new System.Drawing.Size(311, 20); 97 this.minimumArityTextBox.TabIndex = 5; 88 98 // 89 99 // maximumArityTextBox … … 165 175 this.mutationGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 166 176 | System.Windows.Forms.AnchorStyles.Right))); 177 this.mutationGroupBox.Controls.Add(this.varChangeProbTextBox); 178 this.mutationGroupBox.Controls.Add(this.varChangeProbLabel); 167 179 this.mutationGroupBox.Controls.Add(this.multiplicativeWeightChangeLabel); 168 180 this.mutationGroupBox.Controls.Add(this.multiplicativeWeightChangeSigmaTextBox); … … 171 183 this.mutationGroupBox.Location = new System.Drawing.Point(6, 85); 172 184 this.mutationGroupBox.Name = "mutationGroupBox"; 173 this.mutationGroupBox.Size = new System.Drawing.Size(391, 73);185 this.mutationGroupBox.Size = new System.Drawing.Size(391, 97); 174 186 this.mutationGroupBox.TabIndex = 1; 175 187 this.mutationGroupBox.TabStop = false; 176 188 this.mutationGroupBox.Text = "Mutation"; 177 189 // 190 // varChangeProbTextBox 191 // 192 this.varChangeProbTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 193 | System.Windows.Forms.AnchorStyles.Right))); 194 this.varChangeProbTextBox.Location = new System.Drawing.Point(201, 13); 195 this.varChangeProbTextBox.Name = "varChangeProbTextBox"; 196 this.varChangeProbTextBox.Size = new System.Drawing.Size(184, 20); 197 this.varChangeProbTextBox.TabIndex = 1; 198 this.toolTip.SetToolTip(this.varChangeProbTextBox, "The sigma (std.dev.) parameter for the normal distribution to sample an additive " + 199 "change in weight."); 200 this.varChangeProbTextBox.TextChanged += new System.EventHandler(this.VarProbTextBox_TextChanged); 201 // 202 // varChangeProbLabel 203 // 204 this.varChangeProbLabel.AutoSize = true; 205 this.varChangeProbLabel.Location = new System.Drawing.Point(6, 16); 206 this.varChangeProbLabel.Name = "varChangeProbLabel"; 207 this.varChangeProbLabel.Size = new System.Drawing.Size(134, 13); 208 this.varChangeProbLabel.TabIndex = 0; 209 this.varChangeProbLabel.Text = "Variable change probability"; 210 this.toolTip.SetToolTip(this.varChangeProbLabel, "The probability of changing the referenced variable in [0..1]. Variable reference" + 211 "s are sampled uniformly."); 212 // 178 213 // multiplicativeWeightChangeLabel 179 214 // 180 215 this.multiplicativeWeightChangeLabel.AutoSize = true; 181 this.multiplicativeWeightChangeLabel.Location = new System.Drawing.Point(6, 48);216 this.multiplicativeWeightChangeLabel.Location = new System.Drawing.Point(6, 68); 182 217 this.multiplicativeWeightChangeLabel.Name = "multiplicativeWeightChangeLabel"; 183 218 this.multiplicativeWeightChangeLabel.Size = new System.Drawing.Size(180, 13); 184 this.multiplicativeWeightChangeLabel.TabIndex = 2;219 this.multiplicativeWeightChangeLabel.TabIndex = 4; 185 220 this.multiplicativeWeightChangeLabel.Text = "Multiplicative weight change (sigma):"; 186 221 this.toolTip.SetToolTip(this.multiplicativeWeightChangeLabel, "The sigma parameter for the normal distribution to use to sample a multiplicative" + … … 191 226 this.multiplicativeWeightChangeSigmaTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 192 227 | System.Windows.Forms.AnchorStyles.Right))); 193 this.multiplicativeWeightChangeSigmaTextBox.Location = new System.Drawing.Point(201, 45);228 this.multiplicativeWeightChangeSigmaTextBox.Location = new System.Drawing.Point(201, 65); 194 229 this.multiplicativeWeightChangeSigmaTextBox.Name = "multiplicativeWeightChangeSigmaTextBox"; 195 230 this.multiplicativeWeightChangeSigmaTextBox.Size = new System.Drawing.Size(184, 20); 196 this.multiplicativeWeightChangeSigmaTextBox.TabIndex = 3;231 this.multiplicativeWeightChangeSigmaTextBox.TabIndex = 5; 197 232 this.toolTip.SetToolTip(this.multiplicativeWeightChangeSigmaTextBox, "The sigma (std.dev.) parameter for the normal distribution to sample a multiplica" + 198 233 "tive change in weight."); … … 202 237 // 203 238 this.additiveWeightChangeLabel.AutoSize = true; 204 this.additiveWeightChangeLabel.Location = new System.Drawing.Point(6, 22);239 this.additiveWeightChangeLabel.Location = new System.Drawing.Point(6, 42); 205 240 this.additiveWeightChangeLabel.Name = "additiveWeightChangeLabel"; 206 241 this.additiveWeightChangeLabel.Size = new System.Drawing.Size(157, 13); 207 this.additiveWeightChangeLabel.TabIndex = 0;242 this.additiveWeightChangeLabel.TabIndex = 2; 208 243 this.additiveWeightChangeLabel.Text = "Additive weight change (sigma):"; 209 244 this.toolTip.SetToolTip(this.additiveWeightChangeLabel, "The sigma (std.dev.) parameter for the normal distribution to sample an additive " + … … 214 249 this.additiveWeightChangeSigmaTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 215 250 | System.Windows.Forms.AnchorStyles.Right))); 216 this.additiveWeightChangeSigmaTextBox.Location = new System.Drawing.Point(201, 19);251 this.additiveWeightChangeSigmaTextBox.Location = new System.Drawing.Point(201, 39); 217 252 this.additiveWeightChangeSigmaTextBox.Name = "additiveWeightChangeSigmaTextBox"; 218 253 this.additiveWeightChangeSigmaTextBox.Size = new System.Drawing.Size(184, 20); 219 this.additiveWeightChangeSigmaTextBox.TabIndex = 1;254 this.additiveWeightChangeSigmaTextBox.TabIndex = 3; 220 255 this.toolTip.SetToolTip(this.additiveWeightChangeSigmaTextBox, "The sigma (std.dev.) parameter for the normal distribution to sample an additive " + 221 256 "change in weight."); … … 232 267 this.tabControl.Name = "tabControl"; 233 268 this.tabControl.SelectedIndex = 0; 234 this.tabControl.Size = new System.Drawing.Size(408, 190);235 this.tabControl.TabIndex = 5;269 this.tabControl.Size = new System.Drawing.Size(408, 216); 270 this.tabControl.TabIndex = 9; 236 271 // 237 272 // variableNamesTabPage … … 240 275 this.variableNamesTabPage.Name = "variableNamesTabPage"; 241 276 this.variableNamesTabPage.Padding = new System.Windows.Forms.Padding(3); 242 this.variableNamesTabPage.Size = new System.Drawing.Size(400, 1 64);277 this.variableNamesTabPage.Size = new System.Drawing.Size(400, 190); 243 278 this.variableNamesTabPage.TabIndex = 0; 244 279 this.variableNamesTabPage.Text = "Variable Names"; … … 252 287 this.parametersTabPage.Name = "parametersTabPage"; 253 288 this.parametersTabPage.Padding = new System.Windows.Forms.Padding(3); 254 this.parametersTabPage.Size = new System.Drawing.Size(400, 1 64);289 this.parametersTabPage.Size = new System.Drawing.Size(400, 190); 255 290 this.parametersTabPage.TabIndex = 1; 256 291 this.parametersTabPage.Text = "Parameters"; … … 259 294 // VariableView 260 295 // 261 this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);262 296 this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; 263 297 this.Controls.Add(this.tabControl); 264 298 this.Name = "VariableView"; 265 this.Size = new System.Drawing.Size(408, 317); 299 this.Size = new System.Drawing.Size(408, 346); 300 this.Controls.SetChildIndex(this.enabledCheckBox, 0); 266 301 this.Controls.SetChildIndex(this.maximumArityLabel, 0); 267 302 this.Controls.SetChildIndex(this.maximumArityTextBox, 0); … … 301 336 protected System.Windows.Forms.TabPage parametersTabPage; 302 337 protected System.Windows.Forms.TabControl tabControl; 338 protected System.Windows.Forms.TextBox varChangeProbTextBox; 339 protected System.Windows.Forms.Label varChangeProbLabel; 303 340 } 304 341 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/Symbols/VariableView.cs
r14312 r14878 29 29 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views; 30 30 using HeuristicLab.MainForm; 31 using HeuristicLab.MainForm.WindowsForms;32 31 33 32 34 33 namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views { 35 34 [View("Variable View")] 36 [Content(typeof(Variable ), true)]35 [Content(typeof(VariableBase), true)] 37 36 public partial class VariableView : SymbolView { 38 37 private CheckedItemCollectionView<StringValue> variableNamesView; 39 38 40 public new Variable Content {41 get { return (Variable )base.Content; }39 public new VariableBase Content { 40 get { return (VariableBase)base.Content; } 42 41 set { base.Content = value; } 43 42 } … … 101 100 multiplicativeWeightChangeSigmaTextBox.Enabled = Content != null; 102 101 multiplicativeWeightChangeSigmaTextBox.ReadOnly = ReadOnly; 102 varChangeProbTextBox.Enabled = Content != null; 103 varChangeProbTextBox.ReadOnly = ReadOnly; 103 104 } 104 105 … … 175 176 } 176 177 } 178 179 private void VarProbTextBox_TextChanged(object sender, EventArgs e) { 180 double prob; 181 if (double.TryParse(varChangeProbTextBox.Text, out prob) && prob >= 0.0 && prob <= 1.0) { 182 Content.VariableChangeProbability = prob; 183 errorProvider.SetError(varChangeProbTextBox, string.Empty); 184 } else { 185 errorProvider.SetError(varChangeProbTextBox, "Invalid value"); 186 } 187 } 177 188 #endregion 178 189 … … 184 195 additiveWeightChangeSigmaTextBox.Text = string.Empty; 185 196 multiplicativeWeightChangeSigmaTextBox.Text = string.Empty; 197 varChangeProbTextBox.Text = string.Empty; 186 198 // temporarily deregister to prevent circular calling of events 187 199 DeregisterVariableNamesViewContentEvents(); … … 201 213 additiveWeightChangeSigmaTextBox.Text = Content.WeightManipulatorSigma.ToString(); 202 214 multiplicativeWeightChangeSigmaTextBox.Text = Content.MultiplicativeWeightManipulatorSigma.ToString(); 215 varChangeProbTextBox.Text = Content.VariableChangeProbability.ToString(); 203 216 } 204 217 SetEnabledStateOfControls(); 205 218 } 206 219 #endregion 220 207 221 } 208 222 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/TreeEditDialogs/SymbolicExpressionTreeNodeInsertDialog.cs
r14576 r14878 65 65 constantValueLabel.Visible = true; 66 66 constantValueTextBox.Visible = true; 67 } else if (symbol is Variable ) {68 var variableSymbol = (Variable )symbol;67 } else if (symbol is VariableBase) { 68 var variableSymbol = (VariableBase)symbol; 69 69 if (variableSymbol.VariableNames.Any()) { 70 70 foreach (var name in variableSymbol.VariableNames) -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/TreeEditDialogs/SymbolicExpressionTreeVariableNodeEditDialog.cs
r14576 r14878 34 34 get { return variableTreeNode; } 35 35 set { 36 if (InvokeRequired) 37 Invoke(new Action<SymbolicExpressionTreeNode>(x => variableTreeNode = (VariableTreeNode)x), value); 38 else 36 if (InvokeRequired) { 37 Invoke(new Action<SymbolicExpressionTreeNode>(x => 38 { 39 variableTreeNode = (VariableTreeNode) x; 40 variableNameTextBox.Text = variableTreeNode.VariableName; 41 }), value); 42 } else { 39 43 variableTreeNode = value; 44 variableNameTextBox.Text = variableTreeNode.VariableName; 45 } 40 46 } 41 47 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisAlleleFrequencyAnalyzer.cs
r14312 r14878 89 89 var varTreeNode = tree as VariableTreeNode; 90 90 var constTreeNode = tree as ConstantTreeNode; 91 var factorVarTreeNode = tree as FactorVariableTreeNode; 92 var binFactorVarTreeNode = tree as BinaryFactorVariableTreeNode; 91 93 if (varTreeNode != null) { 92 94 builder.Append("(var " + varTreeNode.VariableName); 95 } else if (factorVarTreeNode != null) { 96 builder.Append("(factor " + factorVarTreeNode.VariableName); 97 } else if (binFactorVarTreeNode != null) { 98 builder.Append("(factor " + binFactorVarTreeNode.VariableName + "=" + binFactorVarTreeNode.VariableValue); 93 99 } else if (constTreeNode != null) { 94 100 builder.Append("(const"); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisSingleObjectiveTrainingBestSolutionAnalyzer.cs
r14312 r14878 35 35 [Item("SymbolicDataAnalysisSingleObjectiveTrainingBestSolutionAnalyzer", "An operator that analyzes the training best symbolic data analysis solution for single objective symbolic data analysis problems.")] 36 36 [StorableClass] 37 public abstract class SymbolicDataAnalysisSingleObjectiveTrainingBestSolutionAnalyzer<T> : SymbolicDataAnalysisSingleObjectiveAnalyzer, IIterationBasedOperator 38 39 where T : class, ISymbolicDataAnalysisSolution { 37 public abstract class SymbolicDataAnalysisSingleObjectiveTrainingBestSolutionAnalyzer<T> : SymbolicDataAnalysisSingleObjectiveAnalyzer, IIterationBasedOperator where T : class, ISymbolicDataAnalysisSolution { 40 38 private const string TrainingBestSolutionParameterName = "Best training solution"; 41 39 private const string TrainingBestSolutionQualityParameterName = "Best training solution quality"; 42 40 private const string TrainingBestSolutionGenerationParameterName = "Best training solution generation"; 41 private const string TrainingBestSolutionsHistoryParameterName = "Best training solutions history"; 43 42 private const string UpdateAlwaysParameterName = "Always update best solution"; 44 43 private const string IterationsParameterName = "Iterations"; 45 44 private const string MaximumIterationsParameterName = "Maximum Iterations"; 45 private const string StoreHistoryParameterName = "Store History"; 46 46 47 47 #region parameter properties … … 55 55 get { return (ILookupParameter<IntValue>)Parameters[TrainingBestSolutionGenerationParameterName]; } 56 56 } 57 public ILookupParameter<ItemList<T>> TrainingBestSolutionsHistoryParameter { 58 get { return (ILookupParameter<ItemList<T>>)Parameters[TrainingBestSolutionsHistoryParameterName]; } 59 } 57 60 public IFixedValueParameter<BoolValue> UpdateAlwaysParameter { 58 61 get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateAlwaysParameterName]; } … … 63 66 public IValueLookupParameter<IntValue> MaximumIterationsParameter { 64 67 get { return (IValueLookupParameter<IntValue>)Parameters[MaximumIterationsParameterName]; } 68 } 69 70 public IFixedValueParameter<BoolValue> StoreHistoryParameter { 71 get { return (IFixedValueParameter<BoolValue>)Parameters[StoreHistoryParameterName]; } 65 72 } 66 73 #endregion … … 74 81 set { TrainingBestSolutionQualityParameter.ActualValue = value; } 75 82 } 76 public BoolValue UpdateAlways { 77 get { return UpdateAlwaysParameter.Value; } 83 public bool UpdateAlways { 84 get { return UpdateAlwaysParameter.Value.Value; } 85 set { UpdateAlwaysParameter.Value.Value = value; } 86 } 87 88 public bool StoreHistory { 89 get { return StoreHistoryParameter.Value.Value; } 90 set { StoreHistoryParameter.Value.Value = value; } 78 91 } 79 92 #endregion 93 80 94 81 95 [StorableConstructor] … … 84 98 public SymbolicDataAnalysisSingleObjectiveTrainingBestSolutionAnalyzer() 85 99 : base() { 86 Parameters.Add(new LookupParameter<T>(TrainingBestSolutionParameterName, "The training bestsymbolic data analyis solution."));100 Parameters.Add(new LookupParameter<T>(TrainingBestSolutionParameterName, "The best training symbolic data analyis solution.")); 87 101 Parameters.Add(new LookupParameter<DoubleValue>(TrainingBestSolutionQualityParameterName, "The quality of the training best symbolic data analysis solution.")); 88 102 Parameters.Add(new LookupParameter<IntValue>(TrainingBestSolutionGenerationParameterName, "The generation in which the best training solution was found.")); … … 90 104 Parameters.Add(new LookupParameter<IntValue>(IterationsParameterName, "The number of performed iterations.")); 91 105 Parameters.Add(new ValueLookupParameter<IntValue>(MaximumIterationsParameterName, "The maximum number of performed iterations.") { Hidden = true }); 106 Parameters.Add(new FixedValueParameter<BoolValue>(StoreHistoryParameterName, "Flag that determines whether all encountered best solutions should be stored as results.", new BoolValue(false))); 107 Parameters.Add(new LookupParameter<ItemList<T>>(TrainingBestSolutionsHistoryParameterName, "The history of the best training symbolic data analysis solutions.")); 92 108 UpdateAlwaysParameter.Hidden = true; 93 109 } … … 105 121 if (!Parameters.ContainsKey(MaximumIterationsParameterName)) 106 122 Parameters.Add(new ValueLookupParameter<IntValue>(MaximumIterationsParameterName, "The maximum number of performed iterations.") { Hidden = true }); 123 if (!Parameters.ContainsKey(StoreHistoryParameterName)) 124 Parameters.Add(new FixedValueParameter<BoolValue>(StoreHistoryParameterName, "Flag that determines whether all encountered best solutions should be stored as results.", new BoolValue(false))); 125 if (!Parameters.ContainsKey(TrainingBestSolutionsHistoryParameterName)) 126 Parameters.Add(new LookupParameter<ItemList<T>>(TrainingBestSolutionsHistoryParameterName, "The history of the best training symbolic data analysis solutions.")); 107 127 } 108 128 109 129 public override IOperation Apply() { 130 var results = ResultCollection; 131 #region create results 132 if (!results.ContainsKey(TrainingBestSolutionParameter.Name)) 133 results.Add(new Result(TrainingBestSolutionParameter.Name, TrainingBestSolutionParameter.Description, typeof(T))); 134 if (!results.ContainsKey(TrainingBestSolutionQualityParameter.Name)) 135 results.Add(new Result(TrainingBestSolutionQualityParameter.Name, TrainingBestSolutionQualityParameter.Description, typeof(DoubleValue))); 136 if (!results.ContainsKey(TrainingBestSolutionGenerationParameter.Name) && IterationsParameter.ActualValue != null) 137 results.Add(new Result(TrainingBestSolutionGenerationParameter.Name, TrainingBestSolutionGenerationParameter.Description, typeof(IntValue))); 138 if (StoreHistory && !results.ContainsKey(TrainingBestSolutionsHistoryParameter.Name)) { 139 140 results.Add(new Result(TrainingBestSolutionsHistoryParameter.Name, TrainingBestSolutionsHistoryParameter.Description, typeof(ItemList<T>))); 141 TrainingBestSolutionsHistoryParameter.ActualValue = new ItemList<T>(); 142 results[TrainingBestSolutionsHistoryParameter.Name].Value = TrainingBestSolutionsHistoryParameter.ActualValue; 143 } 144 #endregion 145 110 146 #region find best tree 111 147 double bestQuality = Maximization.Value ? double.NegativeInfinity : double.PositiveInfinity; … … 121 157 #endregion 122 158 123 var results = ResultCollection; 124 if (bestTree != null && (UpdateAlways.Value || TrainingBestSolutionQuality == null || 159 if (bestTree != null && (UpdateAlways || TrainingBestSolutionQuality == null || 125 160 IsBetter(bestQuality, TrainingBestSolutionQuality.Value, Maximization.Value))) { 126 161 TrainingBestSolution = CreateSolution(bestTree, bestQuality); … … 129 164 TrainingBestSolutionGenerationParameter.ActualValue = new IntValue(IterationsParameter.ActualValue.Value); 130 165 131 if (!results.ContainsKey(TrainingBestSolutionParameter.Name)) { 132 results.Add(new Result(TrainingBestSolutionParameter.Name, TrainingBestSolutionParameter.Description, TrainingBestSolution)); 133 results.Add(new Result(TrainingBestSolutionQualityParameter.Name, TrainingBestSolutionQualityParameter.Description, TrainingBestSolutionQuality)); 134 if (TrainingBestSolutionGenerationParameter.ActualValue != null) 135 results.Add(new Result(TrainingBestSolutionGenerationParameter.Name, TrainingBestSolutionGenerationParameter.Description, TrainingBestSolutionGenerationParameter.ActualValue)); 136 } else { 137 results[TrainingBestSolutionParameter.Name].Value = TrainingBestSolution; 138 results[TrainingBestSolutionQualityParameter.Name].Value = TrainingBestSolutionQuality; 139 if (TrainingBestSolutionGenerationParameter.ActualValue != null) 140 results[TrainingBestSolutionGenerationParameter.Name].Value = TrainingBestSolutionGenerationParameter.ActualValue; 166 results[TrainingBestSolutionParameter.Name].Value = TrainingBestSolution; 167 results[TrainingBestSolutionQualityParameter.Name].Value = TrainingBestSolutionQuality; 168 if (TrainingBestSolutionGenerationParameter.ActualValue != null) 169 results[TrainingBestSolutionGenerationParameter.Name].Value = TrainingBestSolutionGenerationParameter.ActualValue; 141 170 171 if (StoreHistory) { 172 TrainingBestSolutionsHistoryParameter.ActualValue.Add(TrainingBestSolution); 142 173 } 143 174 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisVariableFrequencyAnalyzer.cs
r14312 r14878 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Globalization; 24 25 using System.Linq; 25 26 using HeuristicLab.Analysis; … … 41 42 private const string VariableFrequenciesParameterName = "VariableFrequencies"; 42 43 private const string AggregateLaggedVariablesParameterName = "AggregateLaggedVariables"; 44 private const string AggregateFactorVariablesParameterName = "AggregateFactorVariables"; 43 45 private const string VariableImpactsParameterName = "VariableImpacts"; 44 46 … … 52 54 public IValueLookupParameter<BoolValue> AggregateLaggedVariablesParameter { 53 55 get { return (IValueLookupParameter<BoolValue>)Parameters[AggregateLaggedVariablesParameterName]; } 56 } 57 public IValueLookupParameter<BoolValue> AggregateFactorVariablesParameter { 58 get { return (IValueLookupParameter<BoolValue>)Parameters[AggregateFactorVariablesParameterName]; } 54 59 } 55 60 #endregion … … 59 64 set { AggregateLaggedVariablesParameter.Value = value; } 60 65 } 66 public BoolValue AggregateFactorVariables { 67 get { return AggregateFactorVariablesParameter.ActualValue; } 68 set { AggregateFactorVariablesParameter.Value = value; } 69 } 61 70 #endregion 62 71 [StorableConstructor] … … 70 79 Parameters.Add(new LookupParameter<DoubleMatrix>(VariableImpactsParameterName, "The relative variable relevance calculated as the average relative variable frequency over the whole run.")); 71 80 Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateLaggedVariablesParameterName, "Switch that determines whether all references to a variable should be aggregated regardless of time-offsets. Turn off to analyze all variable references with different time offsets separately.", new BoolValue(true))); 81 Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateFactorVariablesParameterName, "Switch that determines whether all references to factor variables should be aggregated regardless of the value. Turn off to analyze all factor variable references with different values separately.", new BoolValue(true))); 82 } 83 84 [StorableHook(HookType.AfterDeserialization)] 85 private void AfterDeserialization() { 86 // BackwardsCompatibility3.3 87 #region Backwards compatible code, remove with 3.4 88 if (!Parameters.ContainsKey(AggregateFactorVariablesParameterName)) { 89 Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateFactorVariablesParameterName, "Switch that determines whether all references to factor variables should be aggregated regardless of the value. Turn off to analyze all factor variable references with different values separately.", new BoolValue(true))); 90 } 91 #endregion 72 92 } 73 93 … … 93 113 int numberOfValues = datatable.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First(); 94 114 95 foreach (var pair in SymbolicDataAnalysisVariableFrequencyAnalyzer.CalculateVariableFrequencies(expressions, AggregateLaggedVariables.Value)) {115 foreach (var pair in CalculateVariableFrequencies(expressions, AggregateLaggedVariables.Value, AggregateFactorVariables.Value)) { 96 116 if (!datatable.Rows.ContainsKey(pair.Key)) { 97 117 // initialize a new row for the variable and pad with zeros … … 128 148 } 129 149 130 public static IEnumerable<KeyValuePair<string, double>> CalculateVariableFrequencies(IEnumerable<ISymbolicExpressionTree> trees, bool aggregateLaggedVariables = true) { 150 public static IEnumerable<KeyValuePair<string, double>> CalculateVariableFrequencies(IEnumerable<ISymbolicExpressionTree> trees, 151 bool aggregateLaggedVariables = true, bool aggregateFactorVariables = true) { 131 152 132 153 var variableFrequencies = trees 133 .SelectMany(t => GetVariableReferences(t, aggregateLaggedVariables ))154 .SelectMany(t => GetVariableReferences(t, aggregateLaggedVariables, aggregateFactorVariables)) 134 155 .GroupBy(pair => pair.Key, pair => pair.Value) 135 156 .ToDictionary(g => g.Key, g => (double)g.Sum()); … … 141 162 } 142 163 143 private static IEnumerable<KeyValuePair<string, int>> GetVariableReferences(ISymbolicExpressionTree tree, bool aggregateLaggedVariables = true) { 164 private static IEnumerable<KeyValuePair<string, int>> GetVariableReferences(ISymbolicExpressionTree tree, 165 bool aggregateLaggedVariables = true, bool aggregateFactorVariables = true) { 144 166 Dictionary<string, int> references = new Dictionary<string, int>(); 145 167 if (aggregateLaggedVariables) { 146 168 tree.Root.ForEachNodePrefix(node => { 147 if (node.Symbol is Variable) { 148 var varNode = node as VariableTreeNode; 149 IncReferenceCount(references, varNode.VariableName); 150 } else if (node.Symbol is VariableCondition) { 151 var varCondNode = node as VariableConditionTreeNode; 152 IncReferenceCount(references, varCondNode.VariableName); 169 if (node is IVariableTreeNode) { 170 var factorNode = node as BinaryFactorVariableTreeNode; 171 if (factorNode != null && !aggregateFactorVariables) { 172 IncReferenceCount(references, factorNode.VariableName + "=" + factorNode.VariableValue); 173 } else { 174 var varNode = node as IVariableTreeNode; 175 IncReferenceCount(references, varNode.VariableName); 176 } 153 177 } 154 178 }); 155 179 } else { 156 GetVariableReferences(references, tree.Root, 0 );180 GetVariableReferences(references, tree.Root, 0, aggregateFactorVariables); 157 181 } 158 182 return references; 159 183 } 160 184 161 private static void GetVariableReferences(Dictionary<string, int> references, ISymbolicExpressionTreeNode node, int currentLag) { 162 if (node.Symbol is LaggedVariable) { 163 var laggedVarNode = node as LaggedVariableTreeNode; 164 IncReferenceCount(references, laggedVarNode.VariableName, currentLag + laggedVarNode.Lag); 165 } else if (node.Symbol is Variable) { 166 var varNode = node as VariableTreeNode; 167 IncReferenceCount(references, varNode.VariableName, currentLag); 168 } else if (node.Symbol is VariableCondition) { 169 var varCondNode = node as VariableConditionTreeNode; 170 IncReferenceCount(references, varCondNode.VariableName, currentLag); 171 GetVariableReferences(references, node.GetSubtree(0), currentLag); 172 GetVariableReferences(references, node.GetSubtree(1), currentLag); 185 private static void GetVariableReferences(Dictionary<string, int> references, ISymbolicExpressionTreeNode node, int currentLag, bool aggregateFactorVariables) { 186 if (node is IVariableTreeNode) { 187 var laggedVarTreeNode = node as LaggedVariableTreeNode; 188 var binFactorVariableTreeNode = node as BinaryFactorVariableTreeNode; 189 var varConditionTreeNode = node as VariableConditionTreeNode; 190 if (laggedVarTreeNode != null) { 191 IncReferenceCount(references, laggedVarTreeNode.VariableName, currentLag + laggedVarTreeNode.Lag); 192 } else if (binFactorVariableTreeNode != null) { 193 if (aggregateFactorVariables) { 194 IncReferenceCount(references, binFactorVariableTreeNode.VariableName, currentLag); 195 } else { 196 IncReferenceCount(references, binFactorVariableTreeNode.VariableName + "=" + binFactorVariableTreeNode.VariableValue, currentLag); 197 } 198 } else if (varConditionTreeNode != null) { 199 IncReferenceCount(references, varConditionTreeNode.VariableName, currentLag); 200 GetVariableReferences(references, node.GetSubtree(0), currentLag, aggregateFactorVariables); 201 GetVariableReferences(references, node.GetSubtree(1), currentLag, aggregateFactorVariables); 202 } else { 203 var varNode = node as IVariableTreeNode; 204 IncReferenceCount(references, varNode.VariableName, currentLag); 205 } 173 206 } else if (node.Symbol is Integral) { 174 207 var laggedNode = node as LaggedTreeNode; 175 208 for (int l = laggedNode.Lag; l <= 0; l++) { 176 GetVariableReferences(references, node.GetSubtree(0), currentLag + l );209 GetVariableReferences(references, node.GetSubtree(0), currentLag + l, aggregateFactorVariables); 177 210 } 178 211 } else if (node.Symbol is Derivative) { 179 212 for (int l = -4; l <= 0; l++) { 180 GetVariableReferences(references, node.GetSubtree(0), currentLag + l );213 GetVariableReferences(references, node.GetSubtree(0), currentLag + l, aggregateFactorVariables); 181 214 } 182 215 } else if (node.Symbol is TimeLag) { 183 216 var laggedNode = node as LaggedTreeNode; 184 GetVariableReferences(references, node.GetSubtree(0), currentLag + laggedNode.Lag );217 GetVariableReferences(references, node.GetSubtree(0), currentLag + laggedNode.Lag, aggregateFactorVariables); 185 218 } else { 186 219 foreach (var subtree in node.Subtrees) { 187 GetVariableReferences(references, subtree, currentLag );220 GetVariableReferences(references, subtree, currentLag, aggregateFactorVariables); 188 221 } 189 222 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs
r14576 r14878 141 141 strBuilder.Append(")"); 142 142 } 143 } else if (node.Symbol is FactorVariable) { 144 var factorNode = node as FactorVariableTreeNode; 145 if (factorNode.VariableName.Contains("'")) { 146 strBuilder.AppendFormat("\"{0}\"", factorNode.VariableName); 147 } else { 148 strBuilder.AppendFormat("'{0}'", factorNode.VariableName); 149 } 150 strBuilder.AppendFormat("[{0}]", 151 string.Join(", ", factorNode.Weights.Select(w => w.ToString(CultureInfo.InvariantCulture)))); 152 } else if (node.Symbol is BinaryFactorVariable) { 153 var factorNode = node as BinaryFactorVariableTreeNode; 154 if (!factorNode.Weight.IsAlmost(1.0)) { 155 strBuilder.Append("("); 156 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", factorNode.Weight); 157 strBuilder.Append("*"); 158 } 159 if (factorNode.VariableName.Contains("'")) { 160 strBuilder.AppendFormat("\"{0}\"", factorNode.VariableName); 161 } else { 162 strBuilder.AppendFormat("'{0}'", factorNode.VariableName); 163 } 164 strBuilder.Append(" = "); 165 if (factorNode.VariableValue.Contains("'")) { 166 strBuilder.AppendFormat("\"{0}\"", factorNode.VariableValue); 167 } else { 168 strBuilder.AppendFormat("'{0}'", factorNode.VariableValue); 169 } 170 171 if (!factorNode.Weight.IsAlmost(1.0)) { 172 strBuilder.Append(")"); 173 } 174 143 175 } else if (node.Symbol is Constant) { 144 176 var constNode = node as ConstantTreeNode; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionCSharpFormatter.cs
r14312 r14878 25 25 using System.Linq; 26 26 using System.Text; 27 using System.Text.RegularExpressions; 27 28 using HeuristicLab.Common; 28 29 using HeuristicLab.Core; … … 53 54 GenerateFooter(strBuilder); 54 55 return strBuilder.ToString(); 56 } 57 58 private string VariableName2Identifier(string name) { 59 /* 60 * identifier-start-character: 61 * letter-character 62 * _ (the underscore character U+005F) 63 * identifier-part-characters: 64 * identifier-part-character 65 * identifier-part-characters identifier-part-character 66 * identifier-part-character: 67 * letter-character 68 * decimal-digit-character 69 * connecting-character 70 * combining-character 71 * formatting-character 72 * letter-character: 73 * A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl 74 * A unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl 75 * combining-character: 76 * A Unicode character of classes Mn or Mc 77 * A unicode-escape-sequence representing a character of classes Mn or Mc 78 * decimal-digit-character: 79 * A Unicode character of the class Nd 80 * A unicode-escape-sequence representing a character of the class Nd 81 * connecting-character: 82 * A Unicode character of the class Pc 83 * A unicode-escape-sequence representing a character of the class Pc 84 * formatting-character: 85 * A Unicode character of the class Cf 86 * A unicode-escape-sequence representing a character of the class Cf 87 */ 88 89 var invalidIdentifierStarts = new Regex(@"[^_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]"); 90 var invalidIdentifierParts = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]"); 91 return "@" + 92 (invalidIdentifierStarts.IsMatch(name.Substring(0, 1)) ? "_" : "") + // prepend '_' if necessary 93 invalidIdentifierParts.Replace(name, "_"); 55 94 } 56 95 … … 106 145 if (node is VariableTreeNode) { 107 146 var varNode = node as VariableTreeNode; 108 strBuilder.AppendFormat("{0} * {1}", varNode.VariableName, varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));147 strBuilder.AppendFormat("{0} * {1}", VariableName2Identifier(varNode.VariableName), varNode.Weight.ToString("g17", CultureInfo.InvariantCulture)); 109 148 } else if (node is ConstantTreeNode) { 110 149 var constNode = node as ConstantTreeNode; 111 150 strBuilder.Append(constNode.Value.ToString("g17", CultureInfo.InvariantCulture)); 151 } else if (node.Symbol is FactorVariable) { 152 var factorNode = node as FactorVariableTreeNode; 153 FormatFactor(factorNode, strBuilder); 154 } else if (node.Symbol is BinaryFactorVariable) { 155 var binFactorNode = node as BinaryFactorVariableTreeNode; 156 FormatBinaryFactor(binFactorNode, strBuilder); 112 157 } else { 113 158 throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter."); 114 159 } 115 160 } 161 } 162 163 private void FormatFactor(FactorVariableTreeNode node, StringBuilder strBuilder) { 164 strBuilder.AppendFormat("EvaluateFactor({0}, new [] {{ {1} }}, new [] {{ {2} }})", VariableName2Identifier(node.VariableName), 165 string.Join(",", node.Symbol.GetVariableValues(node.VariableName).Select(name => "\"" + name + "\"")), string.Join(",", node.Weights.Select(v => v.ToString(CultureInfo.InvariantCulture)))); 166 } 167 168 private void FormatBinaryFactor(BinaryFactorVariableTreeNode node, StringBuilder strBuilder) { 169 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "EvaluateBinaryFactor({0}, \"{1}\", {2})", VariableName2Identifier(node.VariableName), node.VariableValue, node.Weight); 116 170 } 117 171 … … 182 236 GenerateAverageSource(strBuilder); 183 237 GenerateIfThenElseSource(strBuilder); 238 GenerateFactorSource(strBuilder); 239 GenerateBinaryFactorSource(strBuilder); 184 240 strBuilder.Append(Environment.NewLine + "public static double Evaluate ("); 185 241 186 HashSet<string> varNames = new HashSet<string>(); 187 foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode)) { 188 varNames.Add(((VariableTreeNode)node).VariableName); 189 } 190 191 var orderedNames = varNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "double " + n); 242 // here we don't have access to problemData to determine the type for each variable (double/string) therefore we must distinguish based on the symbol type 243 HashSet<string> doubleVarNames = new HashSet<string>(); 244 foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode || x is VariableConditionTreeNode)) { 245 doubleVarNames.Add(((IVariableTreeNode)node).VariableName); 246 } 247 248 HashSet<string> stringVarNames = new HashSet<string>(); 249 foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is BinaryFactorVariableTreeNode || x is FactorVariableTreeNode)) { 250 stringVarNames.Add(((IVariableTreeNode)node).VariableName); 251 } 252 253 var orderedNames = stringVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "string " + VariableName2Identifier(n) + " /* " + n + " */"); 192 254 strBuilder.Append(string.Join(", ", orderedNames)); 255 256 if (stringVarNames.Any() && doubleVarNames.Any()) 257 strBuilder.AppendLine(","); 258 orderedNames = doubleVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "double " + VariableName2Identifier(n) + " /* " + n + " */"); 259 strBuilder.Append(string.Join(", ", orderedNames)); 260 193 261 194 262 strBuilder.AppendLine(") {"); … … 198 266 private void GenerateFooter(StringBuilder strBuilder) { 199 267 strBuilder.AppendLine(";"); 268 200 269 strBuilder.AppendLine("return result;"); 201 270 strBuilder.AppendLine("}"); … … 215 284 strBuilder.AppendLine("}"); 216 285 } 286 287 private void GenerateFactorSource(StringBuilder strBuilder) { 288 strBuilder.AppendLine("private static double EvaluateFactor(string factorValue, string[] factorValues, double[] constants) {"); 289 strBuilder.AppendLine(" for(int i=0;i<factorValues.Length;i++) " + 290 " if(factorValues[i] == factorValue) return constants[i];" + 291 " throw new ArgumentException();"); 292 strBuilder.AppendLine("}"); 293 } 294 295 private void GenerateBinaryFactorSource(StringBuilder strBuilder) { 296 strBuilder.AppendLine("private static double EvaluateBinaryFactor(string factorValue, string targetValue, double weight) {"); 297 strBuilder.AppendLine(" return factorValue == targetValue ? weight : 0.0;"); 298 strBuilder.AppendLine("}"); 299 } 300 217 301 } 218 302 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionExcelFormatter.cs
r14312 r14878 51 51 while (dividend > 0) { 52 52 int modulo = (dividend - 1) % 26; 53 columnName = Convert.ToChar(65 + modulo).ToString() + columnName;53 columnName = System.Convert.ToChar(65 + modulo) + columnName; 54 54 dividend = (int)((dividend - modulo) / 26); 55 55 } … … 60 60 private readonly Dictionary<string, string> variableNameMapping = new Dictionary<string, string>(); 61 61 private int currentVariableIndex = 0; 62 private string GetColumnToVariableName(string var iabelName) {63 if (!variableNameMapping.ContainsKey(var iabelName)) {62 private string GetColumnToVariableName(string varName) { 63 if (!variableNameMapping.ContainsKey(varName)) { 64 64 currentVariableIndex++; 65 variableNameMapping.Add(var iabelName, GetExcelColumnName(currentVariableIndex));66 } 67 return string.Format("${0}1", variableNameMapping[var iabelName]);65 variableNameMapping.Add(varName, GetExcelColumnName(currentVariableIndex)); 66 } 67 return string.Format("${0}1", variableNameMapping[varName]); 68 68 } 69 69 public string Format(ISymbolicExpressionTree symbolicExpressionTree) { … … 71 71 } 72 72 73 73 74 public string Format(ISymbolicExpressionTree symbolicExpressionTree, IDataset dataset) { 75 if (dataset != null) 76 return FormatWithMapping(symbolicExpressionTree, CalculateVariableMapping(symbolicExpressionTree, dataset)); 77 else return FormatWithMapping(symbolicExpressionTree, new Dictionary<string, string>()); 78 } 79 80 public string FormatWithMapping(ISymbolicExpressionTree symbolicExpressionTree, Dictionary<string,string> variableNameMapping) 81 { 82 foreach(var kvp in variableNameMapping) this.variableNameMapping.Add(kvp.Key,kvp.Value); 74 83 var stringBuilder = new StringBuilder(); 75 if (dataset != null) CalculateVariableMapping(symbolicExpressionTree, dataset); 76 84 77 85 stringBuilder.Append("="); 78 86 stringBuilder.Append(FormatRecursively(symbolicExpressionTree.Root)); 79 87 80 foreach (var variable in variableNameMapping) {88 foreach (var variable in this.variableNameMapping) { 81 89 stringBuilder.AppendLine(); 82 90 stringBuilder.Append(variable.Key + " = " + variable.Value); … … 85 93 } 86 94 87 private voidCalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) {88 int columnIndex = 0;95 private Dictionary<string,string> CalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) { 96 var mapping = new Dictionary<string,string>(); 89 97 int inputIndex = 0; 90 var usedVariables = tree.IterateNodesPrefix().OfType< VariableTreeNode>().Select(v => v.VariableName).Distinct();98 var usedVariables = tree.IterateNodesPrefix().OfType<IVariableTreeNode>().Select(v => v.VariableName).Distinct().ToArray(); 91 99 foreach (var variable in dataset.VariableNames) { 92 columnIndex++;93 100 if (!usedVariables.Contains(variable)) continue; 94 101 inputIndex++; 95 variableNameMapping[variable] = GetExcelColumnName(inputIndex); 96 } 102 mapping[variable] = GetExcelColumnName(inputIndex); 103 } 104 return mapping; 97 105 } 98 106 … … 190 198 stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture)); 191 199 stringBuilder.Append("*"); 192 stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName));// + LagToString(currentLag)); 200 stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName)); 201 } else if (symbol is BinaryFactorVariable) { 202 var binFactorNode = node as BinaryFactorVariableTreeNode; 203 stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, 0)", 204 GetColumnToVariableName(binFactorNode.VariableName), 205 binFactorNode.VariableValue, 206 binFactorNode.Weight.ToString(CultureInfo.InvariantCulture) 207 ); 208 } else if (symbol is FactorVariable) { 209 var factorNode = node as FactorVariableTreeNode; 210 var values = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray(); 211 var w = factorNode.Weights; 212 // create nested if 213 for (int i = 0; i < values.Length; i++) { 214 stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, ", 215 GetColumnToVariableName(factorNode.VariableName), 216 values[i], 217 w[i].ToString(CultureInfo.InvariantCulture)); 218 } 219 stringBuilder.Append("\"\""); // return empty string on unknown value 220 stringBuilder.Append(')', values.Length); // add closing parenthesis 193 221 } else if (symbol is Power) { 194 222 stringBuilder.Append("POWER("); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionLatexFormatter.cs
r14576 r14878 33 33 [StorableClass] 34 34 public sealed class SymbolicDataAnalysisExpressionLatexFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter { 35 private readonly List<double> constants; 35 private readonly List<KeyValuePair<string, double>> constants; 36 private int constIndex; 36 37 private int targetCount; 37 38 private int currentLag; … … 43 44 private SymbolicDataAnalysisExpressionLatexFormatter(SymbolicDataAnalysisExpressionLatexFormatter original, Cloner cloner) 44 45 : base(original, cloner) { 45 constants = new List<double>(original.constants); 46 constants = new List<KeyValuePair<string, double>>(original.constants); 47 constIndex = original.constIndex; 48 currentLag = original.currentLag; 49 targetCount = original.targetCount; 46 50 } 47 51 public SymbolicDataAnalysisExpressionLatexFormatter() … … 49 53 Name = ItemName; 50 54 Description = ItemDescription; 51 constants = new List< double>();55 constants = new List<KeyValuePair<string, double>>(); 52 56 } 53 57 … … 63 67 StringBuilder strBuilder = new StringBuilder(); 64 68 constants.Clear(); 69 constIndex = 0; 65 70 this.targetVariable = targetVariable; 66 71 containsTimeSeriesSymbol = symbolicExpressionTree.IterateNodesBreadth().Any(n => IsTimeSeriesSymbol(n.Symbol)); … … 84 89 } 85 90 int i = 1; 86 foreach ( SymbolicExpressionTreeNodesubTree in node.Subtrees.Skip(1)) {91 foreach (var subTree in node.Subtrees.Skip(1)) { 87 92 FormatSep(node, strBuilder, i); 88 93 // format the whole subtree … … 175 180 strBuilder.Append(@" \operatorname{if} \left( "); 176 181 } else if (node.Symbol is Constant) { 182 var constName = "c_{" + constIndex + "}"; 183 constIndex++; 177 184 var constNode = node as ConstantTreeNode; 178 185 if (constNode.Value.IsAlmost(1.0)) { 179 186 strBuilder.Append("1 "); 180 187 } else { 181 strBuilder.Append("c_{" + constants.Count + "} "); 182 constants.Add(constNode.Value); 183 } 188 strBuilder.Append(constName); 189 constants.Add(new KeyValuePair<string, double>(constName, constNode.Value)); 190 } 191 192 } else if (node.Symbol is FactorVariable) { 193 var factorNode = node as FactorVariableTreeNode; 194 var constName = "c_{" + constIndex + "}"; 195 strBuilder.Append(constName + " "); 196 foreach (var e in factorNode.Symbol.GetVariableValues(factorNode.VariableName) 197 .Zip(factorNode.Weights, Tuple.Create)) { 198 constants.Add(new KeyValuePair<string, double>("c_{" + constIndex + ", " + EscapeLatexString(factorNode.VariableName) + "=" + EscapeLatexString(e.Item1) + "}", e.Item2)); 199 } 200 constIndex++; 201 } else if (node.Symbol is BinaryFactorVariable) { 202 var binFactorNode = node as BinaryFactorVariableTreeNode; 203 if (!binFactorNode.Weight.IsAlmost((1.0))) { 204 var constName = "c_{" + constIndex + "}"; 205 strBuilder.Append(constName + " \\cdot"); 206 constants.Add(new KeyValuePair<string, double>(constName, binFactorNode.Weight)); 207 constIndex++; 208 } 209 strBuilder.Append("(" + EscapeLatexString(binFactorNode.VariableName)); 210 strBuilder.Append(LagToString(currentLag)); 211 strBuilder.Append(" = " + EscapeLatexString(binFactorNode.VariableValue) + " )"); 184 212 } else if (node.Symbol is LaggedVariable) { 185 213 var laggedVarNode = node as LaggedVariableTreeNode; 186 214 if (!laggedVarNode.Weight.IsAlmost(1.0)) { 187 strBuilder.Append("c_{" + constants.Count + "} \\cdot "); 188 constants.Add(laggedVarNode.Weight); 215 var constName = "c_{" + constIndex + "}"; 216 strBuilder.Append(constName + " \\cdot"); 217 constants.Add(new KeyValuePair<string, double>(constName, laggedVarNode.Weight)); 218 constIndex++; 189 219 } 190 220 strBuilder.Append(EscapeLatexString(laggedVarNode.VariableName)); … … 194 224 var varNode = node as VariableTreeNode; 195 225 if (!varNode.Weight.IsAlmost((1.0))) { 196 strBuilder.Append("c_{" + constants.Count + "} \\cdot "); 197 constants.Add(varNode.Weight); 226 var constName = "c_{" + constIndex + "}"; 227 strBuilder.Append(constName + " \\cdot"); 228 constants.Add(new KeyValuePair<string, double>(constName, varNode.Weight)); 229 constIndex++; 198 230 } 199 231 strBuilder.Append(EscapeLatexString(varNode.VariableName)); … … 229 261 } else if (node.Symbol is VariableCondition) { 230 262 var conditionTreeNode = node as VariableConditionTreeNode; 231 string p = @"1 / 1 + \exp - c_{" + constants.Count + "} "; 232 constants.Add(conditionTreeNode.Slope); 233 p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} "; 234 constants.Add(conditionTreeNode.Threshold); 263 var constName = "c_{" + constants.Count + "}"; 264 string p = @"1 / 1 + \exp - " + constName + " "; 265 constants.Add(new KeyValuePair<string, double>(constName, conditionTreeNode.Slope)); 266 constIndex++; 267 var const2Name = "c_{" + constants.Count + @"}"; 268 p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - " + const2Name + " "; 269 constants.Add(new KeyValuePair<string, double>(const2Name, conditionTreeNode.Threshold)); 270 constIndex++; 235 271 strBuilder.Append(@" \left( " + p + @"\cdot "); 236 272 } else { … … 323 359 } else if (node.Symbol is VariableCondition) { 324 360 var conditionTreeNode = node as VariableConditionTreeNode; 325 string p = @"1 / \left( 1 + \exp \left( - c_{" + constants.Count + "} "; 326 constants.Add(conditionTreeNode.Slope); 327 p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} \right) \right) \right) "; 328 constants.Add(conditionTreeNode.Threshold); 361 var const1Name = "c_{" + constants.Count + "}"; 362 string p = @"1 / \left( 1 + \exp \left( - " + const1Name + " "; 363 constants.Add(new KeyValuePair<string, double>(const1Name, conditionTreeNode.Slope)); 364 constIndex++; 365 var const2Name = "c_{" + constants.Count + "}"; 366 p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - " + const2Name + " \right) \right) \right) "; 367 constants.Add(new KeyValuePair<string, double>(const2Name, conditionTreeNode.Threshold)); 368 constIndex++; 329 369 strBuilder.Append(@" + \left( 1 - " + p + @" \right) \cdot "); 330 370 } else { … … 404 444 } else if (node.Symbol is LaggedVariable) { 405 445 } else if (node.Symbol is Variable) { 446 } else if (node.Symbol is FactorVariable) { 447 } else if (node.Symbol is BinaryFactorVariable) { 406 448 } else if (node.Symbol is ProgramRootSymbol) { 407 449 strBuilder … … 411 453 // output all constant values 412 454 if (constants.Count > 0) { 413 int i = 0;414 455 foreach (var constant in constants) { 415 456 // replace "." with ".&" to align decimal points 416 var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant );457 var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant.Value); 417 458 if (!constStr.Contains(".")) constStr = constStr + ".0"; 418 459 constStr = constStr.Replace(".", "&."); // fix problem in rendering of aligned expressions 419 strBuilder.Append( "c_{" + i + "}& = & " + constStr);460 strBuilder.Append(constant.Key + "& = & " + constStr); 420 461 strBuilder.Append(@"\\"); 421 i++;422 462 } 423 463 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMATLABFormatter.cs
r14312 r14878 21 21 22 22 using System.Globalization; 23 using System.Linq; 23 24 using System.Text; 24 25 using HeuristicLab.Common; … … 77 78 stringBuilder.AppendLine(" y = (f0 + 2*f1 - 2*f3 - f4) / 8;"); 78 79 stringBuilder.AppendLine("end"); 80 81 var factorVariableNames = 82 symbolicExpressionTree.IterateNodesPostfix() 83 .OfType<FactorVariableTreeNode>() 84 .Select(n => n.VariableName) 85 .Distinct(); 86 87 foreach (var factorVarName in factorVariableNames) { 88 var factorSymb = symbolicExpressionTree.IterateNodesPostfix() 89 .OfType<FactorVariableTreeNode>() 90 .First(n => n.VariableName == factorVarName) 91 .Symbol; 92 stringBuilder.AppendFormat("function y = switch_{0}(val, v)", factorVarName).AppendLine(); 93 var values = factorSymb.GetVariableValues(factorVarName).ToArray(); 94 stringBuilder.AppendLine("switch val"); 95 for (int i = 0; i < values.Length; i++) { 96 stringBuilder.AppendFormat(CultureInfo.InvariantCulture, " case \"{0}\" y = v({1})", values[i], i).AppendLine(); 97 } 98 stringBuilder.AppendLine("end"); 99 stringBuilder.AppendLine(); 100 } 101 79 102 return stringBuilder.ToString(); 80 103 } … … 296 319 stringBuilder.Append("*"); 297 320 stringBuilder.Append(variableTreeNode.VariableName + LagToString(currentLag)); 321 } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.FactorVariable) { 322 var factorNode = node as FactorVariableTreeNode; 323 var weights = string.Join(" ", factorNode.Weights.Select(w => w.ToString("G17", CultureInfo.InvariantCulture))); 324 stringBuilder.AppendFormat("switch_{0}(\"{1}\",[{2}])", 325 factorNode.VariableName, factorNode.VariableName, weights) 326 .AppendLine(); 327 } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.BinaryFactorVariable) { 328 var factorNode = node as BinaryFactorVariableTreeNode; 329 stringBuilder.AppendFormat(CultureInfo.InvariantCulture, 330 "((strcmp({0},\"{1}\")==1) * {2:G17})", factorNode.VariableName, factorNode.VariableValue, factorNode.Weight); 298 331 } else if (symbol is Power) { 299 332 stringBuilder.Append("("); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMathematicaFormatter.cs
r14312 r14878 110 110 } 111 111 } else { 112 if (node is VariableTreeNode) { 112 // terminals 113 if (node.Symbol is Variable) { 113 114 var varNode = node as VariableTreeNode; 114 115 strBuilder.AppendFormat("Times[{0}, {1}]", varNode.VariableName, varNode.Weight.ToString("G17", CultureInfo.InvariantCulture)); 115 } else if (node is ConstantTreeNode) {116 } else if (node.Symbol is Constant) { 116 117 var constNode = node as ConstantTreeNode; 117 118 strBuilder.Append(constNode.Value.ToString("G17", CultureInfo.InvariantCulture)); 119 } else if (node.Symbol is FactorVariable) { 120 var factorNode = node as FactorVariableTreeNode; 121 strBuilder.AppendFormat("Switch[{0},", factorNode.VariableName); 122 var varValues = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray(); 123 var weights = varValues.Select(factorNode.GetValue).ToArray(); 124 125 var weightStr = string.Join(", ", 126 varValues.Zip(weights, (s, d) => string.Format(CultureInfo.InvariantCulture, "\"{0}\", {1:G17}", s, d))); 127 strBuilder.Append(weightStr); 128 strBuilder.Append("]"); 129 } else if (node.Symbol is BinaryFactorVariable) { 130 var factorNode = node as BinaryFactorVariableTreeNode; 131 strBuilder.AppendFormat(CultureInfo.InvariantCulture, "If[{0}==\"{1}\",{2:G17},0.0]", 132 factorNode.VariableName, factorNode.VariableValue, factorNode.Weight); 118 133 } else { 119 134 throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " is not supported."); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionSmalltalkFormatter.cs
r14312 r14878 115 115 stringBuilder.Append("]"); 116 116 } else if (symbol is LaggedVariable) { 117 stringBuilder.Append("lagged variable not implemented");117 stringBuilder.Append("lagged variables are not supported"); 118 118 } else if (symbol is LessThan) { 119 119 stringBuilder.Append("("); … … 165 165 stringBuilder.Append("*"); 166 166 stringBuilder.Append(variableTreeNode.VariableName); 167 } else if (symbol is BinaryFactorVariable || symbol is FactorVariable) { 168 stringBuilder.Append("factor variables are not supported"); 167 169 } else { 168 170 stringBuilder.Append("("); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Grammars/ArithmeticExpressionGrammar.cs
r14312 r14878 53 53 constant.MaxValue = 20; 54 54 var variableSymbol = new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable(); 55 var binFactorVariableSymbol = new BinaryFactorVariable(); 56 var factorVariableSymbol = new FactorVariable(); 55 57 56 var allSymbols = new List<Symbol>() { add, sub, mul, div, constant, variableSymbol 58 var allSymbols = new List<Symbol>() { add, sub, mul, div, constant, variableSymbol, binFactorVariableSymbol, factorVariableSymbol}; 57 59 var functionSymbols = new List<Symbol>() { add, sub, mul, div }; 58 60 … … 65 67 SetSubtreeCount(constant, 0, 0); 66 68 SetSubtreeCount(variableSymbol, 0, 0); 69 SetSubtreeCount(binFactorVariableSymbol, 0, 0); 70 SetSubtreeCount(factorVariableSymbol, 0, 0); 67 71 68 72 // allow each symbol as child of the start symbol -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Grammars/FullFunctionalExpressionGrammar.cs
r14312 r14878 115 115 constant.MaxValue = 20; 116 116 var variableSymbol = new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable(); 117 var binFactorVariable = new BinaryFactorVariable(); 118 var factorVariable = new FactorVariable(); 117 119 var laggedVariable = new LaggedVariable(); 118 120 laggedVariable.InitialFrequency = 0.0; … … 123 125 var allSymbols = new List<Symbol>() { add, sub, mul, div, mean, sin, cos, tan, log, square, pow, sqrt, root, exp, 124 126 airyA, airyB, bessel, cosineIntegral, dawson, erf, expIntegralEi, fresnelCosineIntegral, fresnelSineIntegral, gamma, hypCosineIntegral, hypSineIntegral, norm, psi, sineIntegral, 125 @if, gt, lt, and, or, not,xor, timeLag, integral, derivative, constant, variableSymbol, laggedVariable,autoregressiveVariable, variableCondition };127 @if, gt, lt, and, or, not,xor, timeLag, integral, derivative, constant, variableSymbol, binFactorVariable, factorVariable, laggedVariable,autoregressiveVariable, variableCondition }; 126 128 var unaryFunctionSymbols = new List<Symbol>() { square, sqrt, sin, cos, tan, log, exp, not, timeLag, integral, derivative, 127 129 airyA, airyB, bessel, cosineIntegral, dawson, erf, expIntegralEi, fresnelCosineIntegral, fresnelSineIntegral, gamma, hypCosineIntegral, hypSineIntegral, norm, psi, sineIntegral … … 130 132 var binaryFunctionSymbols = new List<Symbol>() { pow, root, gt, lt, variableCondition }; 131 133 var ternarySymbols = new List<Symbol>() { add, sub, mul, div, mean, and, or, xor }; 132 var terminalSymbols = new List<Symbol>() { variableSymbol, constant, laggedVariable, autoregressiveVariable };134 var terminalSymbols = new List<Symbol>() { variableSymbol, binFactorVariable, factorVariable, constant, laggedVariable, autoregressiveVariable }; 133 135 134 136 foreach (var symb in allSymbols) -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Grammars/TypeCoherentExpressionGrammar.cs
r14312 r14878 26 26 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 27 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;29 28 30 29 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { … … 88 87 var psi = new Psi(); 89 88 var sineIntegral = new SineIntegral(); 90 var passthrough = new Passthrough();91 89 92 90 var @if = new IfThenElse(); … … 107 105 constant.MaxValue = 20; 108 106 var variableSymbol = new Variable(); 107 var binFactorVariable = new BinaryFactorVariable(); 108 var factorVariable = new FactorVariable(); 109 109 var laggedVariable = new LaggedVariable(); 110 110 var autoregressiveVariable = new AutoregressiveTargetVariable(); … … 115 115 var trigonometricSymbols = new GroupSymbol(TrigonometricFunctionsName, new List<ISymbol>() { sin, cos, tan }); 116 116 var exponentialAndLogarithmicSymbols = new GroupSymbol(ExponentialFunctionsName, new List<ISymbol> { exp, log }); 117 var specialFunctions = new GroupSymbol(SpecialFunctionsName, new List<ISymbol> { airyA, airyB, bessel, cosineIntegral, dawson, erf, expIntegralEi, 118 fresnelCosineIntegral,fresnelSineIntegral,gamma,hypCosineIntegral,hypSineIntegral,norm, psi, sineIntegral , passthrough});119 var terminalSymbols = new GroupSymbol(TerminalsName, new List<ISymbol> { constant, variableSymbol });117 var specialFunctions = new GroupSymbol(SpecialFunctionsName, new List<ISymbol> { airyA, airyB, bessel, cosineIntegral, dawson, erf, expIntegralEi, 118 fresnelCosineIntegral,fresnelSineIntegral,gamma,hypCosineIntegral,hypSineIntegral,norm, psi, sineIntegral}); 119 var terminalSymbols = new GroupSymbol(TerminalsName, new List<ISymbol> { constant, variableSymbol, binFactorVariable, factorVariable }); 120 120 var realValuedSymbols = new GroupSymbol(RealValuedSymbolsName, new List<ISymbol>() { arithmeticSymbols, trigonometricSymbols, exponentialAndLogarithmicSymbols, specialFunctions, terminalSymbols }); 121 121 … … 159 159 SetSubtreeCount(laggedVariable, 0, 0); 160 160 SetSubtreeCount(autoregressiveVariable, 0, 0); 161 SetSubtreeCount(passthrough, 1, 1);162 161 #endregion 163 162 … … 228 227 AddAllowedChildSymbol(derivative, powerSymbols); 229 228 AddAllowedChildSymbol(derivative, conditionSymbols); 230 231 AddAllowedChildSymbol(passthrough, realValuedSymbols);232 AddAllowedChildSymbol(passthrough, powerSymbols);233 AddAllowedChildSymbol(passthrough, conditionSymbols);234 AddAllowedChildSymbol(passthrough, timeSeriesSymbols);235 AddAllowedChildSymbol(passthrough, specialFunctions);236 229 #endregion 237 230 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4.csproj
r14427 r14878 47 47 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 48 48 <Prefer32Bit>false</Prefer32Bit> 49 <UseVSHostingProcess>false</UseVSHostingProcess>50 49 </PropertyGroup> 51 50 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> … … 102 101 <Reference Include="ALGLIB-3.7.0"> 103 102 <HintPath>..\..\..\..\trunk\sources\bin\ALGLIB-3.7.0.dll</HintPath> 104 <Private>False</Private> 103 </Reference> 104 <Reference Include="AutoDiff-1.0"> 105 <HintPath>..\..\..\..\trunk\sources\bin\AutoDiff-1.0.dll</HintPath> 105 106 </Reference> 106 107 <Reference Include="HeuristicLab.Analysis-3.3"> 107 108 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Analysis-3.3.dll</HintPath> 108 <Private>False</Private>109 109 </Reference> 110 110 <Reference Include="HeuristicLab.Collections-3.3"> 111 111 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Collections-3.3.dll</HintPath> 112 <Private>False</Private> 113 </Reference> 114 <Reference Include="HeuristicLab.Common-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL"> 115 <SpecificVersion>False</SpecificVersion> 112 </Reference> 113 <Reference Include="HeuristicLab.Common-3.3"> 116 114 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Common-3.3.dll</HintPath> 117 <Private>False</Private>118 115 </Reference> 119 116 <Reference Include="HeuristicLab.Common.Resources-3.3"> 120 117 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Common.Resources-3.3.dll</HintPath> 121 <Private>False</Private> 122 </Reference> 123 <Reference Include="HeuristicLab.Core-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL"> 124 <SpecificVersion>False</SpecificVersion> 118 </Reference> 119 <Reference Include="HeuristicLab.Core-3.3"> 125 120 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Core-3.3.dll</HintPath> 126 <Private>False</Private>127 121 </Reference> 128 122 <Reference Include="HeuristicLab.Data-3.3"> 129 123 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath> 130 <Private>False</Private>131 124 </Reference> 132 125 <Reference Include="HeuristicLab.Operators-3.3"> 133 126 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Operators-3.3.dll</HintPath> 134 <Private>False</Private>135 127 </Reference> 136 128 <Reference Include="HeuristicLab.Optimization-3.3"> 137 129 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization-3.3.dll</HintPath> 138 <Private>False</Private>139 130 </Reference> 140 131 <Reference Include="HeuristicLab.Optimization.Operators-3.3"> 141 132 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization.Operators-3.3.dll</HintPath> 142 <Private>False</Private>143 133 </Reference> 144 134 <Reference Include="HeuristicLab.Parameters-3.3"> 145 135 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Parameters-3.3.dll</HintPath> 146 <Private>False</Private>147 136 </Reference> 148 137 <Reference Include="HeuristicLab.Persistence-3.3"> 149 138 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Persistence-3.3.dll</HintPath> 150 <Private>False</Private>151 139 </Reference> 152 140 <Reference Include="HeuristicLab.PluginInfrastructure-3.3"> 153 141 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.PluginInfrastructure-3.3.dll</HintPath> 154 <Private>False</Private>155 142 </Reference> 156 143 <Reference Include="HeuristicLab.Problems.DataAnalysis-3.4"> 157 144 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.DataAnalysis-3.4.dll</HintPath> 158 <Private>False</Private>159 145 </Reference> 160 146 <Reference Include="HeuristicLab.Problems.Instances-3.3"> 161 147 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.Instances-3.3.dll</HintPath> 162 <Private>False</Private>163 148 </Reference> 164 149 <Reference Include="HeuristicLab.Random-3.3"> 165 150 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath> 166 <Private>False</Private>167 151 </Reference> 168 152 <Reference Include="System" /> … … 181 165 </ItemGroup> 182 166 <ItemGroup> 183 <Compile Include="Analyzers\BuildingBlockAnalyzers\SymbolicDataAnalysisPoly10Analyzer.cs" />184 167 <Compile Include="Analyzers\SymbolicDataAnalysisBottomUpDiversityAnalyzer.cs" /> 168 <Compile Include="Analyzers\SymbolicDataAnalysisGenealogyAnalyzer.cs" /> 185 169 <Compile Include="Analyzers\SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer.cs" /> 186 <Compile Include="Importer\InfixExpressionParser.cs" />187 <Compile Include="SymbolicDataAnalysisExpressionTreeSimplificationOperator.cs" />188 <Compile Include="SymbolicDataAnalysisModelComplexityCalculator.cs" />189 <Compile Include="Symbols\Wildcards\AnyNode.cs" />190 <Compile Include="Symbols\Wildcards\AnySubtreeSymbol.cs" />191 <Compile Include="Symbols\Wildcards\AnySubtree.cs" />192 <Compile Include="Symbols\Wildcards\AnyNodeSymbol.cs" />193 170 <Compile Include="Analyzers\SymbolicDataAnalysisSingleObjectivePruningAnalyzer.cs" /> 194 <Compile Include="Analyzers\SymbolicDataAnalysisGenealogyAnalyzer.cs" />195 171 <Compile Include="Analyzers\SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer.cs" /> 196 172 <Compile Include="Analyzers\SymbolicDataAnalysisSingleObjectiveTrainingParetoBestSolutionAnalyzer.cs" /> … … 206 182 <SubType>Code</SubType> 207 183 </Compile> 184 <Compile Include="Converters\Convert.cs" /> 185 <Compile Include="Converters\LinearModelToTreeConverter.cs" /> 186 <Compile Include="Converters\TreeSimplifier.cs" /> 187 <Compile Include="Converters\TreeToAutoDiffTermConverter.cs" /> 208 188 <Compile Include="Formatters\InfixExpressionFormatter.cs" /> 189 <Compile Include="Formatters\SymbolicDataAnalysisExpressionMathematicaFormatter.cs" /> 190 <Compile Include="Formatters\SymbolicDataAnalysisExpressionCSharpFormatter.cs" /> 191 <Compile Include="Importer\InfixExpressionParser.cs" /> 209 192 <Compile Include="Importer\SymbolicExpressionImporter.cs" /> 210 193 <Compile Include="Importer\Token.cs" /> 211 194 <Compile Include="Interfaces\IModelBacktransformator.cs" /> 212 <Compile Include="Interfaces\ISymbolicDataAnalysisExpressionSimilarityCalculator.cs" /> 213 <Compile Include="SymbolicExpressionTreeBacktransformator.cs" /> 195 <Compile Include="Interfaces\IVariableTreeNode.cs" /> 196 <Compile Include="Interfaces\IVariableSymbol.cs" /> 197 <Compile Include="Interpreter\SymbolicDataAnalysisExpressionCompiledTreeInterpreter.cs" /> 198 <Compile Include="SymbolicDataAnalysisExpressionTreeSimplificationOperator.cs" /> 199 <Compile Include="SymbolicDataAnalysisModelComplexityCalculator.cs" /> 214 200 <Compile Include="SymbolicDataAnalysisExpressionPruningOperator.cs" /> 215 <Compile Include="SymbolicDataAnalysisSolutionPruningOptimizer.cs" />216 201 <Compile Include="Analyzers\SymbolicDataAnalysisVariableFrequencyAnalyzer.cs" /> 217 202 <Compile Include="Analyzers\SymbolicDataAnalysisAlleleFrequencyAnalyzer.cs" /> … … 255 240 <Compile Include="Interfaces\ISymbolicDataAnalysisAnalyzer.cs" /> 256 241 <Compile Include="SymbolicDataAnalysisSingleObjectiveProblem.cs" /> 257 <Compile Include="SymbolicDataAnalysisExpressionTreeSimplifier.cs" />258 242 <Compile Include="SymbolicDataAnalysisProblem.cs" /> 259 243 <Compile Include="SymbolicDataAnalysisSolutionImpactValuesCalculator.cs" /> … … 267 251 <Compile Include="Symbols\AiryB.cs" /> 268 252 <Compile Include="Symbols\Bessel.cs" /> 269 <Compile Include="Symbols\Passthrough.cs" /> 253 <Compile Include="Symbols\BinaryFactorVariable.cs" /> 254 <Compile Include="Symbols\BinaryFactorVariableTreeNode.cs" /> 255 <Compile Include="Symbols\FactorVariableTreeNode.cs" /> 256 <Compile Include="Symbols\FactorVariable.cs" /> 257 <Compile Include="Symbols\VariableBase.cs" /> 258 <Compile Include="Symbols\VariableTreeNodeBase.cs" /> 259 <Compile Include="Symbols\Wildcards\AnyNode.cs" /> 260 <Compile Include="Symbols\Wildcards\AnyNodeSymbol.cs" /> 261 <Compile Include="Symbols\Wildcards\AnySubtree.cs" /> 262 <Compile Include="Symbols\Wildcards\AnySubtreeSymbol.cs" /> 270 263 <Compile Include="Symbols\Xor.cs" /> 271 264 <Compile Include="Symbols\Erf.cs" /> … … 315 308 <Compile Include="Tracking\Analyzers\SymbolicDataAnalysisTraceOverlapAnalyzer.cs" /> 316 309 <Compile Include="Tracking\SchemaDiversification\DiversificationStatisticsOperator.cs" /> 310 <Compile Include="Tracking\SchemaDiversification\SchemaCreator.cs" /> 317 311 <Compile Include="Tracking\SchemaDiversification\SchemaEvaluator.cs" /> 318 <Compile Include="Tracking\SchemaDiversification\SchemaCreator.cs" />319 312 <Compile Include="Tracking\SchemaDiversification\SchemaUtil.cs" /> 320 313 <Compile Include="Tracking\SchemaDiversification\UpdateQualityOperator.cs" /> … … 324 317 <Compile Include="Tracking\SymbolicDataAnalysisExpressionBeforeManipulatorOperator.cs" /> 325 318 <Compile Include="Tracking\TraceCalculator.cs" /> 326 <Compile Include="TransformationToSymbolicTreeMapper.cs" /> 319 <Compile Include="Transformations\SymbolicExpressionTreeBacktransformator.cs" /> 320 <Compile Include="Transformations\TransformationToSymbolicTreeMapper.cs" /> 327 321 <Compile Include="TreeMatching\QueryMatch.cs" /> 328 322 <Compile Include="TreeMatching\SymbolicExpressionTreeBottomUpSimilarityCalculator.cs" /> … … 368 362 </ItemGroup> 369 363 <ItemGroup> 370 <ProjectReference Include="..\..\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views\3.4\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj">371 <Project>{423bd94f-963a-438e-ba45-3bb3d61cd03b}</Project>372 <Name>HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4</Name>373 <Private>False</Private>374 </ProjectReference>375 364 <ProjectReference Include="..\..\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding\3.4\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj"> 376 365 <Project>{06D4A186-9319-48A0-BADE-A2058D462EEA}</Project> … … 381 370 <Project>{1f75cea3-464f-4a6f-b2f0-04b9841ebc16}</Project> 382 371 <Name>HeuristicLab.EvolutionTracking-3.4</Name> 383 <Private>False</Private>384 372 </ProjectReference> 385 373 </ItemGroup> 386 <ItemGroup />387 374 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> 388 375 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Importer/InfixExpressionParser.cs
r14576 r14878 33 33 /// Parses mathematical expressions in infix form. E.g. x1 * (3.0 * x2 + x3) 34 34 /// Identifier format (functions or variables): '_' | letter { '_' | letter | digit } 35 /// Variables names can be set under quotes "" or '' because variable names might contain spaces. 35 /// Variables names and variable values can be set under quotes "" or '' because variable names might contain spaces. 36 /// Variable = ident | " ident " | ' ident ' 36 37 /// It is also possible to use functions e.g. log("x1") or real-valued constants e.g. 3.1415 . 37 38 /// Variable names are case sensitive. Function names are not case sensitive. 39 /// 40 /// 41 /// S = Expr EOF 42 /// Expr = ['-' | '+'] Term { '+' Term | '-' Term } 43 /// Term = Fact { '*' Fact | '/' Fact } 44 /// Fact = '(' Expr ')' 45 /// | 'LAG' '(' varId ',' ['+' | '-' ] number ')' 46 /// | funcId '(' ArgList ')' 47 /// | VarExpr | number 48 /// ArgList = Expr { ',' Expr } 49 /// VarExpr = varId OptFactorPart 50 /// OptFactorPart = [ ('=' varVal | '[' ['+' | '-' ] number {',' ['+' | '-' ] number } ']' ) ] 51 /// varId = ident | ' ident ' | " ident " 52 /// varVal = ident | ' ident ' | " ident " 53 /// ident = '_' | letter { '_' | letter | digit } 38 54 /// </summary> 39 55 public sealed class InfixExpressionParser { 40 private enum TokenType { Operator, Identifier, Number, LeftPar, RightPar, Comma, End, NA };56 private enum TokenType { Operator, Identifier, Number, LeftPar, RightPar, LeftBracket, RightBracket, Comma, Eq, End, NA }; 41 57 private class Token { 42 58 internal double doubleVal; … … 65 81 private Constant constant = new Constant(); 66 82 private Variable variable = new Variable(); 83 private BinaryFactorVariable binaryFactorVar = new BinaryFactorVariable(); 84 private FactorVariable factorVar = new FactorVariable(); 67 85 68 86 private ProgramRootSymbol programRootSymbol = new ProgramRootSymbol(); … … 150 168 && str[pos] != '/' 151 169 && str[pos] != ')' 170 && str[pos] != ']' 152 171 && str[pos] != ',') { 153 172 sb.Append(str[pos]); … … 214 233 pos++; 215 234 yield return new Token { TokenType = TokenType.RightPar, strVal = ")" }; 235 } else if (str[pos] == '[') { 236 pos++; 237 yield return new Token { TokenType = TokenType.LeftBracket, strVal = "[" }; 238 } else if (str[pos] == ']') { 239 pos++; 240 yield return new Token { TokenType = TokenType.RightBracket, strVal = "]" }; 241 } else if (str[pos] == '=') { 242 pos++; 243 yield return new Token { TokenType = TokenType.Eq, strVal = "=" }; 216 244 } else if (str[pos] == ',') { 217 245 pos++; … … 222 250 } 223 251 } 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 } 252 /// S = Expr EOF 230 253 private ISymbolicExpressionTreeNode ParseS(Queue<Token> tokens) { 231 254 var expr = ParseExpr(tokens); … … 237 260 return expr; 238 261 } 262 263 /// Expr = ['-' | '+'] Term { '+' Term | '-' Term } 239 264 private ISymbolicExpressionTreeNode ParseExpr(Queue<Token> tokens) { 240 265 var next = tokens.Peek(); … … 300 325 } 301 326 302 // Term= Fact { '*' Fact | '/' Fact }327 /// Term = Fact { '*' Fact | '/' Fact } 303 328 private ISymbolicExpressionTreeNode ParseTerm(Queue<Token> tokens) { 304 329 var factors = new List<ISymbolicExpressionTreeNode>(); … … 335 360 } 336 361 337 // Fact = '(' Expr ')' | 'LAG' '(' varId ',' ['+' | '-'] number ')' | funcId '(' ArgList ')' | varId | number 362 /// Fact = '(' Expr ')' 363 /// | 'LAG' '(' varId ',' ['+' | '-' ] number ')' 364 /// | funcId '(' ArgList ')' 365 /// | VarExpr | number 366 /// ArgList = Expr { ',' Expr } 367 /// VarExpr = varId OptFactorPart 368 /// OptFactorPart = [ ('=' varVal | '[' ['+' | '-' ] number {',' ['+' | '-' ] number } ']' ) ] 369 /// varId = ident | ' ident ' | " ident " 370 /// varVal = ident | ' ident ' | " ident " 371 /// ident = '_' | letter { '_' | letter | digit } 338 372 private ISymbolicExpressionTreeNode ParseFact(Queue<Token> tokens) { 339 373 var next = tokens.Peek(); … … 348 382 var idTok = tokens.Dequeue(); 349 383 if (tokens.Peek().TokenType == TokenType.LeftPar) { 350 // function identifier 384 // function identifier or LAG 351 385 var funcId = idTok.strVal.ToUpperInvariant(); 352 386 … … 394 428 } else { 395 429 // variable 396 var varNode = (VariableTreeNode)variable.CreateTreeNode(); 397 varNode.Weight = 1.0; 398 varNode.VariableName = idTok.strVal; 399 return varNode; 430 if (tokens.Peek().TokenType == TokenType.Eq) { 431 // binary factor 432 tokens.Dequeue(); // skip Eq 433 var valTok = tokens.Dequeue(); 434 if (valTok.TokenType != TokenType.Identifier) throw new ArgumentException("expected identifier"); 435 var binFactorNode = (BinaryFactorVariableTreeNode)binaryFactorVar.CreateTreeNode(); 436 binFactorNode.Weight = 1.0; 437 binFactorNode.VariableName = idTok.strVal; 438 binFactorNode.VariableValue = valTok.strVal; 439 return binFactorNode; 440 } else if (tokens.Peek().TokenType == TokenType.LeftBracket) { 441 // factor variable 442 var factorVariableNode = (FactorVariableTreeNode)factorVar.CreateTreeNode(); 443 factorVariableNode.VariableName = idTok.strVal; 444 445 tokens.Dequeue(); // skip [ 446 var weights = new List<double>(); 447 // at least one weight is necessary 448 var sign = 1.0; 449 if (tokens.Peek().TokenType == TokenType.Operator) { 450 var opToken = tokens.Dequeue(); 451 if (opToken.strVal == "+") sign = 1.0; 452 else if (opToken.strVal == "-") sign = -1.0; 453 else throw new ArgumentException(); 454 } 455 if (tokens.Peek().TokenType != TokenType.Number) throw new ArgumentException("number expected"); 456 var weightTok = tokens.Dequeue(); 457 weights.Add(sign * weightTok.doubleVal); 458 while (tokens.Peek().TokenType == TokenType.Comma) { 459 // skip comma 460 tokens.Dequeue(); 461 if (tokens.Peek().TokenType == TokenType.Operator) { 462 var opToken = tokens.Dequeue(); 463 if (opToken.strVal == "+") sign = 1.0; 464 else if (opToken.strVal == "-") sign = -1.0; 465 else throw new ArgumentException(); 466 } 467 weightTok = tokens.Dequeue(); 468 if (weightTok.TokenType != TokenType.Number) throw new ArgumentException("number expected"); 469 weights.Add(sign * weightTok.doubleVal); 470 } 471 var rightBracketToken = tokens.Dequeue(); 472 if (rightBracketToken.TokenType != TokenType.RightBracket) throw new ArgumentException("closing bracket ] expected"); 473 factorVariableNode.Weights = weights.ToArray(); 474 return factorVariableNode; 475 } else { 476 // variable 477 var varNode = (VariableTreeNode)variable.CreateTreeNode(); 478 varNode.Weight = 1.0; 479 varNode.VariableName = idTok.strVal; 480 return varNode; 481 } 400 482 } 401 483 } else if (next.TokenType == TokenType.Number) { -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Importer/SymbolicExpressionImporter.cs
r14576 r14878 45 45 {"POW", new Power()}, 46 46 {"ROOT", new Root()}, 47 {"SQR", new Square()}, 48 {"SQRT", new SquareRoot()}, 47 49 {"SIN",new Sine()}, 48 50 {"COS", new Cosine()}, … … 74 76 {"PROG", new ProgramRootSymbol()}, 75 77 {"MAIN", new StartSymbol()}, 78 {"FACTOR", new FactorVariable() }, 79 {"BINFACTOR", new BinaryFactorVariable()} 76 80 }; 77 81 … … 82 86 TimeLag timeLag = new TimeLag(); 83 87 Integral integral = new Integral(); 88 FactorVariable factorVar = new FactorVariable(); 89 BinaryFactorVariable binFactorVar = new BinaryFactorVariable(); 84 90 85 91 ProgramRootSymbol programRootSymbol = new ProgramRootSymbol(); … … 136 142 tree.AddSubtree(ParseSexp(tokens)); 137 143 } 144 } else if (tokens.Peek().StringValue.StartsWith("FACTOR")) { 145 tree = ParseFactor(tokens); 146 } else if (tokens.Peek().StringValue.StartsWith("BINFACTOR")) { 147 tree = ParseBinaryFactor(tokens); 138 148 } else { 139 149 Token curToken = tokens.Dequeue(); … … 201 211 } 202 212 213 private ISymbolicExpressionTreeNode ParseFactor(Queue<Token> tokens) { 214 Token tok = tokens.Dequeue(); 215 Debug.Assert(tok.StringValue == "FACTOR"); 216 FactorVariableTreeNode t = (FactorVariableTreeNode)(new FactorVariable()).CreateTreeNode(); // create a new symbol each time on purpose 217 var varNameTok = tokens.Dequeue(); 218 Debug.Assert(tok.Symbol == TokenSymbol.SYMB); 219 t.VariableName = varNameTok.StringValue; 220 221 var weights = new List<double>(); 222 while (tokens.Peek().Symbol == TokenSymbol.NUMBER) { 223 weights.Add(tokens.Dequeue().DoubleValue); 224 } 225 226 t.Weights = weights.ToArray(); 227 228 // create a set of (virtual) values to match the number of weights 229 t.Symbol.VariableNames = new string[] { t.VariableName }; 230 t.Symbol.VariableValues = new[] 231 { new KeyValuePair<string, Dictionary<string,int>>( 232 t.VariableName, 233 weights.Select((_, i) => Tuple.Create(_,i)).ToDictionary(tup=>"X" + tup.Item2, tup=>tup.Item2)) }; 234 return t; 235 } 236 237 private ISymbolicExpressionTreeNode ParseBinaryFactor(Queue<Token> tokens) { 238 Token tok = tokens.Dequeue(); 239 Debug.Assert(tok.StringValue == "BINFACTOR"); 240 var t = (BinaryFactorVariableTreeNode)binFactorVar.CreateTreeNode(); 241 var varNameTok = tokens.Dequeue(); 242 Debug.Assert(varNameTok.Symbol == TokenSymbol.SYMB); 243 t.VariableName = varNameTok.StringValue; 244 245 var varValTok = tokens.Dequeue(); 246 Debug.Assert(varValTok.Symbol == TokenSymbol.SYMB); 247 t.VariableValue = varValTok.StringValue; 248 249 var weightTok = tokens.Dequeue(); 250 Debug.Assert(weightTok.Symbol == TokenSymbol.NUMBER); 251 t.Weight = weightTok.DoubleValue; 252 253 return t; 254 } 255 256 203 257 private ISymbolicExpressionTreeNode ParseLaggedVariable(Queue<Token> tokens) { 204 258 Token varTok = tokens.Dequeue(); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interfaces/ISymbolicDataAnalysisImpactValuesCalculator.cs
r12891 r14878 5 5 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { 6 6 public interface ISymbolicDataAnalysisSolutionImpactValuesCalculator : IItem { 7 double CalculateReplacementValue(ISymbolicDataAnalysisModel model, ISymbolicExpressionTreeNode node, IDataAnalysisProblemData problemData, IEnumerable<int> rows);8 double CalculateImpactValue(ISymbolicDataAnalysisModel model, ISymbolicExpressionTreeNode node, IDataAnalysisProblemData problemData, IEnumerable<int> rows, double qualityForImpactsCalculation = double.NaN);9 7 void CalculateImpactAndReplacementValues(ISymbolicDataAnalysisModel model, ISymbolicExpressionTreeNode node, IDataAnalysisProblemData problemData, 10 8 IEnumerable<int> rows, out double impactValue, out double replacementValue, out double newQualityForImpactsCalculation, double qualityForImpactsCalculation = double.NaN); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/OpCodes.cs
r14312 r14878 23 23 using System.Collections.Generic; 24 24 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 25 using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;26 25 27 26 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { … … 84 83 public const byte Erf = 43; 85 84 public const byte Bessel = 44; 86 public const byte Passthrough = 45; 85 public const byte FactorVariable = 46; 86 public const byte BinaryFactorVariable = 47; 87 87 88 88 89 private static Dictionary<Type, byte> symbolToOpcode = new Dictionary<Type, byte>() { … … 133 134 { typeof(Erf), OpCodes.Erf}, 134 135 { typeof(Bessel), OpCodes.Bessel}, 135 { typeof(Passthrough), OpCodes.Passthrough} 136 { typeof(FactorVariable), OpCodes.FactorVariable }, 137 { typeof(BinaryFactorVariable), OpCodes.BinaryFactorVariable } 136 138 }; 137 139 -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeILEmittingInterpreter.cs
r14312 r14878 66 66 private static MethodInfo erf = thisType.GetMethod("Erf", new Type[] { typeof(double) }); 67 67 private static MethodInfo bessel = thisType.GetMethod("Bessel", new Type[] { typeof(double) }); 68 private static MethodInfo string_eq = typeof(string).GetMethod("Equals", new Type[] { typeof(string) }); 68 69 #endregion 69 70 … … 259 260 il.Emit(System.Reflection.Emit.OpCodes.Add); 260 261 } 261 il.Emit(System.Reflection.Emit.OpCodes.Ldc_ I4,nArgs);262 il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, (double)nArgs); 262 263 il.Emit(System.Reflection.Emit.OpCodes.Div); 263 264 return; … … 457 458 il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // > 0 458 459 il.Emit(System.Reflection.Emit.OpCodes.Cgt); 460 il.Emit(System.Reflection.Emit.OpCodes.Conv_R8); // convert to float64 459 461 il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2 460 462 il.Emit(System.Reflection.Emit.OpCodes.Mul); … … 475 477 il.Emit(System.Reflection.Emit.OpCodes.Xor); 476 478 } 479 il.Emit(System.Reflection.Emit.OpCodes.Conv_R8); // convert to float64 480 477 481 il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2 478 482 il.Emit(System.Reflection.Emit.OpCodes.Mul); … … 486 490 487 491 il.Emit(System.Reflection.Emit.OpCodes.Cgt); // 1 (>) / 0 (otherwise) 492 il.Emit(System.Reflection.Emit.OpCodes.Conv_R8); // convert to float64 488 493 il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2 489 494 il.Emit(System.Reflection.Emit.OpCodes.Mul); … … 496 501 CompileInstructions(il, state, ds); 497 502 il.Emit(System.Reflection.Emit.OpCodes.Clt); 503 il.Emit(System.Reflection.Emit.OpCodes.Conv_R8); // convert to float64 498 504 il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2 499 505 il.Emit(System.Reflection.Emit.OpCodes.Mul); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeInterpreter.cs
r14576 r14878 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Linq; 24 25 using HeuristicLab.Common; 25 26 using HeuristicLab.Core; … … 143 144 var variableTreeNode = (VariableTreeNode)instr.dynamicNode; 144 145 instr.data = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName); 146 } else if (instr.opCode == OpCodes.FactorVariable) { 147 var factorTreeNode = instr.dynamicNode as FactorVariableTreeNode; 148 instr.data = dataset.GetReadOnlyStringValues(factorTreeNode.VariableName); 149 } else if (instr.opCode == OpCodes.BinaryFactorVariable) { 150 var factorTreeNode = instr.dynamicNode as BinaryFactorVariableTreeNode; 151 instr.data = dataset.GetReadOnlyStringValues(factorTreeNode.VariableName); 145 152 } else if (instr.opCode == OpCodes.LagVariable) { 146 153 var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode; … … 455 462 return ((IList<double>)currentInstr.data)[row] * variableTreeNode.Weight; 456 463 } 464 case OpCodes.BinaryFactorVariable: { 465 if (row < 0 || row >= dataset.Rows) return double.NaN; 466 var factorVarTreeNode = currentInstr.dynamicNode as BinaryFactorVariableTreeNode; 467 return ((IList<string>)currentInstr.data)[row] == factorVarTreeNode.VariableValue ? factorVarTreeNode.Weight : 0; 468 } 469 case OpCodes.FactorVariable: { 470 if (row < 0 || row >= dataset.Rows) return double.NaN; 471 var factorVarTreeNode = currentInstr.dynamicNode as FactorVariableTreeNode; 472 return factorVarTreeNode.GetValue(((IList<string>)currentInstr.data)[row]); 473 } 457 474 case OpCodes.LagVariable: { 458 475 var laggedVariableTreeNode = (LaggedVariableTreeNode)currentInstr.dynamicNode; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs
r14576 r14878 156 156 var variableTreeNode = (VariableTreeNode)instr.dynamicNode; 157 157 instr.value = ((IList<double>)instr.data)[row] * variableTreeNode.Weight; 158 } 159 } else if (instr.opCode == OpCodes.BinaryFactorVariable) { 160 if (row < 0 || row >= dataset.Rows) instr.value = double.NaN; 161 else { 162 var factorTreeNode = instr.dynamicNode as BinaryFactorVariableTreeNode; 163 instr.value = ((IList<string>)instr.data)[row] == factorTreeNode.VariableValue ? factorTreeNode.Weight : 0; 164 } 165 } else if (instr.opCode == OpCodes.FactorVariable) { 166 if (row < 0 || row >= dataset.Rows) instr.value = double.NaN; 167 else { 168 var factorTreeNode = instr.dynamicNode as FactorVariableTreeNode; 169 instr.value = factorTreeNode.GetValue(((IList<string>)instr.data)[row]); 158 170 } 159 171 } else if (instr.opCode == OpCodes.LagVariable) { … … 371 383 state.Reset(); 372 384 instr.value = interpreter.Evaluate(dataset, ref row, state); 373 } else if (instr.opCode == OpCodes.Passthrough) {374 instr.value = code[instr.childIndex].value;375 385 } else { 376 386 var errorText = string.Format("The {0} symbol is not supported by the linear interpreter. To support this symbol, please use the SymbolicDataAnalysisExpressionTreeInterpreter.", instr.dynamicNode.Symbol.Name); … … 412 422 } 413 423 break; 424 case OpCodes.BinaryFactorVariable: { 425 var factorVariableTreeNode = instr.dynamicNode as BinaryFactorVariableTreeNode; 426 instr.data = dataset.GetReadOnlyStringValues(factorVariableTreeNode.VariableName); 427 } 428 break; 429 case OpCodes.FactorVariable: { 430 var factorVariableTreeNode = instr.dynamicNode as FactorVariableTreeNode; 431 instr.data = dataset.GetReadOnlyStringValues(factorVariableTreeNode.VariableName); 432 } 433 break; 414 434 case OpCodes.LagVariable: { 415 435 var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Plugin.cs.frame
r14312 r14878 29 29 [PluginFile("HeuristicLab.Problems.DataAnalysis.Symbolic-3.4.dll", PluginFileType.Assembly)] 30 30 [PluginDependency("HeuristicLab.ALGLIB", "3.7.0")] 31 [PluginDependency("HeuristicLab.AutoDiff", "1.0")] 31 32 [PluginDependency("HeuristicLab.Analysis", "3.3")] 32 33 [PluginDependency("HeuristicLab.Collections", "3.3")] -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeSimplificationOperator.cs
r14312 r14878 37 37 } 38 38 39 private readonly SymbolicDataAnalysisExpressionTreeSimplifier simplifier = new SymbolicDataAnalysisExpressionTreeSimplifier();39 private readonly TreeSimplifier simplifier = new TreeSimplifier(); 40 40 41 41 [StorableConstructor] -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisModel.cs
r14312 r14878 63 63 var variables = 64 64 SymbolicExpressionTree.IterateNodesPrefix() 65 .OfType< VariableTreeNode>()65 .OfType<IVariableTreeNode>() 66 66 .Select(x => x.VariableName) 67 67 .Distinct(); 68 var variableConditions = SymbolicExpressionTree.IterateNodesPrefix()69 .OfType<VariableConditionTreeNode>().Select(x => x.VariableName).Distinct();70 68 71 return variables. Union(variableConditions).OrderBy(x => x);69 return variables.OrderBy(x => x); 72 70 } 73 71 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisModelComplexityCalculator.cs
r14312 r14878 39 39 return 1; 40 40 } 41 case OpCodes.Variable: { 41 case OpCodes.Variable: 42 case OpCodes.BinaryFactorVariable: 43 case OpCodes.FactorVariable: { 42 44 return 2; 43 45 } 44 case OpCodes.Add: 46 case OpCodes.Add: 45 47 case OpCodes.Sub: { 46 48 double complexity = 0; … … 50 52 return complexity; 51 53 } 52 case OpCodes.Mul: 54 case OpCodes.Mul: 53 55 case OpCodes.Div: { 54 56 double complexity = 1; … … 60 62 } 61 63 case OpCodes.Sin: 62 case OpCodes.Cos: 64 case OpCodes.Cos: 63 65 case OpCodes.Tan: 64 case OpCodes.Exp: 66 case OpCodes.Exp: 65 67 case OpCodes.Log: { 66 68 double complexity = CalculateComplexity(node.GetSubtree(0)); … … 75 77 return complexity * complexity * complexity; 76 78 } 77 case OpCodes.Power: 79 case OpCodes.Power: 78 80 case OpCodes.Root: { 79 81 double complexity = CalculateComplexity(node.GetSubtree(0)); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisProblem.cs
r14312 r14878 208 208 209 209 protected virtual void UpdateGrammar() { 210 SymbolicExpressionTreeGrammar.MaximumFunctionArguments = MaximumFunctionArguments.Value; 211 SymbolicExpressionTreeGrammar.MaximumFunctionDefinitions = MaximumFunctionDefinitions.Value; 212 foreach (var varSymbol in SymbolicExpressionTreeGrammar.Symbols.OfType<HeuristicLab.Problems.DataAnalysis.Symbolic.Variable>()) { 210 var problemData = ProblemData; 211 var ds = problemData.Dataset; 212 var grammar = SymbolicExpressionTreeGrammar; 213 grammar.MaximumFunctionArguments = MaximumFunctionArguments.Value; 214 grammar.MaximumFunctionDefinitions = MaximumFunctionDefinitions.Value; 215 foreach (var varSymbol in grammar.Symbols.OfType<HeuristicLab.Problems.DataAnalysis.Symbolic.VariableBase>()) { 213 216 if (!varSymbol.Fixed) { 214 varSymbol.AllVariableNames = ProblemData.InputVariables.Select(x => x.Value);215 varSymbol.VariableNames = ProblemData.AllowedInputVariables;217 varSymbol.AllVariableNames = problemData.InputVariables.Select(x => x.Value).Where(x => ds.VariableHasType<double>(x)); 218 varSymbol.VariableNames = problemData.AllowedInputVariables.Where(x => ds.VariableHasType<double>(x)); 216 219 } 217 220 } 218 foreach (var varSymbol in SymbolicExpressionTreeGrammar.Symbols.OfType<HeuristicLab.Problems.DataAnalysis.Symbolic.VariableCondition>()) { 219 if (!varSymbol.Fixed) { 220 varSymbol.AllVariableNames = ProblemData.InputVariables.Select(x => x.Value); 221 varSymbol.VariableNames = ProblemData.AllowedInputVariables; 221 foreach (var factorSymbol in grammar.Symbols.OfType<BinaryFactorVariable>()) { 222 if (!factorSymbol.Fixed) { 223 factorSymbol.AllVariableNames = problemData.InputVariables.Select(x => x.Value).Where(x => ds.VariableHasType<string>(x)); 224 factorSymbol.VariableNames = problemData.AllowedInputVariables.Where(x => ds.VariableHasType<string>(x)); 225 factorSymbol.VariableValues = factorSymbol.VariableNames 226 .ToDictionary(varName => varName, varName => ds.GetStringValues(varName).Distinct().ToList()); 227 } 228 } 229 foreach (var factorSymbol in grammar.Symbols.OfType<FactorVariable>()) { 230 if (!factorSymbol.Fixed) { 231 factorSymbol.AllVariableNames = problemData.InputVariables.Select(x => x.Value).Where(x => ds.VariableHasType<string>(x)); 232 factorSymbol.VariableNames = problemData.AllowedInputVariables.Where(x => ds.VariableHasType<string>(x)); 233 factorSymbol.VariableValues = factorSymbol.VariableNames 234 .ToDictionary(varName => varName, 235 varName => ds.GetStringValues(varName).Distinct() 236 .Select((n, i) => Tuple.Create(n, i)) 237 .ToDictionary(tup => tup.Item1, tup => tup.Item2)); 222 238 } 223 239 } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisSingleObjectiveProblem.cs
r14312 r14878 73 73 } 74 74 75 p ublicSymbolicDataAnalysisSingleObjectiveProblem(T problemData, U evaluator, V solutionCreator)75 protected SymbolicDataAnalysisSingleObjectiveProblem(T problemData, U evaluator, V solutionCreator) 76 76 : base(problemData, evaluator, solutionCreator) { 77 77 Parameters.Add(new FixedValueParameter<BoolValue>(MaximizationParameterName, "Set to false if the problem should be minimized.")); -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisSolutionImpactValuesCalculator.cs
r14312 r14878 21 21 22 22 using System.Collections.Generic; 23 using System.Linq; 23 24 using HeuristicLab.Common; 24 25 using HeuristicLab.Core; … … 36 37 [StorableConstructor] 37 38 protected SymbolicDataAnalysisSolutionImpactValuesCalculator(bool deserializing) : base(deserializing) { } 38 public abstract double CalculateReplacementValue(ISymbolicDataAnalysisModel model, ISymbolicExpressionTreeNode node, IDataAnalysisProblemData problemData, IEnumerable<int> rows);39 public abstract double CalculateImpactValue(ISymbolicDataAnalysisModel model, ISymbolicExpressionTreeNode node, IDataAnalysisProblemData problemData, IEnumerable<int> rows, double qualityForImpactsCalculation = double.NaN);40 39 public abstract void CalculateImpactAndReplacementValues(ISymbolicDataAnalysisModel model, ISymbolicExpressionTreeNode node, IDataAnalysisProblemData problemData, IEnumerable<int> rows, out double impactValue, out double replacementValue, out double newQualityForImpactsCalculation, double qualityForImpactsCalculation = double.NaN); 41 40 42 protected static double CalculateReplacementValue(ISymbolicExpressionTreeNode node, ISymbolicExpressionTree sourceTree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,41 protected IEnumerable<double> CalculateReplacementValues(ISymbolicExpressionTreeNode node, ISymbolicExpressionTree sourceTree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, 43 42 IDataset dataset, IEnumerable<int> rows) { 44 43 //optimization: constant nodes return always the same value 45 44 ConstantTreeNode constantNode = node as ConstantTreeNode; 46 if (constantNode != null) return constantNode.Value; 45 BinaryFactorVariableTreeNode binaryFactorNode = node as BinaryFactorVariableTreeNode; 46 FactorVariableTreeNode factorNode = node as FactorVariableTreeNode; 47 if (constantNode != null) { 48 yield return constantNode.Value; 49 } else if (binaryFactorNode != null) { 50 // valid replacements are either all off or all on 51 yield return 0; 52 yield return 1; 53 } else if (factorNode != null) { 54 foreach (var w in factorNode.Weights) yield return w; 55 yield return 0.0; 56 } else { 57 var rootSymbol = new ProgramRootSymbol().CreateTreeNode(); 58 var startSymbol = new StartSymbol().CreateTreeNode(); 59 rootSymbol.AddSubtree(startSymbol); 60 startSymbol.AddSubtree((ISymbolicExpressionTreeNode)node.Clone()); 47 61 48 var rootSymbol = new ProgramRootSymbol().CreateTreeNode(); 49 var startSymbol = new StartSymbol().CreateTreeNode(); 50 rootSymbol.AddSubtree(startSymbol); 51 startSymbol.AddSubtree((ISymbolicExpressionTreeNode)node.Clone()); 52 53 var tempTree = new SymbolicExpressionTree(rootSymbol); 54 // clone ADFs of source tree 55 for (int i = 1; i < sourceTree.Root.SubtreeCount; i++) { 56 tempTree.Root.AddSubtree((ISymbolicExpressionTreeNode)sourceTree.Root.GetSubtree(i).Clone()); 62 var tempTree = new SymbolicExpressionTree(rootSymbol); 63 // clone ADFs of source tree 64 for (int i = 1; i < sourceTree.Root.SubtreeCount; i++) { 65 tempTree.Root.AddSubtree((ISymbolicExpressionTreeNode)sourceTree.Root.GetSubtree(i).Clone()); 66 } 67 yield return interpreter.GetSymbolicExpressionTreeValues(tempTree, dataset, rows).Median(); 68 yield return interpreter.GetSymbolicExpressionTreeValues(tempTree, dataset, rows).Average(); // TODO perf 57 69 } 58 return interpreter.GetSymbolicExpressionTreeValues(tempTree, dataset, rows).Median();59 70 } 60 71 -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/LaggedVariable.cs
r14312 r14878 27 27 [StorableClass] 28 28 [Item("LaggedVariable", "Represents a variable value with a time offset.")] 29 public class LaggedVariable : Variable {29 public class LaggedVariable : VariableBase { 30 30 [Storable] 31 31 private int minLag; -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/LaggedVariableTreeNode.cs
r14312 r14878 26 26 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { 27 27 [StorableClass] 28 public sealed class LaggedVariableTreeNode : VariableTreeNode , ILaggedTreeNode {28 public sealed class LaggedVariableTreeNode : VariableTreeNodeBase, ILaggedTreeNode { 29 29 public new LaggedVariable Symbol { 30 30 get { return (LaggedVariable)base.Symbol; } -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/Variable.cs
r14312 r14878 20 20 #endregion 21 21 22 using System;23 using System.Collections.Generic;24 22 using HeuristicLab.Common; 25 23 using HeuristicLab.Core; … … 29 27 [StorableClass] 30 28 [Item("Variable", "Represents a variable value.")] 31 public class Variable : Symbol { 32 #region Properties 33 [Storable] 34 private double weightMu; 35 public double WeightMu { 36 get { return weightMu; } 37 set { 38 if (value != weightMu) { 39 weightMu = value; 40 OnChanged(EventArgs.Empty); 41 } 42 } 43 } 44 [Storable] 45 private double weightSigma; 46 public double WeightSigma { 47 get { return weightSigma; } 48 set { 49 if (weightSigma < 0.0) throw new ArgumentException("Negative sigma is not allowed."); 50 if (value != weightSigma) { 51 weightSigma = value; 52 OnChanged(EventArgs.Empty); 53 } 54 } 55 } 56 [Storable] 57 private double weightManipulatorMu; 58 public double WeightManipulatorMu { 59 get { return weightManipulatorMu; } 60 set { 61 if (value != weightManipulatorMu) { 62 weightManipulatorMu = value; 63 OnChanged(EventArgs.Empty); 64 } 65 } 66 } 67 [Storable] 68 private double weightManipulatorSigma; 69 public double WeightManipulatorSigma { 70 get { return weightManipulatorSigma; } 71 set { 72 if (weightManipulatorSigma < 0.0) throw new ArgumentException("Negative sigma is not allowed."); 73 if (value != weightManipulatorSigma) { 74 weightManipulatorSigma = value; 75 OnChanged(EventArgs.Empty); 76 } 77 } 78 } 79 [Storable(DefaultValue = 0.0)] 80 private double multiplicativeWeightManipulatorSigma; 81 public double MultiplicativeWeightManipulatorSigma { 82 get { return multiplicativeWeightManipulatorSigma; } 83 set { 84 if (multiplicativeWeightManipulatorSigma < 0.0) throw new ArgumentException("Negative sigma is not allowed."); 85 if (value != multiplicativeWeightManipulatorSigma) { 86 multiplicativeWeightManipulatorSigma = value; 87 OnChanged(EventArgs.Empty); 88 } 89 } 90 } 91 private List<string> variableNames; 92 [Storable] 93 public IEnumerable<string> VariableNames { 94 get { return variableNames; } 95 set { 96 if (value == null) throw new ArgumentNullException(); 97 variableNames.Clear(); 98 variableNames.AddRange(value); 99 OnChanged(EventArgs.Empty); 100 } 101 } 102 103 private List<string> allVariableNames; 104 [Storable] 105 public IEnumerable<string> AllVariableNames { 106 get { return allVariableNames; } 107 set { 108 if (value == null) throw new ArgumentNullException(); 109 allVariableNames.Clear(); 110 allVariableNames.AddRange(value); 111 } 112 } 113 114 public override bool Enabled { 115 get { 116 if (variableNames.Count == 0) return false; 117 return base.Enabled; 118 } 119 set { 120 if (variableNames.Count == 0) base.Enabled = false; 121 else base.Enabled = value; 122 } 123 } 124 125 private const int minimumArity = 0; 126 private const int maximumArity = 0; 127 128 public override int MinimumArity { 129 get { return minimumArity; } 130 } 131 public override int MaximumArity { 132 get { return maximumArity; } 133 } 134 #endregion 135 136 [StorableHook(HookType.AfterDeserialization)] 137 private void AfterDeserialization() { 138 if (allVariableNames == null || (allVariableNames.Count == 0 && variableNames.Count > 0)) { 139 allVariableNames = variableNames; 140 } 141 } 29 public sealed class Variable : VariableBase { 142 30 143 31 [StorableConstructor] 144 pr otectedVariable(bool deserializing)32 private Variable(bool deserializing) 145 33 : base(deserializing) { 146 variableNames = new List<string>();147 allVariableNames = new List<string>();148 34 } 149 pr otectedVariable(Variable original, Cloner cloner)35 private Variable(Variable original, Cloner cloner) 150 36 : base(original, cloner) { 151 weightMu = original.weightMu;152 weightSigma = original.weightSigma;153 variableNames = new List<string>(original.variableNames);154 allVariableNames = new List<string>(original.allVariableNames);155 weightManipulatorMu = original.weightManipulatorMu;156 weightManipulatorSigma = original.weightManipulatorSigma;157 multiplicativeWeightManipulatorSigma = original.multiplicativeWeightManipulatorSigma;158 37 } 159 public Variable() : this("Variable", "Represents a variable value.") { } 160 public Variable(string name, string description) 161 : base(name, description) { 162 weightMu = 1.0; 163 weightSigma = 1.0; 164 weightManipulatorMu = 0.0; 165 weightManipulatorSigma = 0.05; 166 multiplicativeWeightManipulatorSigma = 0.03; 167 variableNames = new List<string>(); 168 allVariableNames = new List<string>(); 169 } 38 public Variable() : base("Variable", "Represents a variable value.") { } 39 public Variable(string name, string description) : base(name, description) { } 170 40 171 41 public override ISymbolicExpressionTreeNode CreateTreeNode() { -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/VariableCondition.cs
r14576 r14878 30 30 [StorableClass] 31 31 [Item("Variable Condition", "Represents a condition that tests a given variable against a specified threshold.")] 32 public sealed class VariableCondition : Symbol {32 public sealed class VariableCondition : Symbol, IVariableSymbol { 33 33 #region properties 34 34 [Storable] -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/VariableConditionTreeNode.cs
r14576 r14878 29 29 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { 30 30 [StorableClass] 31 public sealed class VariableConditionTreeNode : SymbolicExpressionTreeNode {31 public sealed class VariableConditionTreeNode : SymbolicExpressionTreeNode, IVariableTreeNode { 32 32 #region properties 33 33 public new VariableCondition Symbol { -
branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/VariableTreeNode.cs
r14312 r14878 21 21 22 22 using HeuristicLab.Common; 23 using HeuristicLab.Core;24 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;25 23 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 26 using HeuristicLab.Random;27 24 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { 28 25 [StorableClass] 29 public class VariableTreeNode : SymbolicExpressionTreeTerminalNode {26 public sealed class VariableTreeNode : VariableTreeNodeBase { 30 27 public new Variable Symbol { 31 28 get { return (Variable)base.Symbol; } 32 29 } 33 [Storable] 34 private double weight; 35 public double Weight { 36 get { return weight; } 37 set { weight = value; } 30 [StorableConstructor] 31 private VariableTreeNode(bool deserializing) : base(deserializing) { } 32 private VariableTreeNode(VariableTreeNode original, Cloner cloner) 33 : base(original, cloner) { 38 34 } 39 [Storable] 40 private string variableName; 41 public string VariableName { 42 get { return variableName; } 43 set { variableName = value; } 44 } 45 46 [StorableConstructor] 47 protected VariableTreeNode(bool deserializing) : base(deserializing) { } 48 protected VariableTreeNode(VariableTreeNode original, Cloner cloner) 49 : base(original, cloner) { 50 weight = original.weight; 51 variableName = original.variableName; 52 } 53 protected VariableTreeNode() { } 35 private VariableTreeNode() { } 54 36 public VariableTreeNode(Variable variableSymbol) : base(variableSymbol) { } 55 56 public override bool HasLocalParameters {57 get { return true; }58 }59 60 public override void ResetLocalParameters(IRandom random) {61 base.ResetLocalParameters(random);62 weight = NormalDistributedRandom.NextDouble(random, Symbol.WeightMu, Symbol.WeightSigma);63 64 #pragma warning disable 612, 61865 variableName = Symbol.VariableNames.SelectRandom(random);66 #pragma warning restore 612, 61867 }68 69 public override void ShakeLocalParameters(IRandom random, double shakingFactor) {70 base.ShakeLocalParameters(random, shakingFactor);71 // 50% additive & 50% multiplicative72 if (random.NextDouble() < 0) {73 double x = NormalDistributedRandom.NextDouble(random, Symbol.WeightManipulatorMu, Symbol.WeightManipulatorSigma);74 weight = weight + x * shakingFactor;75 } else {76 double x = NormalDistributedRandom.NextDouble(random, 1.0, Symbol.MultiplicativeWeightManipulatorSigma);77 weight = weight * x;78 }79 #pragma warning disable 612, 61880 variableName = Symbol.VariableNames.SelectRandom(random);81 #pragma warning restore 612, 61882 }83 37 84 38 public override IDeepCloneable Clone(Cloner cloner) { 85 39 return new VariableTreeNode(this, cloner); 86 40 } 87 88 public override string ToString() {89 if (weight.IsAlmost(1.0)) return variableName;90 else return weight.ToString("E4") + " " + variableName;91 }92 41 } 93 42 } -
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
/branches/symbreg-factors-2650/HeuristicLab.Problems.TravelingSalesman.Views (added) merged: 14497,14499,14591-14592 /trunk/sources/HeuristicLab.Problems.TravelingSalesman.Views merged: 14826
- Property svn:mergeinfo changed
Note: See TracChangeset
for help on using the changeset viewer.