Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisVariableFrequencyAnalyzer.cs @ 6479

Last change on this file since 6479 was 5924, checked in by gkronber, 14 years ago

#1418 fixed another bug in variable frequency analyzer.

File size: 10.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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Analysis;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  /// <summary>
36  /// Calculates the accumulated frequencies of variable-symbols over all trees in the population.
37  /// </summary>
38  [Item("SymbolicDataAnalysisVariableFrequencyAnalyzer", "Calculates the accumulated frequencies of variable-symbols over all trees in the population.")]
39  [StorableClass]
40  public sealed class SymbolicDataAnalysisVariableFrequencyAnalyzer : SymbolicDataAnalysisAnalyzer {
41    private const string VariableFrequenciesParameterName = "VariableFrequencies";
42    private const string AggregateLaggedVariablesParameterName = "AggregateLaggedVariables";
43    private const string VariableImpactsParameterName = "VariableImpacts";
44
45    #region parameter properties
46    public ILookupParameter<DataTable> VariableFrequenciesParameter {
47      get { return (ILookupParameter<DataTable>)Parameters[VariableFrequenciesParameterName]; }
48    }
49    public ILookupParameter<DoubleMatrix> VariableImpactsParameter {
50      get { return (ILookupParameter<DoubleMatrix>)Parameters[VariableImpactsParameterName]; }
51    }
52    public IValueLookupParameter<BoolValue> AggregateLaggedVariablesParameter {
53      get { return (IValueLookupParameter<BoolValue>)Parameters[AggregateLaggedVariablesParameterName]; }
54    }
55    #endregion
56    #region properties
57    public BoolValue AggregateLaggedVariables {
58      get { return AggregateLaggedVariablesParameter.ActualValue; }
59      set { AggregateLaggedVariablesParameter.Value = value; }
60    }
61    #endregion
62    [StorableConstructor]
63    private SymbolicDataAnalysisVariableFrequencyAnalyzer(bool deserializing) : base(deserializing) { }
64    private SymbolicDataAnalysisVariableFrequencyAnalyzer(SymbolicDataAnalysisVariableFrequencyAnalyzer original, Cloner cloner)
65      : base(original, cloner) {
66    }
67    public SymbolicDataAnalysisVariableFrequencyAnalyzer()
68      : base() {
69      Parameters.Add(new LookupParameter<DataTable>(VariableFrequenciesParameterName, "The relative variable reference frequencies aggregated over all trees in the population."));
70      Parameters.Add(new LookupParameter<DoubleMatrix>(VariableImpactsParameterName, "The relative variable relevance calculated as the average relative variable frequency over the whole run."));
71      Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateLaggedVariablesParameterName, "Switch that determines whether all references to a variable should be aggregated regardless of time-offsets. Turn off to analyze all variable references with different time offsets separately.", new BoolValue(true)));
72    }
73
74    public override IDeepCloneable Clone(Cloner cloner) {
75      return new SymbolicDataAnalysisVariableFrequencyAnalyzer(this, cloner);
76    }
77
78    public override IOperation Apply() {
79      ItemArray<ISymbolicExpressionTree> expressions = SymbolicExpressionTreeParameter.ActualValue;
80      ResultCollection results = ResultCollection;
81      DoubleMatrix impacts;
82      DataTable datatable;
83      if (VariableFrequenciesParameter.ActualValue == null) {
84        datatable = new DataTable("Variable frequencies", "Relative frequency of variable references aggregated over the whole population.");
85        datatable.VisualProperties.XAxisTitle = "Generation";
86        datatable.VisualProperties.YAxisTitle = "Relative Variable Frequency";
87        impacts = new DoubleMatrix();
88        VariableFrequenciesParameter.ActualValue = datatable;
89        VariableImpactsParameter.ActualValue = impacts;
90        results.Add(new Result("Variable frequencies", "Relative frequency of variable references aggregated over the whole population.", datatable));
91        results.Add(new Result("Variable impacts", "The relative variable relevance calculated as the average relative variable frequency over the whole run.", impacts));
92      }
93
94      impacts = VariableImpactsParameter.ActualValue;
95      datatable = VariableFrequenciesParameter.ActualValue;
96      // all rows must have the same number of values so we can just take the first
97      int numberOfValues = datatable.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First();
98
99      foreach (var pair in SymbolicDataAnalysisVariableFrequencyAnalyzer.CalculateVariableFrequencies(expressions, AggregateLaggedVariables.Value)) {
100        if (!datatable.Rows.ContainsKey(pair.Key)) {
101          // initialize a new row for the variable and pad with zeros
102          DataRow row = new DataRow(pair.Key, "", Enumerable.Repeat(0.0, numberOfValues));
103          row.VisualProperties.StartIndexZero = true;
104          datatable.Rows.Add(row);
105        }
106        datatable.Rows[pair.Key].Values.Add(pair.Value);
107      }
108
109      // add a zero for each data row that was not modified in the previous loop
110      foreach (var row in datatable.Rows.Where(r => r.Values.Count != numberOfValues + 1))
111        row.Values.Add(0.0);
112
113      // update variable impacts matrix
114      var orderedImpacts = (from row in datatable.Rows
115                            select new { Name = row.Name, Impact = datatable.Rows[row.Name].Values.Average() })
116                           .OrderByDescending(p => p.Impact)
117                           .ToList();
118      var matrix = (IStringConvertibleMatrix)impacts;
119      matrix.Rows = orderedImpacts.Count;
120      matrix.RowNames = orderedImpacts.Select(x => x.Name);
121      matrix.Columns = 1;
122      matrix.ColumnNames = new string[] { "Relative variable relevance" };
123      int i = 0;
124      foreach (var p in orderedImpacts) {
125        matrix.SetValue(p.Impact.ToString(), i++, 0);
126      }
127
128      return base.Apply();
129    }
130
131    public static IEnumerable<KeyValuePair<string, double>> CalculateVariableFrequencies(IEnumerable<ISymbolicExpressionTree> trees, bool aggregateLaggedVariables = true) {
132      Dictionary<string, double> variableFrequencies = new Dictionary<string, double>();
133      int totalNumberOfSymbols = 0;
134
135      foreach (var tree in trees) {
136        var variableReferences = GetVariableReferences(tree, aggregateLaggedVariables);
137        foreach (var pair in variableReferences) {
138          totalNumberOfSymbols += pair.Value;
139          if (variableFrequencies.ContainsKey(pair.Key)) {
140            variableFrequencies[pair.Key] += pair.Value;
141          } else {
142            variableFrequencies.Add(pair.Key, pair.Value);
143          }
144        }
145      }
146
147      foreach (var pair in variableFrequencies)
148        yield return new KeyValuePair<string, double>(pair.Key, pair.Value / totalNumberOfSymbols);
149    }
150
151    private static IEnumerable<KeyValuePair<string, int>> GetVariableReferences(ISymbolicExpressionTree tree, bool aggregateLaggedVariables = true) {
152      Dictionary<string, int> references = new Dictionary<string, int>();
153      if (aggregateLaggedVariables) {
154        tree.Root.ForEachNodePrefix(node => {
155          if (node.Symbol is Variable) {
156            var varNode = node as VariableTreeNode;
157            IncReferenceCount(references, varNode.VariableName);
158          } else if (node.Symbol is VariableCondition) {
159            var varCondNode = node as VariableConditionTreeNode;
160            IncReferenceCount(references, varCondNode.VariableName);
161          }
162        });
163      } else {
164        GetVariableReferences(references, tree.Root, 0);
165      }
166      return references;
167    }
168
169    private static void GetVariableReferences(Dictionary<string, int> references, ISymbolicExpressionTreeNode node, int currentLag) {
170      if (node.Symbol is LaggedVariable) {
171        var laggedVarNode = node as LaggedVariableTreeNode;
172        IncReferenceCount(references, laggedVarNode.VariableName, currentLag + laggedVarNode.Lag);
173      } else if (node.Symbol is Variable) {
174        var varNode = node as VariableTreeNode;
175        IncReferenceCount(references, varNode.VariableName, currentLag);
176      } else if (node.Symbol is VariableCondition) {
177        var varCondNode = node as VariableConditionTreeNode;
178        IncReferenceCount(references, varCondNode.VariableName, currentLag);
179        GetVariableReferences(references, node.GetSubtree(0), currentLag);
180        GetVariableReferences(references, node.GetSubtree(1), currentLag);
181      } else if (node.Symbol is Integral) {
182        var laggedNode = node as LaggedTreeNode;
183        for (int l = laggedNode.Lag; l <= 0; l++) {
184          GetVariableReferences(references, node.GetSubtree(0), currentLag + l);
185        }
186      } else if (node.Symbol is Derivative) {
187        for (int l = -4; l <= 0; l++) {
188          GetVariableReferences(references, node.GetSubtree(0), currentLag + l);
189        }
190      } else if (node.Symbol is TimeLag) {
191        var laggedNode = node as LaggedTreeNode;
192        GetVariableReferences(references, node.GetSubtree(0), currentLag + laggedNode.Lag);
193      } else {
194        foreach (var subtree in node.Subtrees) {
195          GetVariableReferences(references, subtree, currentLag);
196        }
197      }
198    }
199
200    private static void IncReferenceCount(Dictionary<string, int> references, string variableName, int timeLag = 0) {
201      string referenceId = variableName +
202        (timeLag == 0 ? "" : timeLag < 0 ? "(t" + timeLag + ")" : "(t+" + timeLag + ")");
203      if (references.ContainsKey(referenceId)) {
204        references[referenceId]++;
205      } else {
206        references[referenceId] = 1;
207      }
208    }
209  }
210}
Note: See TracBrowser for help on using the repository browser.