Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionSymbolFrequencyAnalyzer.cs @ 18242

Last change on this file since 18242 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

File size: 7.4 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.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
35  /// <summary>
36  /// An operator that tracks the frequencies of distinct symbols in symbolic expression trees.
37  /// </summary>
38  [Item("SymbolicExpressionSymbolFrequencyAnalyzer", "An operator that tracks frequencies of symbols in symbolic expression trees.")]
39  [StorableClass]
40  public class SymbolicExpressionSymbolFrequencyAnalyzer : SingleSuccessorOperator, ISymbolicExpressionTreeAnalyzer {
41    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
42    private const string ResultsParameterName = "Results";
43    private const string SymbolFrequenciesParameterName = "SymbolFrequencies";
44    private const string AggregateSymbolsWithDifferentSubtreeCountParameterName = "AggregateSymbolsWithDifferentSubtreeCount";
45
46    #region parameter properties
47    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
48      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
49    }
50    public ILookupParameter<DataTable> SymbolFrequenciesParameter {
51      get { return (ILookupParameter<DataTable>)Parameters[SymbolFrequenciesParameterName]; }
52    }
53    public ILookupParameter<ResultCollection> ResultsParameter {
54      get { return (ILookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
55    }
56    public IValueParameter<BoolValue> AggregateSymbolsWithDifferentSubtreeCountParameter {
57      get { return (IValueParameter<BoolValue>)Parameters[AggregateSymbolsWithDifferentSubtreeCountParameterName]; }
58    }
59    #endregion
60    #region properties
61    public BoolValue AggregrateSymbolsWithDifferentSubtreeCount {
62      get { return AggregateSymbolsWithDifferentSubtreeCountParameter.Value; }
63      set { AggregateSymbolsWithDifferentSubtreeCountParameter.Value = value; }
64    }
65    #endregion
66
67    [StorableConstructor]
68    protected SymbolicExpressionSymbolFrequencyAnalyzer(bool deserializing) : base(deserializing) { }
69    protected SymbolicExpressionSymbolFrequencyAnalyzer(SymbolicExpressionSymbolFrequencyAnalyzer original, Cloner cloner) : base(original, cloner) { }
70    public SymbolicExpressionSymbolFrequencyAnalyzer()
71      : base() {
72      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
73      Parameters.Add(new LookupParameter<DataTable>(SymbolFrequenciesParameterName, "The data table to store the symbol frequencies."));
74      Parameters.Add(new LookupParameter<ResultCollection>(ResultsParameterName, "The result collection where the symbol frequencies should be stored."));
75      Parameters.Add(new ValueParameter<BoolValue>(AggregateSymbolsWithDifferentSubtreeCountParameterName, "Flag that indicates if the frequencies of symbols with the same name but different number of sub-trees should be aggregated.", new BoolValue(true)));
76    }
77    public override IDeepCloneable Clone(Cloner cloner) {
78      return new SymbolicExpressionSymbolFrequencyAnalyzer(this, cloner);
79    }
80
81    [StorableHook(HookType.AfterDeserialization)]
82    private void AfterDeserialization() {
83      #region remove with HL 3.4
84      if (!Parameters.ContainsKey(AggregateSymbolsWithDifferentSubtreeCountParameterName))
85        Parameters.Add(new ValueParameter<BoolValue>(AggregateSymbolsWithDifferentSubtreeCountParameterName, "Flag that indicates if the frequencies of symbols with the same name but different number of sub-trees should be aggregated.", new BoolValue(true)));
86      #endregion
87    }
88
89    public override IOperation Apply() {
90      ItemArray<ISymbolicExpressionTree> expressions = SymbolicExpressionTreeParameter.ActualValue;
91      ResultCollection results = ResultsParameter.ActualValue;
92      DataTable symbolFrequencies = SymbolFrequenciesParameter.ActualValue;
93      if (symbolFrequencies == null) {
94        symbolFrequencies = new DataTable("Symbol frequencies", "Relative frequency of symbols aggregated over the whole population.");
95        symbolFrequencies.VisualProperties.YAxisTitle = "Relative Symbol Frequency";
96
97        SymbolFrequenciesParameter.ActualValue = symbolFrequencies;
98        results.Add(new Result("Symbol frequencies", symbolFrequencies));
99      }
100
101      // all rows must have the same number of values so we can just take the first
102      int numberOfValues = symbolFrequencies.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First();
103
104      foreach (var pair in SymbolicExpressionSymbolFrequencyAnalyzer.CalculateSymbolFrequencies(expressions, AggregrateSymbolsWithDifferentSubtreeCount.Value)) {
105        if (!symbolFrequencies.Rows.ContainsKey(pair.Key)) {
106          // initialize a new row for the symbol and pad with zeros
107          DataRow row = new DataRow(pair.Key, "", Enumerable.Repeat(0.0, numberOfValues));
108          row.VisualProperties.StartIndexZero = true;
109          symbolFrequencies.Rows.Add(row);
110        }
111        symbolFrequencies.Rows[pair.Key].Values.Add(Math.Round(pair.Value, 3));
112      }
113
114      // add a zero for each data row that was not modified in the previous loop
115      foreach (var row in symbolFrequencies.Rows.Where(r => r.Values.Count != numberOfValues + 1))
116        row.Values.Add(0.0);
117
118      return base.Apply();
119    }
120
121    public static IEnumerable<KeyValuePair<string, double>> CalculateSymbolFrequencies(IEnumerable<ISymbolicExpressionTree> trees, bool aggregateDifferentNumberOfSubtrees = true) {
122      Dictionary<string, double> symbolFrequencies = new Dictionary<string, double>();
123      int totalNumberOfSymbols = 0;
124
125      foreach (var tree in trees) {
126        foreach (var node in tree.IterateNodesPrefix()) {
127          string symbolName;
128          if (aggregateDifferentNumberOfSubtrees) symbolName = node.Symbol.Name;
129          else symbolName = node.Symbol.Name + "-" + node.SubtreesCount;
130          if (symbolFrequencies.ContainsKey(symbolName)) symbolFrequencies[symbolName] += 1;
131          else symbolFrequencies.Add(symbolName, 1);
132          totalNumberOfSymbols++;
133        }
134      }
135
136      foreach (var pair in symbolFrequencies)
137        yield return new KeyValuePair<string, double>(pair.Key, pair.Value / totalNumberOfSymbols);
138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.