Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11733 was 11674, checked in by mkommend, 10 years ago

#2282: Performance improvements in PPP (reduced memory allocations and more efficient implementation).

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