Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1661: Improved naming of variables and replaced literals with constants. Added new IsVisibleInLegend visual property for data rows.

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