source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisVariableFrequencyAnalyzer.cs @ 6811

Last change on this file since 6811 was 6811, checked in by gkronber, 10 years ago

#1081 added configuration of default grammar for time-series prognosis and improved multiple update of variable impacts result

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