En yakın komşuları aramak için benim kanaatimce en uygun olanı Spatial Grid Bucketing veya Locality sensitive hashing.
Design A Location Based Service videosu da faydalı
Aşağıdaki anlatıda Spatial Grid Bucketing ve 2D Arrays / Nested TreeMap kullanılıyor.
Locality Sensitive Hashing (LSH) vs Spatial Grid Bucketing (and Space-Filling Curves)
Açıklaması şöyle
Spatial Grid Bucketing (and Space-Filling Curves)What it is: Partitioning a 2D/3D coordinate space into fixed or hierarchical cells/chunks (or mapping grid cells onto a 1D line via Z-order / Geohash / Hilbert curves).How it works: Deterministic geometry. Given (x, y) or (lat, lon), you compute a cell ID, chunk index, or curve code directly from the coordinates.Key property & catch: It preserves grid/coordinate proximity, but grid boundaries cut across neighborhoods—so a point just across a cell or chunk border lands in a different bucket, forcing you to check neighboring cells or run multiple range scans.Locality Sensitive Hashing (LSH)What it is: A family of probabilistic hashing techniques designed for approximate nearest neighbor (ANN) search, typically in high-dimensional spaces (embeddings, vectors, documents, images)—not just 2D map coordinates.How it works: Uses hash functions chosen so that similar items (by cosine similarity, Euclidean distance, Jaccard similarity, etc.) have a high probability of hashing to the same bucket, while dissimilar items have a low probability. To boost recall, LSH typically uses multiple hash tables / multiple hash functions and accepts some false positives and misses (it's approximate, not an exact spatial grid).
1.1. Cell döndüren Hash Fonksiyon
Elimizdeki nesnelerin koordinat bilgisini bir hash fonksiyonuna sokup hangi hücreye yerleşeceğine karar veriyoruz. Arama için hızlı bir yöntem. hash fonksiyonunun birbirlerine yakın nesneleri komşu hücrelere yerleştirmesi gerekiyor.
1.2 GeoHash Fonksion
1.2 GeoHash Fonksion
String döndürür. Önce binary bir string üretir daha sonra bu Base32 olarak kodeklenir
1D Space-Filling Curves in a B-Tree
Burada Enzo başka bir yöntem sunuyor.
Lombardi specifically argues against separate/nested two-axis range filtering and shows how to collapse 2D coordinates into a single 1D key (Z-order or Hilbert curve) so a standard 1D B-tree handles range queries directly.
Yani
He uses grid cells and squares in a very specific way rather than casual "spatial grid bucketing."How Lombardi Treats Grids vs. BucketingNo LSH: There is no discussion of probabilistic similarity hashing, multi-table hash buckets, or high-dimensional approximate nearest neighbor search.Grid cells as 1D B-tree keys (not array chunks): Lombardi starts with a 2D grid of cells, but his goal isn't putting points into fixed 2D/3D array buckets (chunks[x][y]) or running separate x and y range filters. Instead, he numbers every grid cell along a 1D space-filling curve—Z-order (Morton codes), Geohash (which turns shared prefixes into aligned square boxes), and Hilbert curves—so a standard 1D B-tree can query squares as sorted key ranges.Coarse cells for fewer B-tree seeks: In his later sections ("Every square is a run of keys" and "Coarse cells, fewer seeks"), squares/cells act as range boundaries in the B-tree index, trading cell granularity against how many separate B-tree range seeks a query has to perform.
2. Verinin Saklanması
2.1 Matrix Şeklinde Spatial Grid Bucketing
Matrix'in en zor tarafı hücre bulunduktan sonra etrafındaki hücreleri de dolaşmak. Bu kod parçasında matrix'in dışına taşıp IndexOutOfBounds tipi bir exception alma ihtimaline karşı dikkatli kodlamak gerekiyor.
Örnek - Etraftaki Hücreleri Dolaşmak
Elimizde iki boyutlu bir dünya olsun
Cell[][] cells;Şöyle yaparız
Optional<Cell> getCell(int x, int y) {
if(x >= 0 && x < width && y >= 0 && y < height) {
return Optional.of(cells[y][x]);
}
return Optional.empty();
}
List<Cell> getCellNeighbours(Cell cell) {
List<Optional<Cell>> neighbours = new ArrayList<>();
neighbours.add(getCell(cell.x, cell.y+1)); // TOP
neighbours.add(getCell(cell.x, cell.y-1)); // BOTTOM
neighbours.add(getCell(cell.x-1, cell.y)); // LEFT
neighbours.add(getCell(cell.x+1, cell.y)); // RIGHT
return neighbours.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}Örnek - 3 boyutlu dünya
Eğer dünya koordinatımız eksi değerlere de sahip olsaydı (mesela -10,000 , 10,000 arasında) şöyle yaparız. Önce 1 satırında offset değerini ekleyerek eksi değerleri artı hale getiririz. Daha sonra 2 satırında ChunkSize'lara böleriz. Mesela X,Y ve Z için chunksize 100 kabul edilebilir. Bu durumda her chunk merkezi arasında 1000 birimlik mesafe olur
Chunk GetChunkForWorldPosition(Vector3 position) {
float offset = WorldWidth * 0.5; //1
int x = (int)Math.Floor((position.x + offset) / ChunkSizeX); //2
int y = (int)Math.Floor((position.y + offset) / ChunkSizeY);
int z = (int)Math.Floor((position.z + offset) / ChunkSizeZ);
return chunks[x][y][z];
}Örnek - İki Boyutlu Dünya
Açıklaması şöyle
Imagine a 2D example. You have a 2D world where each chunk contains 10 x 10 pixels. At the world level you want to access the pixel data for pixel (342,103). First you need to find the chunk that contains the data. You can easily find that because you know each chunk contains 10 x 10 pixels. To get chunk coordinates, just divide by the number of pixels per chunk, (int)342/10 = 34 and (int)103/10 = 10, giving you chunk (34,10).Now you just need to get the coordinates within the chunk. Those coordinates can easily be found by getting the remainder after the division, i.e. a modulo operation. 342%10 = 2 and 103%10 = 3, giving you pixel (2,3).That means world position (342,103) can be found in chunk (34,10) at position (2,3).
2.2. Tree Şeklinde Spatial Grid Bucketing
Java'da TreeMap kullanarak hücreleri sıralı tutmak ve daha sonra xmin, xmax arasında kalan (örneğin 2 enlem arası) ve daha sonra ymin, ymax (iki boylam arası) değerleri dolaşmak mümkün.TreeMap<Integer, TreeMap<Integer, Integer>> values;
for (int x : values.subMap(xmin, xmax).keySet()) {
for (int y : values.get(x).subMap(ymin, ymax).values()) {
// y here, represents the values of points in range...
}
}3. Diğer
3.1 Zaman İçin HashingLocality zaman için de kullanılabilir. Örnekte birbirlerine yakın zamanlar aynı kümeye ekleniyor.
Örnek - Birbirlerine en yakın zamanları eşleştirmemodel.get_time_bucket(seconds) {returnfloor(self.timestamp / seconds); }
Eğer birbirlerine en yakın zamanları eşleştirmek istersek şöyle yapabiliriz.
//compute reasonably aligned pairsvarmax_tolerable_offset =500;//do not match more then 500 miliseconds distant onesDictionary<long,long> alignedPairs =newDictionary<long,long>();foreach(vars in s_timestamps) {//for every timestamp in first timeline find the nearest one from rvarnearest_r = r_timestamps.OrderBy(r =>Math.Abs(r - s)).First();//if that is closer than allowed offsetif((Math.Abs(nearest_r - s)) <= max_tolerable_offset *10000) {//so now I need to find nearest s mark for this r markvarclosest_s = s_timestamps.OrderBy(s=>Math.Abs(s- nearest_r )).First();//if they are mutually in love, marry themif(closest_s == s) alignedPairs.Add(s, nearest_r); } }

Hiç yorum yok:
Yorum Gönder