[5556] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[15583] | 3 | * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[5556] | 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 |
|
---|
[6709] | 22 | using System;
|
---|
[5556] | 23 | using System.Collections.Generic;
|
---|
[14826] | 24 | using System.Globalization;
|
---|
[5556] | 25 | using System.Linq;
|
---|
[6981] | 26 | using HeuristicLab.Analysis;
|
---|
[5556] | 27 | using HeuristicLab.Common;
|
---|
| 28 | using HeuristicLab.Core;
|
---|
| 29 | using HeuristicLab.Data;
|
---|
| 30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
| 31 | using HeuristicLab.Optimization;
|
---|
| 32 | using HeuristicLab.Parameters;
|
---|
| 33 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 34 |
|
---|
| 35 | namespace 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";
|
---|
[14826] | 44 | private const string AggregateFactorVariablesParameterName = "AggregateFactorVariables";
|
---|
[5748] | 45 | private const string VariableImpactsParameterName = "VariableImpacts";
|
---|
[5556] | 46 |
|
---|
| 47 | #region parameter properties
|
---|
| 48 | public ILookupParameter<DataTable> VariableFrequenciesParameter {
|
---|
| 49 | get { return (ILookupParameter<DataTable>)Parameters[VariableFrequenciesParameterName]; }
|
---|
| 50 | }
|
---|
[5748] | 51 | public ILookupParameter<DoubleMatrix> VariableImpactsParameter {
|
---|
| 52 | get { return (ILookupParameter<DoubleMatrix>)Parameters[VariableImpactsParameterName]; }
|
---|
| 53 | }
|
---|
[5556] | 54 | public IValueLookupParameter<BoolValue> AggregateLaggedVariablesParameter {
|
---|
| 55 | get { return (IValueLookupParameter<BoolValue>)Parameters[AggregateLaggedVariablesParameterName]; }
|
---|
| 56 | }
|
---|
[14826] | 57 | public IValueLookupParameter<BoolValue> AggregateFactorVariablesParameter {
|
---|
| 58 | get { return (IValueLookupParameter<BoolValue>)Parameters[AggregateFactorVariablesParameterName]; }
|
---|
| 59 | }
|
---|
[5556] | 60 | #endregion
|
---|
| 61 | #region properties
|
---|
| 62 | public BoolValue AggregateLaggedVariables {
|
---|
| 63 | get { return AggregateLaggedVariablesParameter.ActualValue; }
|
---|
[5748] | 64 | set { AggregateLaggedVariablesParameter.Value = value; }
|
---|
[5556] | 65 | }
|
---|
[14826] | 66 | public BoolValue AggregateFactorVariables {
|
---|
| 67 | get { return AggregateFactorVariablesParameter.ActualValue; }
|
---|
| 68 | set { AggregateFactorVariablesParameter.Value = value; }
|
---|
| 69 | }
|
---|
[5556] | 70 | #endregion
|
---|
| 71 | [StorableConstructor]
|
---|
| 72 | private SymbolicDataAnalysisVariableFrequencyAnalyzer(bool deserializing) : base(deserializing) { }
|
---|
| 73 | private SymbolicDataAnalysisVariableFrequencyAnalyzer(SymbolicDataAnalysisVariableFrequencyAnalyzer original, Cloner cloner)
|
---|
| 74 | : base(original, cloner) {
|
---|
| 75 | }
|
---|
| 76 | public SymbolicDataAnalysisVariableFrequencyAnalyzer()
|
---|
| 77 | : base() {
|
---|
| 78 | Parameters.Add(new LookupParameter<DataTable>(VariableFrequenciesParameterName, "The relative variable reference frequencies aggregated over all trees in the population."));
|
---|
[5748] | 79 | Parameters.Add(new LookupParameter<DoubleMatrix>(VariableImpactsParameterName, "The relative variable relevance calculated as the average relative variable frequency over the whole run."));
|
---|
[5556] | 80 | 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)));
|
---|
[14826] | 81 | Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateFactorVariablesParameterName, "Switch that determines whether all references to factor variables should be aggregated regardless of the value. Turn off to analyze all factor variable references with different values separately.", new BoolValue(true)));
|
---|
[5556] | 82 | }
|
---|
[5748] | 83 |
|
---|
[14826] | 84 | [StorableHook(HookType.AfterDeserialization)]
|
---|
| 85 | private void AfterDeserialization() {
|
---|
| 86 | // BackwardsCompatibility3.3
|
---|
| 87 | #region Backwards compatible code, remove with 3.4
|
---|
| 88 | if (!Parameters.ContainsKey(AggregateFactorVariablesParameterName)) {
|
---|
| 89 | Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateFactorVariablesParameterName, "Switch that determines whether all references to factor variables should be aggregated regardless of the value. Turn off to analyze all factor variable references with different values separately.", new BoolValue(true)));
|
---|
| 90 | }
|
---|
| 91 | #endregion
|
---|
| 92 | }
|
---|
| 93 |
|
---|
[5556] | 94 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 95 | return new SymbolicDataAnalysisVariableFrequencyAnalyzer(this, cloner);
|
---|
| 96 | }
|
---|
| 97 |
|
---|
| 98 | public override IOperation Apply() {
|
---|
| 99 | ItemArray<ISymbolicExpressionTree> expressions = SymbolicExpressionTreeParameter.ActualValue;
|
---|
| 100 | ResultCollection results = ResultCollection;
|
---|
[5748] | 101 | DataTable datatable;
|
---|
| 102 | if (VariableFrequenciesParameter.ActualValue == null) {
|
---|
| 103 | datatable = new DataTable("Variable frequencies", "Relative frequency of variable references aggregated over the whole population.");
|
---|
| 104 | datatable.VisualProperties.XAxisTitle = "Generation";
|
---|
| 105 | datatable.VisualProperties.YAxisTitle = "Relative Variable Frequency";
|
---|
| 106 | VariableFrequenciesParameter.ActualValue = datatable;
|
---|
| 107 | results.Add(new Result("Variable frequencies", "Relative frequency of variable references aggregated over the whole population.", datatable));
|
---|
[6811] | 108 | results.Add(new Result("Variable impacts", "The relative variable relevance calculated as the average relative variable frequency over the whole run.", new DoubleMatrix()));
|
---|
[5556] | 109 | }
|
---|
| 110 |
|
---|
[5748] | 111 | datatable = VariableFrequenciesParameter.ActualValue;
|
---|
[5556] | 112 | // all rows must have the same number of values so we can just take the first
|
---|
[5748] | 113 | int numberOfValues = datatable.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First();
|
---|
[5556] | 114 |
|
---|
[14826] | 115 | foreach (var pair in CalculateVariableFrequencies(expressions, AggregateLaggedVariables.Value, AggregateFactorVariables.Value)) {
|
---|
[5748] | 116 | if (!datatable.Rows.ContainsKey(pair.Key)) {
|
---|
[5556] | 117 | // initialize a new row for the variable and pad with zeros
|
---|
| 118 | DataRow row = new DataRow(pair.Key, "", Enumerable.Repeat(0.0, numberOfValues));
|
---|
| 119 | row.VisualProperties.StartIndexZero = true;
|
---|
[5748] | 120 | datatable.Rows.Add(row);
|
---|
[5556] | 121 | }
|
---|
[6709] | 122 | datatable.Rows[pair.Key].Values.Add(Math.Round(pair.Value, 3));
|
---|
[5556] | 123 | }
|
---|
| 124 |
|
---|
| 125 | // add a zero for each data row that was not modified in the previous loop
|
---|
[5748] | 126 | foreach (var row in datatable.Rows.Where(r => r.Values.Count != numberOfValues + 1))
|
---|
[5556] | 127 | row.Values.Add(0.0);
|
---|
| 128 |
|
---|
[5748] | 129 | // update variable impacts matrix
|
---|
| 130 | var orderedImpacts = (from row in datatable.Rows
|
---|
[8735] | 131 | select new { Name = row.Name, Impact = Math.Round(datatable.Rows[row.Name].Values.Average(), 3) })
|
---|
[5748] | 132 | .OrderByDescending(p => p.Impact)
|
---|
| 133 | .ToList();
|
---|
[6811] | 134 | var impacts = new DoubleMatrix();
|
---|
| 135 | var matrix = impacts as IStringConvertibleMatrix;
|
---|
[5748] | 136 | matrix.Rows = orderedImpacts.Count;
|
---|
| 137 | matrix.RowNames = orderedImpacts.Select(x => x.Name);
|
---|
| 138 | matrix.Columns = 1;
|
---|
| 139 | matrix.ColumnNames = new string[] { "Relative variable relevance" };
|
---|
| 140 | int i = 0;
|
---|
| 141 | foreach (var p in orderedImpacts) {
|
---|
| 142 | matrix.SetValue(p.Impact.ToString(), i++, 0);
|
---|
| 143 | }
|
---|
| 144 |
|
---|
[6811] | 145 | VariableImpactsParameter.ActualValue = impacts;
|
---|
| 146 | results["Variable impacts"].Value = impacts;
|
---|
[5556] | 147 | return base.Apply();
|
---|
| 148 | }
|
---|
| 149 |
|
---|
[14826] | 150 | public static IEnumerable<KeyValuePair<string, double>> CalculateVariableFrequencies(IEnumerable<ISymbolicExpressionTree> trees,
|
---|
| 151 | bool aggregateLaggedVariables = true, bool aggregateFactorVariables = true) {
|
---|
[5556] | 152 |
|
---|
[6728] | 153 | var variableFrequencies = trees
|
---|
[14826] | 154 | .SelectMany(t => GetVariableReferences(t, aggregateLaggedVariables, aggregateFactorVariables))
|
---|
[6728] | 155 | .GroupBy(pair => pair.Key, pair => pair.Value)
|
---|
| 156 | .ToDictionary(g => g.Key, g => (double)g.Sum());
|
---|
[5556] | 157 |
|
---|
[6728] | 158 | double totalNumberOfSymbols = variableFrequencies.Values.Sum();
|
---|
| 159 |
|
---|
[6981] | 160 | foreach (var pair in variableFrequencies.OrderBy(p => p.Key, new NaturalStringComparer()))
|
---|
[5556] | 161 | yield return new KeyValuePair<string, double>(pair.Key, pair.Value / totalNumberOfSymbols);
|
---|
| 162 | }
|
---|
| 163 |
|
---|
[14826] | 164 | private static IEnumerable<KeyValuePair<string, int>> GetVariableReferences(ISymbolicExpressionTree tree,
|
---|
| 165 | bool aggregateLaggedVariables = true, bool aggregateFactorVariables = true) {
|
---|
[5556] | 166 | Dictionary<string, int> references = new Dictionary<string, int>();
|
---|
| 167 | if (aggregateLaggedVariables) {
|
---|
| 168 | tree.Root.ForEachNodePrefix(node => {
|
---|
[14826] | 169 | if (node is IVariableTreeNode) {
|
---|
| 170 | var factorNode = node as BinaryFactorVariableTreeNode;
|
---|
| 171 | if (factorNode != null && !aggregateFactorVariables) {
|
---|
| 172 | IncReferenceCount(references, factorNode.VariableName + "=" + factorNode.VariableValue);
|
---|
| 173 | } else {
|
---|
| 174 | var varNode = node as IVariableTreeNode;
|
---|
| 175 | IncReferenceCount(references, varNode.VariableName);
|
---|
| 176 | }
|
---|
[5556] | 177 | }
|
---|
| 178 | });
|
---|
| 179 | } else {
|
---|
[14826] | 180 | GetVariableReferences(references, tree.Root, 0, aggregateFactorVariables);
|
---|
[5556] | 181 | }
|
---|
| 182 | return references;
|
---|
| 183 | }
|
---|
| 184 |
|
---|
[14826] | 185 | private static void GetVariableReferences(Dictionary<string, int> references, ISymbolicExpressionTreeNode node, int currentLag, bool aggregateFactorVariables) {
|
---|
| 186 | if (node is IVariableTreeNode) {
|
---|
| 187 | var laggedVarTreeNode = node as LaggedVariableTreeNode;
|
---|
| 188 | var binFactorVariableTreeNode = node as BinaryFactorVariableTreeNode;
|
---|
| 189 | var varConditionTreeNode = node as VariableConditionTreeNode;
|
---|
| 190 | if (laggedVarTreeNode != null) {
|
---|
| 191 | IncReferenceCount(references, laggedVarTreeNode.VariableName, currentLag + laggedVarTreeNode.Lag);
|
---|
| 192 | } else if (binFactorVariableTreeNode != null) {
|
---|
| 193 | if (aggregateFactorVariables) {
|
---|
| 194 | IncReferenceCount(references, binFactorVariableTreeNode.VariableName, currentLag);
|
---|
| 195 | } else {
|
---|
| 196 | IncReferenceCount(references, binFactorVariableTreeNode.VariableName + "=" + binFactorVariableTreeNode.VariableValue, currentLag);
|
---|
| 197 | }
|
---|
| 198 | } else if (varConditionTreeNode != null) {
|
---|
| 199 | IncReferenceCount(references, varConditionTreeNode.VariableName, currentLag);
|
---|
| 200 | GetVariableReferences(references, node.GetSubtree(0), currentLag, aggregateFactorVariables);
|
---|
| 201 | GetVariableReferences(references, node.GetSubtree(1), currentLag, aggregateFactorVariables);
|
---|
| 202 | } else {
|
---|
| 203 | var varNode = node as IVariableTreeNode;
|
---|
| 204 | IncReferenceCount(references, varNode.VariableName, currentLag);
|
---|
| 205 | }
|
---|
[5556] | 206 | } else if (node.Symbol is Integral) {
|
---|
| 207 | var laggedNode = node as LaggedTreeNode;
|
---|
| 208 | for (int l = laggedNode.Lag; l <= 0; l++) {
|
---|
[14826] | 209 | GetVariableReferences(references, node.GetSubtree(0), currentLag + l, aggregateFactorVariables);
|
---|
[5556] | 210 | }
|
---|
| 211 | } else if (node.Symbol is Derivative) {
|
---|
[5924] | 212 | for (int l = -4; l <= 0; l++) {
|
---|
[14826] | 213 | GetVariableReferences(references, node.GetSubtree(0), currentLag + l, aggregateFactorVariables);
|
---|
[5556] | 214 | }
|
---|
| 215 | } else if (node.Symbol is TimeLag) {
|
---|
| 216 | var laggedNode = node as LaggedTreeNode;
|
---|
[14826] | 217 | GetVariableReferences(references, node.GetSubtree(0), currentLag + laggedNode.Lag, aggregateFactorVariables);
|
---|
[5922] | 218 | } else {
|
---|
| 219 | foreach (var subtree in node.Subtrees) {
|
---|
[14826] | 220 | GetVariableReferences(references, subtree, currentLag, aggregateFactorVariables);
|
---|
[5922] | 221 | }
|
---|
[5556] | 222 | }
|
---|
| 223 | }
|
---|
| 224 |
|
---|
| 225 | private static void IncReferenceCount(Dictionary<string, int> references, string variableName, int timeLag = 0) {
|
---|
| 226 | string referenceId = variableName +
|
---|
| 227 | (timeLag == 0 ? "" : timeLag < 0 ? "(t" + timeLag + ")" : "(t+" + timeLag + ")");
|
---|
| 228 | if (references.ContainsKey(referenceId)) {
|
---|
| 229 | references[referenceId]++;
|
---|
| 230 | } else {
|
---|
| 231 | references[referenceId] = 1;
|
---|
| 232 | }
|
---|
| 233 | }
|
---|
| 234 | }
|
---|
| 235 | }
|
---|