Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/TSNE/SpacePartitioningTree.cs @ 14927

Last change on this file since 14927 was 14862, checked in by gkronber, 8 years ago

#2700 copied tSNE from branch to trunk

File size: 12.2 KB
RevLine 
[14414]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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
21//Code is based on an implementation from Laurens van der Maaten
22
23/*
24*
25* Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology)
26* All rights reserved.
27*
28* Redistribution and use in source and binary forms, with or without
29* modification, are permitted provided that the following conditions are met:
30* 1. Redistributions of source code must retain the above copyright
31*    notice, this list of conditions and the following disclaimer.
32* 2. Redistributions in binary form must reproduce the above copyright
33*    notice, this list of conditions and the following disclaimer in the
34*    documentation and/or other materials provided with the distribution.
35* 3. All advertising materials mentioning features or use of this software
36*    must display the following acknowledgement:
37*    This product includes software developed by the Delft University of Technology.
38* 4. Neither the name of the Delft University of Technology nor the names of
39*    its contributors may be used to endorse or promote products derived from
40*    this software without specific prior written permission.
41*
42* THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS
43* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
44* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
45* EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
47* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
48* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
49* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
50* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
51* OF SUCH DAMAGE.
52*
53*/
54#endregion
55
56using System;
57using System.Collections.Generic;
58using System.Linq;
59using HeuristicLab.Common;
60
61namespace HeuristicLab.Algorithms.DataAnalysis {
[14783]62  /// <summary>
[14785]63  /// Space partitioning tree (SPTree)
[14783]64  /// </summary>
[14787]65  public class SpacePartitioningTree : ISpacePartitioningTree {
[14414]66    private const uint QT_NODE_CAPACITY = 1;
67
68    private double[] buff;
[14785]69    private SpacePartitioningTree parent;
[14414]70    private int dimension;
71    private bool isLeaf;
72    private uint size;
73    private uint cumulativeSize;
74
75    // Axis-aligned bounding box stored as a center with half-dimensions to represent the boundaries of this quad tree
[14787]76    private Cell boundary;
[14414]77
[14806]78    private double[,] data;
[14787]79
[14855]80    // Indices in this space-partitioning tree node, corresponding center-of-mass, and list of all children
[14414]81    private double[] centerOfMass;
[14787]82    private readonly int[] index = new int[QT_NODE_CAPACITY];
[14414]83
84    // Children
[14785]85    private SpacePartitioningTree[] children;
[14414]86    private uint noChildren;
87
[14785]88    public SpacePartitioningTree(double[,] inpData) {
[14414]89      var d = inpData.GetLength(1);
90      var n = inpData.GetLength(0);
91      var meanY = new double[d];
92      var minY = new double[d];
[14855]93      for (var i = 0; i < d; i++) minY[i] = double.MaxValue;
[14414]94      var maxY = new double[d];
[14855]95      for (var i = 0; i < d; i++) maxY[i] = double.MinValue;
96      for (uint i = 0; i < n; i++) {
97        for (uint j = 0; j < d; j++) {
98          meanY[j] += inpData[i, j];
99          if (inpData[i, j] < minY[j]) minY[j] = inpData[i, j];
100          if (inpData[i, j] > maxY[j]) maxY[j] = inpData[i, j];
[14414]101        }
102      }
[14855]103      for (var i = 0; i < d; i++) meanY[i] /= n;
[14414]104      var width = new double[d];
[14855]105      for (var i = 0; i < d; i++) width[i] = Math.Max(maxY[i] - meanY[i], meanY[i] - minY[i]) + 1e-5;
[14414]106      Init(null, inpData, meanY, width);
107      Fill(n);
108    }
109
[14785]110    public SpacePartitioningTree(double[,] inpData, IEnumerable<double> impCorner, IEnumerable<double> impWith) {
[14414]111      Init(null, inpData, impCorner, impWith);
112    }
[14785]113    public SpacePartitioningTree(SpacePartitioningTree parent, double[,] inpData, IEnumerable<double> impCorner, IEnumerable<double> impWith) {
[14414]114      Init(parent, inpData, impCorner, impWith);
115    }
116
[14785]117    public ISpacePartitioningTree GetParent() {
[14414]118      return parent;
119    }
120
121    public bool Insert(int newIndex) {
122      // Ignore objects which do not belong in this quad tree
123      var point = new double[dimension];
[14806]124      Buffer.BlockCopy(data, sizeof(double) * dimension * newIndex, point, 0, sizeof(double) * dimension);
[14855]125      if (!boundary.ContainsPoint(point)) return false;
[14414]126      cumulativeSize++;
127      // Online update of cumulative size and center-of-mass
128      var mult1 = (double)(cumulativeSize - 1) / cumulativeSize;
129      var mult2 = 1.0 / cumulativeSize;
[14855]130      for (var i = 0; i < dimension; i++) centerOfMass[i] *= mult1;
131      for (var i = 0; i < dimension; i++) centerOfMass[i] += mult2 * point[i];
[14414]132
133      // If there is space in this quad tree and it is a leaf, add the object here
[14855]134      if (isLeaf && size < QT_NODE_CAPACITY) {
[14414]135        index[size] = newIndex;
136        size++;
137        return true;
138      }
139
140      // Don't add duplicates for now (this is not very nice)
141      var anyDuplicate = false;
[14855]142      for (uint n = 0; n < size; n++) {
[14414]143        var duplicate = true;
[14855]144        for (var d = 0; d < dimension; d++) {
145          if (Math.Abs(point[d] - data[index[n], d]) < double.Epsilon) continue;
[14414]146          duplicate = false; break;
147        }
148        anyDuplicate = anyDuplicate | duplicate;
149      }
[14855]150      if (anyDuplicate) return true;
[14414]151
152      // Otherwise, we need to subdivide the current cell
[14855]153      if (isLeaf) Subdivide();
[14414]154      // Find out where the point can be inserted
[14855]155      for (var i = 0; i < noChildren; i++) {
156        if (children[i].Insert(newIndex)) return true;
[14414]157      }
158
159      // Otherwise, the point cannot be inserted (this should never happen)
160      return false;
161    }
162
163    public void Subdivide() {
164      // Create new children
165      var newCorner = new double[dimension];
166      var newWidth = new double[dimension];
[14855]167      for (var i = 0; i < noChildren; i++) {
[14414]168        var div = 1;
[14855]169        for (var d = 0; d < dimension; d++) {
[14414]170          newWidth[d] = .5 * boundary.GetWidth(d);
[14855]171          if ((i / div) % 2 == 1) newCorner[d] = boundary.GetCorner(d) - .5 * boundary.GetWidth(d);
[14414]172          else newCorner[d] = boundary.GetCorner(d) + .5 * boundary.GetWidth(d);
173          div *= 2;
174        }
[14806]175        children[i] = new SpacePartitioningTree(this, data, newCorner, newWidth);
[14414]176      }
177
178      // Move existing points to correct children
[14855]179      for (var i = 0; i < size; i++) {
[14414]180        var success = false;
[14855]181        for (var j = 0; j < noChildren; j++) {
182          if (!success) success = children[j].Insert(index[i]);
[14414]183        }
[14855]184        index[i] = -1; // as in tSNE implementation by van der Maaten
[14414]185      }
186
187      // Empty parent node
188      size = 0;
189      isLeaf = false;
190    }
191
192    public bool IsCorrect() {
193      var row = new double[dimension];
[14855]194      for (var n = 0; n < size; n++) {
195        Buffer.BlockCopy(data, sizeof(double) * dimension * index[n], row, 0, sizeof(double) * dimension);
196        if (!boundary.ContainsPoint(row)) return false;
197      }
198      if (isLeaf) return true;
[14414]199      var correct = true;
[14855]200      for (var i = 0; i < noChildren; i++) correct = correct && children[i].IsCorrect();
[14414]201      return correct;
202    }
203
204    public void GetAllIndices(int[] indices) {
205      GetAllIndices(indices, 0);
206    }
207
208    public int GetAllIndices(int[] indices, int loc) {
209      // Gather indices in current quadrant
[14855]210      for (var i = 0; i < size; i++) indices[loc + i] = index[i];
[14414]211      loc += (int)size;
212      // Gather indices in children
[14855]213      if (isLeaf) return loc;
214      for (var i = 0; i < noChildren; i++) loc = children[i].GetAllIndices(indices, loc);
[14414]215      return loc;
216    }
217
218    public int GetDepth() {
219      return isLeaf ? 1 : 1 + children.Max(x => x.GetDepth());
220    }
221
[14806]222    public void ComputeNonEdgeForces(int pointIndex, double theta, double[] negF, ref double sumQ) {
[14414]223      // Make sure that we spend no time on empty nodes or self-interactions
[14855]224      if (cumulativeSize == 0 || (isLeaf && size == 1 && index[0] == pointIndex)) return;
[14414]225
226      // Compute distance between point and center-of-mass
227      var D = .0;
[14855]228      for (var d = 0; d < dimension; d++) buff[d] = data[pointIndex, d] - centerOfMass[d];
229      for (var d = 0; d < dimension; d++) D += buff[d] * buff[d];
[14414]230
231      // Check whether we can use this node as a "summary"
232      var maxWidth = 0.0;
[14855]233      for (var d = 0; d < dimension; d++) {
[14414]234        var curWidth = boundary.GetWidth(d);
235        maxWidth = (maxWidth > curWidth) ? maxWidth : curWidth;
236      }
[14855]237      if (isLeaf || maxWidth / Math.Sqrt(D) < theta) {
[14414]238
239        // Compute and add t-SNE force between point and current node
240        D = 1.0 / (1.0 + D);
241        var mult = cumulativeSize * D;
[14788]242        sumQ += mult;
[14414]243        mult *= D;
[14855]244        for (var d = 0; d < dimension; d++) negF[d] += mult * buff[d];
[14414]245      } else {
246
247        // Recursively apply Barnes-Hut to children
[14855]248        for (var i = 0; i < noChildren; i++) children[i].ComputeNonEdgeForces(pointIndex, theta, negF, ref sumQ);
[14414]249      }
250    }
251
[14858]252    // does not use the tree
[14414]253    public void ComputeEdgeForces(int[] rowP, int[] colP, double[] valP, int n, double[,] posF) {
254      // Loop over all edges in the graph
[14855]255      for (var k = 0; k < n; k++) {
256        for (var i = rowP[k]; i < rowP[k + 1]; i++) {
[14414]257
258          // Compute pairwise distance and Q-value
[14806]259          // uses squared distance
[14414]260          var d = 1.0;
[14855]261          for (var j = 0; j < dimension; j++) buff[j] = data[k, j] - data[colP[i], j];
262          for (var j = 0; j < dimension; j++) d += buff[j] * buff[j];
[14414]263          d = valP[i] / d;
264
265          // Sum positive force
[14855]266          for (var j = 0; j < dimension; j++) posF[k, j] += d * buff[j];
[14414]267        }
268      }
269    }
270
271    #region Helpers
272    private void Fill(int n) {
[14855]273      for (var i = 0; i < n; i++) Insert(i);
[14414]274    }
[14785]275    private void Init(SpacePartitioningTree p, double[,] inpData, IEnumerable<double> inpCorner, IEnumerable<double> inpWidth) {
[14414]276      parent = p;
277      dimension = inpData.GetLength(1);
278      noChildren = 2;
[14855]279      for (uint i = 1; i < dimension; i++) noChildren *= 2;
[14806]280      data = inpData;
[14414]281      isLeaf = true;
282      size = 0;
283      cumulativeSize = 0;
284      boundary = new Cell((uint)dimension);
285      inpCorner.ForEach((i, x) => boundary.SetCorner(i, x));
286      inpWidth.ForEach((i, x) => boundary.SetWidth(i, x));
287
[14785]288      children = new SpacePartitioningTree[noChildren];
[14414]289      centerOfMass = new double[dimension];
290      buff = new double[dimension];
291
292    }
293    #endregion
294
[14787]295
[14806]296    private class Cell {
[14787]297      private readonly uint dimension;
298      private readonly double[] corner;
299      private readonly double[] width;
300
301      public Cell(uint inpDimension) {
302        dimension = inpDimension;
303        corner = new double[dimension];
304        width = new double[dimension];
305      }
306
307      public double GetCorner(int d) {
308        return corner[d];
309      }
310      public double GetWidth(int d) {
311        return width[d];
312      }
313      public void SetCorner(int d, double val) {
314        corner[d] = val;
315      }
316      public void SetWidth(int d, double val) {
317        width[d] = val;
318      }
319      public bool ContainsPoint(double[] point) {
[14855]320        for (var d = 0; d < dimension; d++)
321          if (corner[d] - width[d] > point[d] || corner[d] + width[d] < point[d]) return false;
[14787]322        return true;
323      }
324    }
[14414]325  }
326}
Note: See TracBrowser for help on using the repository browser.