Free cookie consent management tool by TermsFeed Policy Generator

source: branches/TSNE/HeuristicLab.Algorithms.DataAnalysis/3.4/TSNE/VPTree.cs @ 14783

Last change on this file since 14783 was 14783, checked in by gkronber, 7 years ago

#2700 renamed EuclideanDistance and added some comments

File size: 9.2 KB
Line 
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;
60using HeuristicLab.Core;
61using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
62using HeuristicLab.Random;
63
64namespace HeuristicLab.Algorithms.DataAnalysis {
65  /// <summary>
66  /// Vantage point tree  (or VP tree) is a metric tree that segregates data in a metric space by choosing
67  /// a position in the space (the "vantage point") and partitioning the data points into two parts:
68  /// those points that are nearer to the vantage point than a threshold, and those points that are not.
69  /// By recursively applying this procedure to partition the data into smaller and smaller sets, a tree
70  /// data structure is created where neighbors in the tree are likely to be neighbors in the space.
71  /// </summary>
72  /// <typeparam name="T"></typeparam>
73  [StorableClass]
74  public class VPTree<T> : DeepCloneable, IVPTree<T> where T : class, IDeepCloneable {
75    #region properties
76    [Storable]
77    private List<T> items;
78    [Storable]
79    private double tau;
80    [Storable]
81    private Node root;
82    [Storable]
83    private IDistance<T> distance;
84    #endregion
85
86    #region HLConstructors & Cloning
87    [StorableConstructor]
88    protected VPTree(bool deserializing) { }
89    protected VPTree(VPTree<T> original, Cloner cloner)
90      : base(original, cloner) {
91      items = original.items.Select(cloner.Clone).ToList();
92      tau = original.tau;
93      root = cloner.Clone(original.root);
94      distance = cloner.Clone(distance);
95    }
96    public override IDeepCloneable Clone(Cloner cloner) { return new VPTree<T>(this, cloner); }
97    public VPTree(IDistance<T> distance) {
98      root = null;
99      this.distance = distance;
100    }
101    #endregion
102
103    public void Create(IEnumerable<T> items) {
104      this.items = items.Select(x => x).ToList();
105      root = BuildFromPoints(0, this.items.Count);
106    }
107
108    public void Search(T target, int k, out List<T> results, out List<double> distances) {
109      var heap = new PriorityQueue<double, HeapItem>(double.MaxValue, double.MinValue, k);
110      tau = double.MaxValue;
111      Search(root, target, k, heap);
112      results = new List<T>();
113      distances = new List<double>();
114      while (heap.Size > 0) {
115        results.Add(items[heap.PeekMinValue().Index]);
116        distances.Add(heap.PeekMinValue().Dist);
117        heap.RemoveMin();
118      }
119      results.Reverse();
120      distances.Reverse();
121    }
122
123    private Node BuildFromPoints(int lower, int upper) {
124      if (upper == lower)      // indicates that we're done here!
125        return null;
126
127      // Lower index is center of current node
128      var node = new Node { index = lower };
129      var r = new MersenneTwister(); //outer behaviour does not change with the random seed => no need to take the IRandom from the algorithm
130      if (upper - lower <= 1) return node; // if we did not arrive at leaf yet
131
132      // Choose an arbitrary point and move it to the start
133      var i = (int)(r.NextDouble() / 1 * (upper - lower - 1)) + lower;
134      items.Swap(lower, i);
135
136      // Partition around the median distance
137      var median = (upper + lower) / 2;
138      items.NthElement(lower + 1, upper - 1, median, distance.GetDistanceComparer(items[lower]));
139
140      // Threshold of the new node will be the distance to the median
141      node.threshold = distance.Get(items[lower], items[median]);
142
143      // Recursively build tree
144      node.index = lower;
145      node.left = BuildFromPoints(lower + 1, median);
146      node.right = BuildFromPoints(median, upper);
147
148      // Return result
149      return node;
150    }
151
152    private void Search(Node node, T target, int k, PriorityQueue<double, HeapItem> heap) {
153      if (node == null) return;
154      var dist = distance.Get(items[node.index], target);
155      if (dist < tau) {
156        if (heap.Size == k) heap.RemoveMin();
157        heap.Insert(-dist, new HeapItem(node.index, dist));//TODO check if minheap or maxheap should be used here
158        if (heap.Size == k) tau = heap.PeekMinValue().Dist;
159      }
160      if (node.left == null && node.right == null) return;
161
162      if (dist < node.threshold) {
163        if (dist - tau <= node.threshold) Search(node.left, target, k, heap);   // if there can still be neighbors inside the ball, recursively search left child first
164        if (dist + tau >= node.threshold) Search(node.right, target, k, heap);  // if there can still be neighbors outside the ball, recursively search right child
165      } else {
166        if (dist + tau >= node.threshold) Search(node.right, target, k, heap);  // if there can still be neighbors outside the ball, recursively search right child first
167        if (dist - tau <= node.threshold) Search(node.left, target, k, heap);   // if there can still be neighbors inside the ball, recursively search left child
168      }
169
170    }
171
172    [StorableClass]
173    private sealed class Node : Item {
174      [Storable]
175      public int index;
176      [Storable]
177      public double threshold;
178      [Storable]
179      public Node left;
180      [Storable]
181      public Node right;
182
183      #region HLConstructors & Cloning
184      [StorableConstructor]
185      private Node(bool deserializing) : base(deserializing) { }
186      private Node(Node original, Cloner cloner) : base(original, cloner) {
187        index = original.index;
188        threshold = original.threshold;
189        left = (Node)original.left.Clone(cloner);
190        right = (Node)original.right.Clone(cloner);
191      }
192      internal Node() {
193        index = 0;
194        threshold = 0;
195        left = null;
196        right = null;
197      }
198      public override IDeepCloneable Clone(Cloner cloner) {
199        return new Node(this, cloner);
200      }
201      #endregion
202    }
203
204    [StorableClass]
205    private sealed class HeapItem : Item, IComparable<HeapItem> {
206      [Storable]
207      public int Index;
208      [Storable]
209      public double Dist;
210
211      #region HLConstructors & Cloning
212      [StorableConstructor]
213      private HeapItem(bool deserializing) : base(deserializing) { }
214      private HeapItem(HeapItem original, Cloner cloner)
215      : base(original, cloner) {
216        Index = original.Index;
217        Dist = original.Dist;
218      }
219      public override IDeepCloneable Clone(Cloner cloner) { return new HeapItem(this, cloner); }
220      public HeapItem(int index, double dist) {
221        Index = index;
222        Dist = dist;
223      }
224      #endregion
225
226      public int CompareTo(HeapItem other) {
227        return Dist.CompareTo(Dist);
228      }
229    }
230  }
231}
Note: See TracBrowser for help on using the repository browser.