Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Parameter-less Population Pyramid/HeuristicLab.Algorithms.ParameterlessPopulationPyramid/3.3/LinkageTree.cs @ 11838

Last change on this file since 11838 was 11838, checked in by bgoldman, 9 years ago

#2282: Added BEACON to the copyright on P3 files and included comments referring to the publication

File size: 9.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 * and the BEACON Center for the Study of Evolution in Action.
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21#endregion
22
23using System;
24using System.Collections.Generic;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28
29namespace HeuristicLab.Algorithms.ParameterlessPopulationPyramid {
30  // This code is based off the publication
31  // B. W. Goldman and W. F. Punch, "Parameter-less Population Pyramid," GECCO, pp. 785–792, 2014
32  // and the original source code in C++11 available from: https://github.com/brianwgoldman/Parameter-less_Population_Pyramid
33  public class LinkageTree {
34    private readonly int[][][] occurances;
35    private readonly List<int>[] clusters;
36    private List<int> clusterOrdering;
37    private readonly int length;
38    private readonly IRandom rand;
39    private bool rebuildRequired = false;
40
41    public LinkageTree(int length, IRandom rand) {
42      this.length = length;
43      this.rand = rand;
44      occurances = new int[length][][];
45
46      // Create a lower triangular matrix without the diagonal
47      for (int i = 1; i < length; i++) {
48        occurances[i] = new int[i][];
49        for (int j = 0; j < i; j++) {
50          occurances[i][j] = new int[4];
51        }
52      }
53      clusters = new List<int>[2 * length - 1];
54      for (int i = 0; i < clusters.Length; i++) {
55        clusters[i] = new List<int>();
56      }
57      clusterOrdering = new List<int>();
58
59      // first "length" clusters just contain a single gene
60      for (int i = 0; i < length; i++) {
61        clusters[i].Add(i);
62      }
63    }
64
65    public void Add(bool[] solution) {
66      if (solution.Length != length) throw new ArgumentException("The individual has not the correct length.");
67      for (int i = 1; i < solution.Length; i++) {
68        for (int j = 0; j < i; j++) {
69          // Updates the entry of the 4 long array based on the two bits
70
71          var pattern = (Convert.ToByte(solution[j]) << 1) + Convert.ToByte(solution[i]);
72          occurances[i][j][pattern]++;
73        }
74      }
75      rebuildRequired = true;
76    }
77
78    // While "total" always has an integer value, it is a double to reduce
79    // how often type casts are needed to prevent integer divison
80    // In the GECCO paper, calculates Equation 2
81    private static double NegativeEntropy(int[] counts, double total) {
82      double sum = 0;
83      for (int i = 0; i < counts.Length; i++) {
84        if (counts[i] != 0) {
85          sum += ((counts[i] / total) * Math.Log(counts[i] / total));
86        }
87      }
88      return sum;
89    }
90
91    // Uses the frequency table to calcuate the entropy distance between two indices.
92    // In the GECCO paper, calculates Equation 1
93    private int[] bits = new int[4];
94    private double EntropyDistance(int i, int j) {
95      // This ensures you are using the lower triangular part of "occurances"
96      if (i < j) {
97        int temp = i;
98        i = j;
99        j = temp;
100      }
101      var entry = occurances[i][j];
102      // extracts the occurrences of the individual bits
103      bits[0] = entry[0] + entry[2];  // i zero
104      bits[1] = entry[1] + entry[3];  // i one
105      bits[2] = entry[0] + entry[1];  // j zero
106      bits[3] = entry[2] + entry[3];  // j one
107      double total = bits[0] + bits[1];
108      // entropy of the two bits on their own
109      double separate = NegativeEntropy(bits, total);
110      // entropy of the two bits as a single unit
111      double together = NegativeEntropy(entry, total);
112      // If together there is 0 entropy, the distance is zero
113      if (together.IsAlmost(0)) {
114        return 0.0;
115      }
116      return 2 - (separate / together);
117    }
118
119
120
121    // Performs O(N^2) clustering based on the method described in:
122    // "Optimal implementations of UPGMA and other common clustering algorithms"
123    // by I. Gronau and S. Moran
124    // In the GECCO paper, Figure 2 is a simplified version of this algorithm.
125    private double[][] distances;
126    private void Rebuild() {
127      if (distances == null) {
128        distances = new double[clusters.Length * 2 - 1][];
129        for (int i = 0; i < distances.Length; i++)
130          distances[i] = new double[clusters.Length * 2 - 1];
131      }
132
133
134      // Keep track of which clusters have not been merged
135      var topLevel = new List<int>(length);
136      for (int i = 0; i < length; i++)
137        topLevel.Add(i);
138
139      bool[] useful = new bool[clusters.Length];
140      for (int i = 0; i < useful.Length; i++)
141        useful[i] = true;
142
143      // Store the distances between all clusters
144      for (int i = 1; i < length; i++) {
145        for (int j = 0; j < i; j++) {
146          distances[i][j] = EntropyDistance(clusters[i][0], clusters[j][0]);
147          // make it symmetric
148          distances[j][i] = distances[i][j];
149        }
150      }
151      // Each iteration we add some amount to the path, and remove the last
152      // two elements.  This keeps track of how much of usable is in the path.
153      int end_of_path = 0;
154
155      // build all clusters of size greater than 1
156      for (int index = length; index < clusters.Length; index++) {
157        // Shuffle everything not yet in the path
158        topLevel.ShuffleInPlace(rand, end_of_path, topLevel.Count - 1);
159
160        // if nothing in the path, just add a random usable node
161        if (end_of_path == 0) {
162          end_of_path = 1;
163        }
164        while (end_of_path < topLevel.Count) {
165          // last node in the path
166          int final = topLevel[end_of_path - 1];
167
168          // best_index stores the location of the best thing in the top level
169          int best_index = end_of_path;
170          double min_dist = distances[final][topLevel[best_index]];
171          // check all options which might be closer to "final" than "topLevel[best_index]"
172          for (int option = end_of_path + 1; option < topLevel.Count; option++) {
173            if (distances[final][topLevel[option]] < min_dist) {
174              min_dist = distances[final][topLevel[option]];
175              best_index = option;
176            }
177          }
178          // If the current last two in the path are minimally distant
179          if (end_of_path > 1 && min_dist >= distances[final][topLevel[end_of_path - 2]]) {
180            break;
181          }
182
183          // move the best to the end of the path
184          topLevel.Swap(end_of_path, best_index);
185          end_of_path++;
186        }
187        // Last two elements in the path are the clusters to join
188        int first = topLevel[end_of_path - 2];
189        int second = topLevel[end_of_path - 1];
190
191        // Only keep a cluster if the distance between the joining clusters is > zero
192        bool keep = !distances[first][second].IsAlmost(0.0);
193        useful[first] = keep;
194        useful[second] = keep;
195
196        // create the new cluster
197        clusters[index] = clusters[first].Concat(clusters[second]).ToList();
198        // Calculate distances from all clusters to the newly created cluster
199        int i = 0;
200        int end = topLevel.Count - 1;
201        while (i <= end) {
202          int x = topLevel[i];
203          // Moves 'first' and 'second' to after "end" in topLevel
204          if (x == first || x == second) {
205            topLevel.Swap(i, end);
206            end--;
207            continue;
208          }
209          // Use the previous distances to calculate the joined distance
210          double first_distance = distances[first][x];
211          first_distance *= clusters[first].Count;
212          double second_distance = distances[second][x];
213          second_distance *= clusters[second].Count;
214          distances[x][index] = ((first_distance + second_distance)
215              / (clusters[first].Count + clusters[second].Count));
216          // make it symmetric
217          distances[index][x] = distances[x][index];
218          i++;
219        }
220
221        // Remove first and second from the path
222        end_of_path -= 2;
223        topLevel.RemoveAt(topLevel.Count - 1);
224        topLevel[topLevel.Count - 1] = index;
225      }
226      // Extract the useful clusters
227      clusterOrdering.Clear();
228      // Add all useful clusters. The last one is never useful.
229      for (int i = 0; i < useful.Length - 1; i++) {
230        if (useful[i]) clusterOrdering.Add(i);
231      }
232
233      // Shuffle before sort to ensure ties are broken randomly
234      clusterOrdering.ShuffleInPlace(rand);
235      clusterOrdering = clusterOrdering.OrderBy(i => clusters[i].Count).ToList();
236    }
237
238    public IEnumerable<List<int>> Clusters {
239      get {
240        // Just in time rebuilding
241        if (rebuildRequired) Rebuild();
242        foreach (var index in clusterOrdering) {
243          // Send out the clusters in the desired order
244          yield return clusters[index];
245        }
246      }
247    }
248  }
249}
Note: See TracBrowser for help on using the repository browser.