Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Algorithms.ParameterlessPopulationPyramid/3.3/LinkageTree.cs @ 11975

Last change on this file since 11975 was 11939, checked in by mkommend, 10 years ago

#2282: Moved PPP into the trunk.

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