/
QuadPrefixTree.cs
385 lines (344 loc) · 14.3 KB
/
QuadPrefixTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
using Lucene.Net.Diagnostics;
using Spatial4n.Context;
using Spatial4n.Shapes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Spatial.Prefix.Tree
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A <see cref="SpatialPrefixTree"/> which uses a
/// <a href="http://en.wikipedia.org/wiki/Quadtree">quad tree</a> in which an
/// indexed term will be generated for each cell, 'A', 'B', 'C', 'D'.
/// <para/>
/// @lucene.experimental
/// </summary>
public class QuadPrefixTree : SpatialPrefixTree
{
// LUCENENET specific - de-nested Factory and renamed QuadPrefixTreeFactory
public const int MAX_LEVELS_POSSIBLE = 50;//not really sure how big this should be
public const int DEFAULT_MAX_LEVELS = 12;
private readonly double xmin;
private readonly double xmax;
private readonly double ymin;
private readonly double ymax;
private readonly double xmid;
private readonly double ymid;
private readonly double gridW;
public double GridH => gridH;
private readonly double gridH;
internal readonly double[] levelW;
internal readonly double[] levelH;
internal readonly int[] levelS; // side
internal readonly int[] levelN; // number
/// <summary>
/// Initializes a new instance of <see cref="QuadPrefixTree"/> with the specified
/// spatial context (<paramref name="ctx"/>), <paramref name="bounds"/> and <paramref name="maxLevels"/>.
/// </summary>
/// <param name="ctx">The spatial context.</param>
/// <param name="bounds">The bounded rectangle.</param>
/// <param name="maxLevels">The maximum number of levels in the tree.</param>
/// <exception cref="ArgumentNullException"><paramref name="ctx"/> or <paramref name="bounds"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxLevels"/> is less than or equal to 0.</exception>
public QuadPrefixTree(SpatialContext ctx, IRectangle bounds, int maxLevels)
: base(ctx, maxLevels)
{
// LUCENENET specific - added guard clause
if (bounds is null)
throw new ArgumentNullException(nameof(bounds));
xmin = bounds.MinX;
xmax = bounds.MaxX;
ymin = bounds.MinY;
ymax = bounds.MaxY;
levelW = new double[maxLevels];
levelH = new double[maxLevels];
levelS = new int[maxLevels];
levelN = new int[maxLevels];
gridW = xmax - xmin;
gridH = ymax - ymin;
this.xmid = xmin + gridW / 2.0;
this.ymid = ymin + gridH / 2.0;
levelW[0] = gridW / 2.0;
levelH[0] = gridH / 2.0;
levelS[0] = 2;
levelN[0] = 4;
for (int i = 1; i < levelW.Length; i++)
{
levelW[i] = levelW[i - 1] / 2.0;
levelH[i] = levelH[i - 1] / 2.0;
levelS[i] = levelS[i - 1] * 2;
levelN[i] = levelN[i - 1] * 4;
}
}
/// <summary>
/// Initializes a new instance of <see cref="QuadPrefixTree"/> with the specified
/// spatial context (<paramref name="ctx"/>).
/// </summary>
/// <param name="ctx">The spatial context.</param>
/// <exception cref="ArgumentNullException"><paramref name="ctx"/> is <c>null</c>.</exception>
public QuadPrefixTree(SpatialContext ctx)
: this(ctx, DEFAULT_MAX_LEVELS)
{
}
/// <summary>
/// Initializes a new instance of <see cref="QuadPrefixTree"/> with the specified
/// spatial context (<paramref name="ctx"/>) and <paramref name="maxLevels"/>.
/// </summary>
/// <param name="ctx">The spatial context.</param>
/// <param name="maxLevels">The maximum number of levels in the tree.</param>
/// <exception cref="ArgumentNullException"><paramref name="ctx"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxLevels"/> is less than or equal to 0.</exception>
public QuadPrefixTree(SpatialContext ctx, int maxLevels)
: this(ctx, ctx?.WorldBounds!, maxLevels)
{
}
public virtual void PrintInfo(TextWriter output)
{
// LUCENENET specific - added guard clause
if (output is null)
throw new ArgumentNullException(nameof(output));
// Format the number to min 3 integer digits and exactly 5 fraction digits
const string FORMAT_STR = @"000.00000";
for (int i = 0; i < m_maxLevels; i++)
{
output.WriteLine(i + "]\t" + levelW[i].ToString(FORMAT_STR) + "\t" + levelH[i].ToString(FORMAT_STR) + "\t" +
levelS[i] + "\t" + (levelS[i] * levelS[i]));
}
}
public override int GetLevelForDistance(double dist)
{
if (dist == 0)//short circuit
{
return m_maxLevels;
}
for (int i = 0; i < m_maxLevels - 1; i++)
{
//note: level[i] is actually a lookup for level i+1
if (dist > levelW[i] && dist > levelH[i])
{
return i + 1;
}
}
return m_maxLevels;
}
protected internal override Cell GetCell(IPoint p, int level)
{
// LUCENENET specific - added guard clause
if (p is null)
throw new ArgumentNullException(nameof(p));
IList<Cell> cells = new JCG.List<Cell>(1);
Build(xmid, ymid, 0, cells, new StringBuilder(), m_ctx.MakePoint(p.X, p.Y), level);
return cells[0];
}
//note cells could be longer if p on edge
public override Cell GetCell(string token)
{
return new QuadCell(this, token);
}
public override Cell GetCell(byte[] bytes, int offset, int length)
{
return new QuadCell(this, bytes, offset, length);
}
private void Build(
double x,
double y,
int level,
IList<Cell> matches,
StringBuilder str,
IShape shape,
int maxLevel)
{
if (Debugging.AssertsEnabled) Debugging.Assert(str.Length == level);
double w = levelW[level] / 2;
double h = levelH[level] / 2;
// Z-Order
// http://en.wikipedia.org/wiki/Z-order_%28curve%29
CheckBattenberg('A', x - w, y + h, level, matches, str, shape, maxLevel);
CheckBattenberg('B', x + w, y + h, level, matches, str, shape, maxLevel);
CheckBattenberg('C', x - w, y - h, level, matches, str, shape, maxLevel);
CheckBattenberg('D', x + w, y - h, level, matches, str, shape, maxLevel);
}
// possibly consider hilbert curve
// http://en.wikipedia.org/wiki/Hilbert_curve
// http://blog.notdot.net/2009/11/Damn-Cool-Algorithms-Spatial-indexing-with-Quadtrees-and-Hilbert-Curves
// if we actually use the range property in the query, this could be useful
private void CheckBattenberg(
char c,
double cx,
double cy,
int level,
IList<Cell> matches,
StringBuilder str,
IShape shape,
int maxLevel)
{
if (Debugging.AssertsEnabled) Debugging.Assert(str.Length == level);
double w = levelW[level] / 2;
double h = levelH[level] / 2;
int strlen = str.Length;
IRectangle rectangle = m_ctx.MakeRectangle(cx - w, cx + w, cy - h, cy + h);
SpatialRelation v = shape.Relate(rectangle);
if (SpatialRelation.Contains == v)
{
str.Append(c);
//str.append(SpatialPrefixGrid.COVER);
matches.Add(new QuadCell(this, str.ToString(), v.Transpose()));
}
else if (SpatialRelation.Disjoint == v)
{
// nothing
}
else // SpatialRelation.WITHIN, SpatialRelation.INTERSECTS
{
str.Append(c);
int nextLevel = level + 1;
if (nextLevel >= maxLevel)
{
//str.append(SpatialPrefixGrid.INTERSECTS);
matches.Add(new QuadCell(this, str.ToString(), v.Transpose()));
}
else
{
Build(cx, cy, nextLevel, matches, str, shape, maxLevel);
}
}
str.Length = strlen;
}
#region Nested type: QuadCell
internal class QuadCell : Cell
{
public QuadCell(QuadPrefixTree outerInstance, string token)
: base(outerInstance, token)
{
}
public QuadCell(QuadPrefixTree outerInstance, string token, SpatialRelation shapeRel)
: base(outerInstance, token)
{
this.m_shapeRel = shapeRel;
}
internal QuadCell(QuadPrefixTree outerInstance, byte[] bytes, int off, int len)
: base(outerInstance, bytes, off, len)
{
}
public override void Reset(byte[] bytes, int off, int len)
{
base.Reset(bytes, off, len);
shape = null;
}
protected internal override ICollection<Cell> GetSubCells()
{
QuadPrefixTree outerInstance = (QuadPrefixTree)this.m_spatialPrefixTree;
return new JCG.List<Cell>(4)
{
new QuadCell(outerInstance, TokenString + "A"),
new QuadCell(outerInstance, TokenString + "B"),
new QuadCell(outerInstance, TokenString + "C"),
new QuadCell(outerInstance, TokenString + "D")
};
}
public override int SubCellsSize => 4;
public override Cell GetSubCell(IPoint p)
{
return m_spatialPrefixTree.GetCell(p, Level + 1);//not performant!
}
private IShape? shape; //cache
public override IShape Shape
{
get
{
if (shape is null)
{
shape = MakeShape();
}
return shape;
}
}
private IRectangle MakeShape()
{
QuadPrefixTree outerInstance = (QuadPrefixTree)this.m_spatialPrefixTree;
string token = TokenString;
double xmin = outerInstance.xmin;
double ymin = outerInstance.ymin;
for (int i = 0; i < token.Length; i++)
{
char c = token[i];
if ('A' == c || 'a' == c)
{
ymin += outerInstance.levelH[i];
}
else if ('B' == c || 'b' == c)
{
xmin += outerInstance.levelW[i];
ymin += outerInstance.levelH[i];
}
else if ('C' == c || 'c' == c)
{
// nothing really
}
else if ('D' == c || 'd' == c)
{
xmin += outerInstance.levelW[i];
}
else
{
throw RuntimeException.Create("unexpected char: " + c);
}
}
int len = token.Length;
double width;
double height;
if (len > 0)
{
width = outerInstance.levelW[len - 1];
height = outerInstance.levelH[len - 1];
}
else
{
width = outerInstance.gridW;
height = outerInstance.gridH;
}
return outerInstance.m_ctx.MakeRectangle(xmin, xmin + width, ymin, ymin + height);
}
}//QuadCell
#endregion
}
/// <summary>
/// Factory for creating <see cref="QuadPrefixTree"/> instances with useful defaults
/// </summary>
public class QuadPrefixTreeFactory : SpatialPrefixTreeFactory
{
protected internal override int GetLevelForDistance(double degrees)
{
// LUCENENET specific - added guard clause
if (m_ctx is null)
throw new InvalidOperationException($"{nameof(m_ctx)} must be set prior to calling GetLevelForDistance(double).");
var grid = new QuadPrefixTree(m_ctx, QuadPrefixTree.MAX_LEVELS_POSSIBLE);
return grid.GetLevelForDistance(degrees);
}
protected internal override SpatialPrefixTree NewSPT()
{
// LUCENENET specific - added guard clause
if (m_ctx is null)
throw new InvalidOperationException($"{nameof(m_ctx)} must be set prior to calling NewSPT().");
return new QuadPrefixTree(m_ctx, m_maxLevels ?? QuadPrefixTree.MAX_LEVELS_POSSIBLE);
}
}
}