Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gp-crossover/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs @ 7344

Last change on this file since 7344 was 7344, checked in by bburlacu, 13 years ago

#1682: New branch format: removed unnecessary files, merged remaining.

File size: 13.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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;
32using System;
33
34namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
35  /// <summary>
36  /// An operator that tracks tree lengths of Symbolic Expression Trees
37  /// </summary>
38  [Item("SymbolicExpressionTreeLengthAnalyzer", "An operator that tracks tree lengths of Symbolic Expression Trees")]
39  [StorableClass]
40  public sealed class SymbolicExpressionTreeLengthAnalyzer : SingleSuccessorOperator, ISymbolicExpressionTreeAnalyzer {
41    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
42    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
43    private const string SymbolicExpressionTreeLengthsParameterName = "SymbolicExpressionTreeLengthsTable";
44    private const string SymbolicExpressionTreeLengthsHistoryParameterName = "SymbolicExpressionTreeLengthsHistoryTable";
45    private const string ResultsParameterName = "Results";
46    private const string StoreHistoryParameterName = "StoreHistory";
47    private const string UpdateIntervalParameterName = "UpdateInterval";
48    private const string UpdateCounterParameterName = "UpdateCounter";
49
50    #region Parameter properties
51    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
52      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
53    }
54    public ValueLookupParameter<DataTable> SymbolicExpressionTreeLengthsParameter {
55      get { return (ValueLookupParameter<DataTable>)Parameters[SymbolicExpressionTreeLengthsParameterName]; }
56    }
57    public ValueLookupParameter<DataTableHistory> SymbolicExpressionTreeLengthsHistoryParameter {
58      get { return (ValueLookupParameter<DataTableHistory>)Parameters[SymbolicExpressionTreeLengthsHistoryParameterName]; }
59    }
60    public ValueLookupParameter<ResultCollection> ResultsParameter {
61      get { return (ValueLookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
62    }
63    // history
64    public ValueParameter<BoolValue> StoreHistoryParameter {
65      get { return (ValueParameter<BoolValue>)Parameters[StoreHistoryParameterName]; }
66    }
67    public ValueParameter<IntValue> UpdateIntervalParameter {
68      get { return (ValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
69    }
70    public ValueParameter<IntValue> UpdateCounterParameter {
71      get { return (ValueParameter<IntValue>)Parameters[UpdateCounterParameterName]; }
72    }
73    #endregion
74
75    #region Properties
76    public bool EnabledByDefault {
77      get { return true; }
78    }
79    public IntValue UpdateInterval {
80      get { return UpdateIntervalParameter.Value; }
81    }
82    public IntValue UpdateCounter {
83      get { return UpdateCounterParameter.Value; }
84    }
85    public BoolValue StoreHistory {
86      get { return StoreHistoryParameter.Value; }
87    }
88    #endregion
89
90    [StorableConstructor]
91    private SymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base() { }
92    private SymbolicExpressionTreeLengthAnalyzer(SymbolicExpressionTreeLengthAnalyzer original, Cloner cloner)
93      : base(original, cloner) {
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      SymbolicExpressionTreeLengthsParameter.Hidden = true;
110      SymbolicExpressionTreeLengthsHistoryParameter.Hidden = true;
111      ResultsParameter.Hidden = true;
112      UpdateCounterParameter.Hidden = true;
113    }
114
115    [StorableHook(HookType.AfterDeserialization)]
116    private void AfterDeserialization() {
117      // check if all the parameters are present and accounted for
118      if (!Parameters.ContainsKey(StoreHistoryParameterName)) {
119        Parameters.Add(new ValueParameter<BoolValue>(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
120      }
121      if (!Parameters.ContainsKey(UpdateIntervalParameterName)) {
122        Parameters.Add(new ValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
123      }
124      //necessary code to correct UpdateCounterParameter - type was changed from LookupParameter to ValueParameter
125      if (Parameters.ContainsKey(UpdateCounterParameterName) && (Parameters[UpdateCounterParameterName] is LookupParameter<IntValue>))
126        Parameters.Remove(UpdateCounterParameterName);
127      if (!Parameters.ContainsKey(UpdateCounterParameterName)) {
128        Parameters.Add(new ValueParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", new IntValue(0)));
129        UpdateCounterParameter.Hidden = true;
130      }
131    }
132
133    #region IStatefulItem members
134    public override void InitializeState() {
135      base.InitializeState();
136      UpdateCounter.Value = 0;
137    }
138    public override void ClearState() {
139      base.ClearState();
140      UpdateCounter.Value = 0;
141    }
142    #endregion
143
144    public override IOperation Apply() {
145      UpdateCounter.Value++;
146      // the analyzer runs periodically, every 'updateInterval' times
147      if (UpdateCounter.Value == UpdateInterval.Value) {
148        UpdateCounter.Value = 0; // reset counter
149
150        // compute all tree lengths and store them in the lengthsTable
151        var solutions = SymbolicExpressionTreeParameter.ActualValue;
152
153        var treeLengthsTable = SymbolicExpressionTreeLengthsParameter.ActualValue;
154        // if the table was not created yet, we create it here
155        if (treeLengthsTable == null) {
156          treeLengthsTable = new DataTable("Histogram");
157          SymbolicExpressionTreeLengthsParameter.ActualValue = treeLengthsTable;
158        }
159
160        // data table which stores tree length values
161        DataRow treeLengthsTableRow;
162
163        const string treeLengthsTableRowName = "Symbolic expression tree lengths";
164        const string treeLengthsTableRowDesc = "The distribution of symbolic expression tree lengths";
165        const string xAxisTitle = "Symbolic expression tree lengths";
166        const string yAxisTitle = "Frequency / Number of tree individuals";
167
168        var treeLengths = solutions.Select(s => (int)s.Length).ToList();
169
170        int maxLength = treeLengths.Max(t => t);
171        int minLength = treeLengths.Min(t => t);
172
173        if (!treeLengthsTable.Rows.ContainsKey(treeLengthsTableRowName)) {
174          treeLengthsTableRow = new DataRow(treeLengthsTableRowName, treeLengthsTableRowDesc, treeLengths.Select(x => (double)x));
175          treeLengthsTable.Rows.Add(treeLengthsTableRow);
176        } else {
177          treeLengthsTableRow = treeLengthsTable.Rows[treeLengthsTableRowName];
178          treeLengthsTableRow.Values.Replace(treeLengths.Select(x => (double)x));
179        }
180
181        double maximumAllowedTreeLength = ((LookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]).ActualValue.Value;
182
183        treeLengthsTableRow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
184        treeLengthsTableRow.VisualProperties.ExactBins = false;
185
186        int range = maxLength - minLength;
187        if (range == 0) range = 1;
188        // the following trick should result in an integer intervalWidth of 1,2,4,...
189        treeLengthsTableRow.VisualProperties.Bins = range;
190
191        if (maxLength <= 25) // [0,25]
192          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0;
193        else if (maxLength <= 100) // [26,100]
194          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 2.0;
195        else if (maxLength <= 250) // [101,250]
196          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 5.0;
197        else if (maxLength <= 500) // [251,500]
198          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 10.0;
199        else
200          treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 20.0; // [501,inf]
201
202        treeLengthsTableRow.VisualProperties.IsVisibleInLegend = false;
203
204        // visual properties for the X-axis
205        treeLengthsTable.VisualProperties.XAxisMinimumAuto = false;
206        treeLengthsTable.VisualProperties.XAxisMaximumAuto = false;
207        treeLengthsTable.VisualProperties.XAxisMinimumFixedValue = 0.0;
208        if (maxLength > maximumAllowedTreeLength + 1)
209          treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maxLength + 1; // +1 so the histogram column for the maximum length won't get trimmed
210        else
211          treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maximumAllowedTreeLength + 1;
212        treeLengthsTable.VisualProperties.XAxisTitle = xAxisTitle;
213        //visual properties for the Y-axis
214        treeLengthsTable.VisualProperties.YAxisMinimumAuto = false;
215        treeLengthsTable.VisualProperties.YAxisMaximumAuto = false;
216        treeLengthsTable.VisualProperties.YAxisMinimumFixedValue = 0.0;
217        int maxFreq = (int)Math.Round(solutions.GroupBy(s => s.Length).Max(g => g.Count()) / treeLengthsTableRow.VisualProperties.ScaleFactor);
218        if (maxFreq % 5 != 0)
219          maxFreq += (5 - maxFreq % 5);
220        double yAxisMaximumFixedValue = maxFreq;
221
222        treeLengthsTable.VisualProperties.YAxisMaximumFixedValue = yAxisMaximumFixedValue;
223        treeLengthsTable.VisualProperties.YAxisTitle = yAxisTitle;
224
225        var results = ResultsParameter.ActualValue;
226
227        if (!results.ContainsKey(treeLengthsTableRowName)) {
228          results.Add(new Result(treeLengthsTableRowName, treeLengthsTable));
229        } else {
230          results[treeLengthsTableRowName].Value = treeLengthsTable;
231        }
232
233        bool storeHistory = StoreHistoryParameter.Value.Value;
234        const string treeLengthHistoryTableName = "Tree lengths history";
235
236        if (storeHistory) {
237          var treeLengthsHistory = SymbolicExpressionTreeLengthsHistoryParameter.ActualValue;
238          if (treeLengthsHistory == null) {
239            treeLengthsHistory = new DataTableHistory();
240            SymbolicExpressionTreeLengthsHistoryParameter.ActualValue = treeLengthsHistory;
241          }
242          treeLengthsHistory.Add((DataTable)treeLengthsTable.Clone());
243
244          if (!results.ContainsKey(treeLengthHistoryTableName)) {
245            results.Add(new Result(treeLengthHistoryTableName, treeLengthsHistory));
246          } else {
247            results[treeLengthHistoryTableName].Value = treeLengthsHistory;
248          }
249        }
250      }
251      return base.Apply();
252    }
253  }
254}
Note: See TracBrowser for help on using the repository browser.