Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RegressionBenchmarks/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs @ 7085

Last change on this file since 7085 was 7085, checked in by sforsten, 12 years ago

#1669: branch has been merged with the trunk in revision 7081 and methods in RegressionBenchmark have been renamed.

File size: 12.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
34  /// <summary>
35  /// An operator that tracks tree lengths of Symbolic Expression Trees
36  /// </summary>
37  [Item("SymbolicExpressionTreeLengthAnalyzer", "An operator that tracks tree lengths of Symbolic Expression Trees")]
38  [StorableClass]
39  public sealed class SymbolicExpressionTreeLengthAnalyzer : SingleSuccessorOperator, ISymbolicExpressionTreeAnalyzer {
40    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
41    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
42    private const string SymbolicExpressionTreeLengthsParameterName = "SymbolicExpressionTreeLengthsTable";
43    private const string SymbolicExpressionTreeLengthsHistoryParameterName = "SymbolicExpressionTreeLengthsHistoryTable";
44    private const string ResultsParameterName = "Results";
45    private const string StoreHistoryParameterName = "StoreHistory";
46    private const string UpdateIntervalParameterName = "UpdateInterval";
47    private const string UpdateCounterParameterName = "UpdateCounter";
48
49    #region Parameter properties
50    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
51      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
52    }
53    public ValueLookupParameter<DataTable> SymbolicExpressionTreeLengthsParameter {
54      get {
55        return (ValueLookupParameter<DataTable>)Parameters[SymbolicExpressionTreeLengthsParameterName];
56      }
57    }
58    public ValueLookupParameter<DataTableHistory> SymbolicExpressionTreeLengthsHistoryParameter {
59      get {
60        return (ValueLookupParameter<DataTableHistory>)Parameters[SymbolicExpressionTreeLengthsHistoryParameterName];
61      }
62    }
63    public ValueLookupParameter<ResultCollection> ResultsParameter {
64      get { return (ValueLookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
65    }
66    // history
67    public ValueParameter<BoolValue> StoreHistoryParameter {
68      get { return (ValueParameter<BoolValue>)Parameters[StoreHistoryParameterName]; }
69    }
70    public ValueParameter<IntValue> UpdateIntervalParameter {
71      get { return (ValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
72    }
73    public LookupParameter<IntValue> UpdateCounterParameter {
74      get { return (LookupParameter<IntValue>)Parameters[UpdateCounterParameterName]; }
75    }
76    #endregion
77    [StorableConstructor]
78    private SymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base() { }
79    private SymbolicExpressionTreeLengthAnalyzer(SymbolicExpressionTreeLengthAnalyzer original, Cloner cloner)
80      : base(original, cloner) {
81      AfterDeserialization();
82    }
83    public override IDeepCloneable Clone(Cloner cloner) {
84      return new SymbolicExpressionTreeLengthAnalyzer(this, cloner);
85    }
86    public SymbolicExpressionTreeLengthAnalyzer()
87      : base() {
88      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression tree whose length should be calculated."));
89      Parameters.Add(new LookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximum allowed symbolic expression tree length"));
90      Parameters.Add(new ValueLookupParameter<DataTable>(SymbolicExpressionTreeLengthsParameterName, "The data table to store the symbolic expression tree lengths."));
91      Parameters.Add(new ValueLookupParameter<DataTableHistory>(SymbolicExpressionTreeLengthsHistoryParameterName, "The data table to store the symbolic expression tree lengths history."));
92      Parameters.Add(new ValueLookupParameter<ResultCollection>(ResultsParameterName, "The results collection where the analysis values should be stored."));
93
94      #region Add parameters for history
95      Parameters.Add(new ValueParameter<BoolValue>(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
96      Parameters.Add(new ValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
97      Parameters.Add(new LookupParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", "MinMaxAverageSymbolicExpressionTreeLengthAnalyzerUpdateCounter"));
98      #endregion
99
100      UpdateCounterParameter.Hidden = true;
101
102      AfterDeserialization();
103    }
104
105    [StorableHook(HookType.AfterDeserialization)]
106    private void AfterDeserialization() {
107      // check if all the parameters are present and accounted for
108      if (!Parameters.ContainsKey(StoreHistoryParameterName)) {
109        Parameters.Add(new ValueParameter<BoolValue>(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
110      }
111      if (!Parameters.ContainsKey(UpdateIntervalParameterName)) {
112        Parameters.Add(new ValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
113      }
114      if (!Parameters.ContainsKey(UpdateCounterParameterName)) {
115        Parameters.Add(new LookupParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", "MinMaxAverageSymbolicExpressionTreeLengthAnalyzerUpdateCounter"));
116      }
117    }
118
119    public override IOperation Apply() {
120      int updateInterval = UpdateIntervalParameter.Value.Value;
121      IntValue updateCounter = UpdateCounterParameter.ActualValue;
122      // if the counter doesn't exist yet, we initialize it here with the current update interval
123      if (updateCounter == null) {
124        updateCounter = new IntValue(updateInterval);
125        UpdateCounterParameter.ActualValue = updateCounter;
126      } else updateCounter.Value++;
127
128      // the analyzer runs periodically, every 'updateInterval' times
129      if (updateCounter.Value == updateInterval) {
130        updateCounter.Value = 0; // reset counter
131
132        // compute all tree lengths and store them in the lengthsTable
133        var solutions = SymbolicExpressionTreeParameter.ActualValue;
134
135        var treeLengthsTable = SymbolicExpressionTreeLengthsParameter.ActualValue;
136        // if the table was not created yet, we create it here
137        if (treeLengthsTable == null) {
138          treeLengthsTable = new DataTable("Tree Length Values");
139          SymbolicExpressionTreeLengthsParameter.ActualValue = treeLengthsTable;
140        }
141
142        // data table which stores tree length values
143        DataRow dataRow;
144
145        var treeLengths = solutions.Select(s => (double)s.Length);
146
147        if (!treeLengthsTable.Rows.ContainsKey("Tree Lengths")) {
148          dataRow = new DataRow("Tree Lengths", "", treeLengths);
149          treeLengthsTable.Rows.Add(dataRow);
150        } else {
151          dataRow = treeLengthsTable.Rows["Tree Lengths"];
152          dataRow.Values.Replace(treeLengths);
153        }
154
155        double maximumAllowedTreeLength = ((LookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]).ActualValue.Value;
156
157        dataRow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
158        dataRow.VisualProperties.ExactBins = false;
159
160        // the following trick should result in an intervalWidth of 1,2,4,... (an int value)
161        dataRow.VisualProperties.Bins = solutions.Max(s => s.Length) - solutions.Min(s => s.Length);
162
163        int maxLength = solutions.Max(s => s.Length);
164        if (maxLength <= 25)      // [0,25]
165          dataRow.VisualProperties.ScaleFactor = 1.0;
166        else if (maxLength <= 100) // [26,100])
167          dataRow.VisualProperties.ScaleFactor = 1.0 / 2.0;
168        else if (maxLength <= 250) // [100,250]
169          dataRow.VisualProperties.ScaleFactor = 1.0 / 5.0;
170        else if (maxLength <= 500) // [251,500]
171          dataRow.VisualProperties.ScaleFactor = 1.0 / 10.0;
172        else
173          dataRow.VisualProperties.ScaleFactor = 1.0 / 20.0;   // [501,inf]
174
175        // visual properties for the X-axis
176        treeLengthsTable.VisualProperties.XAxisMinimumAuto = false;
177        treeLengthsTable.VisualProperties.XAxisMaximumAuto = false;
178        treeLengthsTable.VisualProperties.XAxisMinimumFixedValue = 0.0;
179        if (maxLength > maximumAllowedTreeLength + 1)
180          treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = solutions.Max(s => s.Length) + 1; // +1 so the histogram column for the maximum length won't get trimmed
181        else
182          treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maximumAllowedTreeLength + 1;
183        // visual properties for the Y-axis
184        treeLengthsTable.VisualProperties.YAxisMinimumAuto = false;
185        treeLengthsTable.VisualProperties.YAxisMaximumAuto = false;
186        treeLengthsTable.VisualProperties.YAxisMinimumFixedValue = 0.0;
187        treeLengthsTable.VisualProperties.YAxisMaximumFixedValue = Math.Ceiling(solutions.Length / 2.0);
188
189        var results = ResultsParameter.ActualValue;
190
191        if (!results.ContainsKey("Tree Lengths")) {
192          results.Add(new Result("Tree Lengths", treeLengthsTable));
193        } else {
194          results["Tree Lengths"].Value = treeLengthsTable;
195        }
196
197        bool storeHistory = StoreHistoryParameter.Value.Value;
198
199        if (storeHistory) {
200          // store tree lengths for each generation
201          var historyDataRow = new DataRow("Tree Lengths " + results["Generations"].Value, "", dataRow.Values);
202          historyDataRow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
203          historyDataRow.VisualProperties.ExactBins = false;
204          historyDataRow.VisualProperties.Bins = solutions.Max(s => s.Length) - solutions.Min(s => s.Length);
205          historyDataRow.VisualProperties.ScaleFactor = dataRow.VisualProperties.ScaleFactor;
206          var historyTable = new DataTable("Lengths Table " + results["Generations"]);
207          historyTable.Rows.Add(historyDataRow);
208          // visual properties for the X-axis
209          historyTable.VisualProperties.XAxisMinimumAuto = false;
210          historyTable.VisualProperties.XAxisMaximumAuto = false;
211          historyTable.VisualProperties.XAxisMinimumFixedValue = 0.0;
212          if (solutions.Max(s => s.Length) > maximumAllowedTreeLength + 1)
213            historyTable.VisualProperties.XAxisMaximumFixedValue = maxLength + 1; // +1 so the histogram column for the maximum length won't get trimmed
214          else
215            historyTable.VisualProperties.XAxisMaximumFixedValue = maximumAllowedTreeLength + 1;
216          // visual properties for the Y-axis
217          historyTable.VisualProperties.YAxisMinimumAuto = false;
218          historyTable.VisualProperties.YAxisMaximumAuto = false;
219          historyTable.VisualProperties.YAxisMinimumFixedValue = 0.0;
220          historyTable.VisualProperties.YAxisMaximumFixedValue = Math.Ceiling(solutions.Length / 2.0);
221
222          var treeLengthsHistory = SymbolicExpressionTreeLengthsHistoryParameter.ActualValue;
223          if (treeLengthsHistory == null) {
224            treeLengthsHistory = new DataTableHistory();
225            SymbolicExpressionTreeLengthsHistoryParameter.ActualValue = treeLengthsHistory;
226          }
227
228          treeLengthsHistory.Add(historyTable);
229
230          if (!results.ContainsKey("Tree Lengths History")) {
231            results.Add(new Result("Tree Lengths History", treeLengthsHistory));
232          } else {
233            results["Tree Lengths History"].Value = treeLengthsHistory;
234          }
235        }
236      }
237
238      return base.Apply();
239    }
240  }
241}
Note: See TracBrowser for help on using the repository browser.