Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18105 was 18105, checked in by dpiringe, 2 years ago

#3139

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