Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1530 integrate changes from trunk

File size: 7.4 KB
RevLine 
[5386]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5386]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
[6760]22using System;
[5386]23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
[5983]28using HeuristicLab.Data;
[5386]29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
[5499]34namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[5386]35  /// <summary>
[5499]36  /// An operator that tracks the frequencies of distinct symbols in symbolic expression trees.
[5386]37  /// </summary>
[5499]38  [Item("SymbolicExpressionSymbolFrequencyAnalyzer", "An operator that tracks frequencies of symbols in symbolic expression trees.")]
[5386]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";
[5971]44    private const string AggregateSymbolsWithDifferentSubtreeCountParameterName = "AggregateSymbolsWithDifferentSubtreeCount";
[5386]45
46    #region parameter properties
[5510]47    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
48      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
[5386]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    }
[5971]56    public IValueParameter<BoolValue> AggregateSymbolsWithDifferentSubtreeCountParameter {
57      get { return (IValueParameter<BoolValue>)Parameters[AggregateSymbolsWithDifferentSubtreeCountParameterName]; }
58    }
[5386]59    #endregion
60    #region properties
[5971]61    public BoolValue AggregrateSymbolsWithDifferentSubtreeCount {
62      get { return AggregateSymbolsWithDifferentSubtreeCountParameter.Value; }
63      set { AggregateSymbolsWithDifferentSubtreeCountParameter.Value = value; }
[5386]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() {
[5510]72      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
[5971]73      Parameters.Add(new LookupParameter<DataTable>(SymbolFrequenciesParameterName, "The data table to store the symbol frequencies."));
[5499]74      Parameters.Add(new LookupParameter<ResultCollection>(ResultsParameterName, "The result collection where the symbol frequencies should be stored."));
[5971]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)));
[5386]76    }
77    public override IDeepCloneable Clone(Cloner cloner) {
78      return new SymbolicExpressionSymbolFrequencyAnalyzer(this, cloner);
79    }
80
[5983]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
[5386]89    public override IOperation Apply() {
[5510]90      ItemArray<ISymbolicExpressionTree> expressions = SymbolicExpressionTreeParameter.ActualValue;
[5386]91      ResultCollection results = ResultsParameter.ActualValue;
[5971]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";
[5386]96
[5971]97        SymbolFrequenciesParameter.ActualValue = symbolFrequencies;
98        results.Add(new Result("Symbol frequencies", symbolFrequencies));
[5386]99      }
100
[5392]101      // all rows must have the same number of values so we can just take the first
[5971]102      int numberOfValues = symbolFrequencies.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First();
[5392]103
[5971]104      foreach (var pair in SymbolicExpressionSymbolFrequencyAnalyzer.CalculateSymbolFrequencies(expressions, AggregrateSymbolsWithDifferentSubtreeCount.Value)) {
105        if (!symbolFrequencies.Rows.ContainsKey(pair.Key)) {
[5392]106          // initialize a new row for the symbol and pad with zeros
107          DataRow row = new DataRow(pair.Key, "", Enumerable.Repeat(0.0, numberOfValues));
[5386]108          row.VisualProperties.StartIndexZero = true;
[5971]109          symbolFrequencies.Rows.Add(row);
[5386]110        }
[6760]111        symbolFrequencies.Rows[pair.Key].Values.Add(Math.Round(pair.Value, 3));
[5386]112      }
113
[5392]114      // add a zero for each data row that was not modified in the previous loop
[5971]115      foreach (var row in symbolFrequencies.Rows.Where(r => r.Values.Count != numberOfValues + 1))
[5386]116        row.Values.Add(0.0);
117
118      return base.Apply();
119    }
120
[5971]121    public static IEnumerable<KeyValuePair<string, double>> CalculateSymbolFrequencies(IEnumerable<ISymbolicExpressionTree> trees, bool aggregateDifferentNumberOfSubtrees = true) {
[5386]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()) {
[5971]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);
[5386]132          totalNumberOfSymbols++;
133        }
134      }
135
[5392]136      foreach (var pair in symbolFrequencies)
137        yield return new KeyValuePair<string, double>(pair.Key, pair.Value / totalNumberOfSymbols);
[5386]138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.