Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2988_ModelsOfModels2/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/ModelClustersFrequencyAnalyzer.cs @ 16899

Last change on this file since 16899 was 16899, checked in by msemenki, 5 years ago

#2988: New version of class structure.

File size: 7.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
23using HeuristicLab.Analysis;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using System;
31using System.Collections.Generic;
32using System.Linq;
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("SymbolicDataAnalysisModelClustersFrequencyAnalyzer", "Calculates the accumulated frequencies of Model Clusters over all trees in the population.")]
39  [StorableType("4755115D-1B73-4577-BA2A-A762AE4C3B2F")]
40  public sealed class ModelClustersFrequencyAnalyzer : SymbolicDataAnalysisAnalyzer {
41    private const string ModelClustersFrequencyParameterName = "ModelClustersFrequency";
42    private const string AggregateModelClustersParameterName = "AggregateModelClusters";
43
44    #region parameter properties
45    [Storable]
46    public ILookupParameter<DataTable> ModelClustersFrequencyParameter {
47      get { return (ILookupParameter<DataTable>)Parameters[ModelClustersFrequencyParameterName]; }
48    }
49    [Storable]
50    public IValueLookupParameter<BoolValue> AggregateModelClustersParameter {
51      get { return (IValueLookupParameter<BoolValue>)Parameters[AggregateModelClustersParameterName]; }
52    }
53    #endregion
54    #region properties
55    public BoolValue AggregateModelClusters {
56      get { return AggregateModelClustersParameter.ActualValue; }
57      set { AggregateModelClustersParameter.Value = value; }
58    }
59    public DataTable ModelClustersFrequency {
60      get { return ModelClustersFrequencyParameter.ActualValue; }
61      set { ModelClustersFrequencyParameter.ActualValue = value; }
62    }
63    #endregion
64    [StorableConstructor]
65    private ModelClustersFrequencyAnalyzer(StorableConstructorFlag _) : base(_) { }
66    private ModelClustersFrequencyAnalyzer(ModelClustersFrequencyAnalyzer original, Cloner cloner)
67      : base(original, cloner) {
68    }
69    public ModelClustersFrequencyAnalyzer()
70      : base() {
71      Parameters.Add(new LookupParameter<DataTable>(ModelClustersFrequencyParameterName, "The relative Model Clusters reference frequencies aggregated over all trees in the population."));
72      Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateModelClustersParameterName, "Switch that determines whether all references to factor Model Clusters should be aggregated regardless of the value. Turn off to analyze all factor variable references with different values separately.", new BoolValue(true)));
73    }
74
75    [StorableHook(HookType.AfterDeserialization)]
76    private void AfterDeserialization() {
77      // BackwardsCompatibility3.3
78      #region Backwards compatible code, remove with 3.4
79      if (!Parameters.ContainsKey(AggregateModelClustersParameterName)) {
80        Parameters.Add(new ValueLookupParameter<BoolValue>(AggregateModelClustersParameterName, "Switch that determines whether all references to factor Model Clusters should be aggregated regardless of the value. Turn off to analyze all factor Model Clusters references with different values separately.", new BoolValue(true)));
81      }
82      #endregion
83    }
84
85    public override IDeepCloneable Clone(Cloner cloner) {
86      return new ModelClustersFrequencyAnalyzer(this, cloner);
87    }
88
89    public override IOperation Apply() {
90      ItemArray<ISymbolicExpressionTree> expressions = SymbolicExpressionTreeParameter.ActualValue;
91      ResultCollection results = ResultCollection;
92      DataTable datatable;
93      if (ModelClustersFrequencyParameter.ActualValue == null) {
94        datatable = new DataTable("ModelClusters frequencies", "Relative frequency of ModelClusters references aggregated over the whole population.");
95        datatable.VisualProperties.XAxisTitle = "Generation";
96        datatable.VisualProperties.YAxisTitle = "Relative ModelClusters Frequency";
97        ModelClustersFrequencyParameter.ActualValue = datatable;
98        results.Add(new Result("ModelClusters frequencies", "Relative frequency of ModelClusters references aggregated over the whole population.", datatable));
99      }
100
101      datatable = ModelClustersFrequencyParameter.ActualValue;
102      // all rows must have the same number of values so we can just take the first
103      int numberOfValues = datatable.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First();
104
105      foreach (var pair in CalculateModelClustersFrequency(expressions)) {
106        if (!datatable.Rows.ContainsKey(pair.Key)) {
107          // initialize a new row for the variable and pad with zeros
108          DataRow row = new DataRow(pair.Key, "", Enumerable.Repeat(0.0, numberOfValues));
109          row.VisualProperties.StartIndexZero = true;
110          datatable.Rows.Add(row);
111        }
112        datatable.Rows[pair.Key].Values.Add(Math.Round(pair.Value, 3));
113      }
114
115      // add a zero for each data row that was not modified in the previous loop
116      foreach (var row in datatable.Rows.Where(r => r.Values.Count != numberOfValues + 1))
117        row.Values.Add(0.0);
118
119      return base.Apply();
120    }
121
122    public static IEnumerable<KeyValuePair<string, double>> CalculateModelClustersFrequency(IEnumerable<ISymbolicExpressionTree> trees) {
123      var modelClustersFrequency = trees
124          .SelectMany(t => GetModelClustersReferences(t))
125          .GroupBy(pair => pair.Key, pair => pair.Value)
126          .ToDictionary(g => g.Key, g => (double)g.Sum());
127
128      double totalNumberOfSymbols = modelClustersFrequency.Values.Sum();
129
130      foreach (var pair in modelClustersFrequency.OrderBy(p => p.Key, new NaturalStringComparer()))
131        yield return new KeyValuePair<string, double>(pair.Key, pair.Value / totalNumberOfSymbols);
132    }
133
134    private static IEnumerable<KeyValuePair<string, int>> GetModelClustersReferences(ISymbolicExpressionTree tree) {
135      Dictionary<string, int> references = new Dictionary<string, int>();
136      foreach (var treeNode in tree.IterateNodesPrefix().OfType<TreeModelTreeNode>()) {
137        string referenceId = "Cluster " + treeNode.ClusterNumer;
138        if (references.ContainsKey(referenceId)) {
139          references[referenceId]++;
140        } else {
141          references[referenceId] = 1;
142        }
143      }
144      return references;
145    }
146  }
147}
Note: See TracBrowser for help on using the repository browser.