Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs @ 7223

Last change on this file since 7223 was 7223, checked in by bburlacu, 12 years ago

#1661: Fixed bug in the CalculateHistogram method inside the DataTableView, adjusted the way vertical scaling is performed in the SymbolicExpressionTreeLengthAnalyzer.

File size: 14.1 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.Linq;
23using HeuristicLab.Analysis;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using System;
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 { return (ValueLookupParameter<DataTable>)Parameters[SymbolicExpressionTreeLengthsParameterName]; }
55    }
56    public ValueLookupParameter<DataTableHistory> SymbolicExpressionTreeLengthsHistoryParameter {
57      get { return (ValueLookupParameter<DataTableHistory>)Parameters[SymbolicExpressionTreeLengthsHistoryParameterName]; }
58    }
59    public ValueLookupParameter<ResultCollection> ResultsParameter {
60      get { return (ValueLookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
61    }
62    // history
63    public ValueParameter<BoolValue> StoreHistoryParameter {
64      get { return (ValueParameter<BoolValue>)Parameters[StoreHistoryParameterName]; }
65    }
66    public ValueParameter<IntValue> UpdateIntervalParameter {
67      get { return (ValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
68    }
69    public ValueParameter<IntValue> UpdateCounterParameter {
70      get { return (ValueParameter<IntValue>)Parameters[UpdateCounterParameterName]; }
71    }
72    #endregion
73
74    #region Properties
75    public bool EnabledByDefault {
76      get { return true; }
77    }
78    public IntValue UpdateInterval {
79      get { return UpdateIntervalParameter.Value; }
80    }
81    public IntValue UpdateCounter {
82      get { return UpdateCounterParameter.Value; }
83    }
84    public BoolValue StoreHistory {
85      get { return StoreHistoryParameter.Value; }
86    }
87    #endregion
88
89    [StorableConstructor]
90    private SymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base() { }
91    private SymbolicExpressionTreeLengthAnalyzer(SymbolicExpressionTreeLengthAnalyzer original, Cloner cloner)
92      : base(original, cloner) {
93      AfterDeserialization();
94    }
95    public override IDeepCloneable Clone(Cloner cloner) {
96      return new SymbolicExpressionTreeLengthAnalyzer(this, cloner);
97    }
98    public SymbolicExpressionTreeLengthAnalyzer()
99      : base() {
100      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression tree whose length should be calculated."));
101      Parameters.Add(new LookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximum allowed symbolic expression tree length"));
102      Parameters.Add(new ValueLookupParameter<DataTable>(SymbolicExpressionTreeLengthsParameterName, "The data table to store the symbolic expression tree lengths."));
103      Parameters.Add(new ValueLookupParameter<DataTableHistory>(SymbolicExpressionTreeLengthsHistoryParameterName, "The data table to store the symbolic expression tree lengths history."));
104      Parameters.Add(new ValueLookupParameter<ResultCollection>(ResultsParameterName, "The results collection where the analysis values should be stored."));
105      Parameters.Add(new ValueParameter<BoolValue>(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
106      Parameters.Add(new ValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
107      Parameters.Add(new ValueParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", new IntValue(0)));
108
109      AfterDeserialization();
110    }
111
112    [StorableHook(HookType.AfterDeserialization)]
113    private void AfterDeserialization() {
114      // check if all the parameters are present and accounted for
115      if (!Parameters.ContainsKey(StoreHistoryParameterName)) {
116        Parameters.Add(new ValueParameter<BoolValue>(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
117      }
118      if (!Parameters.ContainsKey(UpdateIntervalParameterName)) {
119        Parameters.Add(new ValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
120      }
121      if (Parameters.ContainsKey(UpdateCounterParameterName))
122        Parameters.Remove(UpdateCounterParameterName);
123      Parameters.Add(new ValueParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", new IntValue(0)));
124
125      SymbolicExpressionTreeLengthsParameter.Hidden = true;
126      SymbolicExpressionTreeLengthsHistoryParameter.Hidden = true;
127      ResultsParameter.Hidden = true;
128      UpdateCounterParameter.Hidden = true;
129    }
130
131    public override IOperation Apply() {
132      UpdateCounter.Value++;
133      // the analyzer runs periodically, every 'updateInterval' times
134      if (UpdateCounter.Value == UpdateInterval.Value) {
135        UpdateCounter.Value = 0; // reset counter
136
137        // compute all tree lengths and store them in the lengthsTable
138        var solutions = SymbolicExpressionTreeParameter.ActualValue;
139
140        var treeLengthsTable = SymbolicExpressionTreeLengthsParameter.ActualValue;
141        // if the table was not created yet, we create it here
142        if (treeLengthsTable == null) {
143          treeLengthsTable = new DataTable("Histogram");
144          SymbolicExpressionTreeLengthsParameter.ActualValue = treeLengthsTable;
145        }
146
147        // data table which stores tree length values
148        DataRow treeLengthsTableRow;
149
150        const string treeLengthsTableRowName = "Symbolic expression tree lengths";
151        const string treeLengthsTableRowDesc = "The distribution of symbolic expression tree lengths";
152        const string xAxisTitle = "Symbolic expression tree lengths";
153        const string yAxisTitle = "Frequency / Number of tree individuals";
154
155        var treeLengths = solutions.Select(s => (int)s.Length).ToList();
156
157        int maxLength = treeLengths.Max(t => t);
158        int minLength = treeLengths.Min(t => t);
159
160        if (!treeLengthsTable.Rows.ContainsKey(treeLengthsTableRowName)) {
161          treeLengthsTableRow = new DataRow(treeLengthsTableRowName, treeLengthsTableRowDesc, treeLengths.Select(x => (double)x));
162          treeLengthsTable.Rows.Add(treeLengthsTableRow);
163        } else {
164          treeLengthsTableRow = treeLengthsTable.Rows[treeLengthsTableRowName];
165          treeLengthsTableRow.Values.Replace(treeLengths.Select(x => (double)x));
166        }
167
168        double maximumAllowedTreeLength = ((LookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]).ActualValue.Value;
169
170        treeLengthsTableRow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
171        treeLengthsTableRow.VisualProperties.ExactBins = false;
172
173        int range = maxLength - minLength;
174        if (range == 0) range = 1;
175        // the following trick should result in an integer intervalWidth of 1,2,4,...
176        treeLengthsTableRow.VisualProperties.Bins = range;
177
178        if (maxLength <= 25) // [0,25]
179          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0;
180        else if (maxLength <= 100) // [26,100]
181          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 2.0;
182        else if (maxLength <= 250) // [101,250]
183          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 5.0;
184        else if (maxLength <= 500) // [251,500]
185          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 10.0;
186        else
187          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 20.0; // [501,inf]
188
189        treeLengthsTableRow.VisualProperties.IsVisibleInLegend = false;
190
191        // visual properties for the X-axis
192        treeLengthsTable.VisualProperties.XAxisMinimumAuto = false;
193        treeLengthsTable.VisualProperties.XAxisMaximumAuto = false;
194        treeLengthsTable.VisualProperties.XAxisMinimumFixedValue = 0.0;
195        if (maxLength > maximumAllowedTreeLength + 1)
196          treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maxLength + 1; // +1 so the histogram column for the maximum length won't get trimmed
197        else
198          treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maximumAllowedTreeLength + 1;
199        treeLengthsTable.VisualProperties.XAxisTitle = xAxisTitle;
200        //visual properties for the Y-axis
201        treeLengthsTable.VisualProperties.YAxisMinimumAuto = false;
202        treeLengthsTable.VisualProperties.YAxisMaximumAuto = false;
203        treeLengthsTable.VisualProperties.YAxisMinimumFixedValue = 0.0;
204        int maxFreq = (int)Math.Round(solutions.GroupBy(s => s.Length).Max(g => g.Count()) / treeLengthsTableRow.VisualProperties.ScaleFactor);
205        if (maxFreq % 5 != 0)
206          maxFreq += (5 - maxFreq % 5);
207        double yAxisMaximumFixedValue = maxFreq;
208
209        treeLengthsTable.VisualProperties.YAxisMaximumFixedValue = yAxisMaximumFixedValue;
210        treeLengthsTable.VisualProperties.YAxisTitle = yAxisTitle;
211
212        var results = ResultsParameter.ActualValue;
213
214        if (!results.ContainsKey(treeLengthsTableRowName)) {
215          results.Add(new Result(treeLengthsTableRowName, treeLengthsTable));
216        } else {
217          results[treeLengthsTableRowName].Value = treeLengthsTable;
218        }
219
220        bool storeHistory = StoreHistoryParameter.Value.Value;
221        const string treeLengthHistoryTableName = "Tree lengths history";
222
223        if (storeHistory) {
224          // store tree lengths for each generation
225          var historyDataRow = new DataRow("Tree lengths", "", treeLengthsTableRow.Values);
226          historyDataRow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
227          historyDataRow.VisualProperties.ExactBins = false;
228          historyDataRow.VisualProperties.Bins = range;
229          historyDataRow.VisualProperties.ScaleFactor = treeLengthsTableRow.VisualProperties.ScaleFactor;
230          historyDataRow.VisualProperties.IsVisibleInLegend = false;
231          var historyTable = new DataTable("Tree lengths");
232          historyTable.Rows.Add(historyDataRow);
233          // visual properties for the X-axis
234          historyTable.VisualProperties.XAxisMinimumAuto = false;
235          historyTable.VisualProperties.XAxisMaximumAuto = false;
236          historyTable.VisualProperties.XAxisMinimumFixedValue = 0.0;
237          if (maxLength > maximumAllowedTreeLength + 1)
238            historyTable.VisualProperties.XAxisMaximumFixedValue = maxLength + 1; // +1 so the histogram column for the maximum length won't get trimmed
239          else
240            historyTable.VisualProperties.XAxisMaximumFixedValue = maximumAllowedTreeLength + 1;
241          historyTable.VisualProperties.XAxisTitle = xAxisTitle;
242          // visual properties for the Y-axis
243          historyTable.VisualProperties.YAxisMinimumAuto = false;
244          historyTable.VisualProperties.YAxisMaximumAuto = false;
245          historyTable.VisualProperties.YAxisMinimumFixedValue = 0.0;
246          historyTable.VisualProperties.YAxisMaximumFixedValue = yAxisMaximumFixedValue;
247          historyTable.VisualProperties.YAxisTitle = yAxisTitle;
248
249          var treeLengthsHistory = SymbolicExpressionTreeLengthsHistoryParameter.ActualValue;
250          if (treeLengthsHistory == null) {
251            treeLengthsHistory = new DataTableHistory();
252            SymbolicExpressionTreeLengthsHistoryParameter.ActualValue = treeLengthsHistory;
253          }
254
255          treeLengthsHistory.Add(historyTable);
256
257          if (!results.ContainsKey(treeLengthHistoryTableName)) {
258            results.Add(new Result(treeLengthHistoryTableName, treeLengthsHistory));
259          } else {
260            results[treeLengthHistoryTableName].Value = treeLengthsHistory;
261          }
262        }
263      }
264      return base.Apply();
265    }
266  }
267}
Note: See TracBrowser for help on using the repository browser.