Debian Codegraph @

src/main/org/h2/tools/MultiDimension.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.tools;
7
8 import java.sql.PreparedStatement;
9 import java.sql.ResultSet;
10 import java.sql.SQLException;
11 import java.util.ArrayList;
12 import java.util.Comparator;
13 import org.h2.util.StringUtils;
14
15 /**
16 * A tool to help an application execute multi-dimensional range queries.
17 * The algorithm used is database independent, the only requirement
18 * is that the engine supports a range index (for example b-tree).
19 */
20 public class MultiDimension implements Comparator<long[]> {
21
22 private static final MultiDimension INSTANCE = new MultiDimension();
23
24 protected MultiDimension() {
25 // don't allow construction by normal code
26 // but allow tests
27 }
28
29 /**
30 * Get the singleton.
31 *
32 * @return the singleton
33 */
34 public static MultiDimension getInstance() {
35 return INSTANCE;
36 }
37
38 /**
39 * Normalize a value so that it is between the minimum and maximum for the
40 * given number of dimensions.
41 *
42 * @param dimensions the number of dimensions
43 * @param value the value (must be in the range min..max)
44 * @param min the minimum value
45 * @param max the maximum value (must be larger than min)
46 * @return the normalized value in the range 0..getMaxValue(dimensions)
47 */
48 public int normalize(int dimensions, double value, double min, double max) {
49 if (value < min || value > max) {
50 throw new IllegalArgumentException(min + "<" + value + "<" + max);
51 }
52 double x = (value - min) / (max - min);
53 return (int) (x * getMaxValue(dimensions));
54 }
55
56 /**
57 * Get the maximum value for the given dimension count. For two dimensions,
58 * each value must contain at most 32 bit, for 3: 21 bit, 4: 16 bit, 5: 12
59 * bit, 6: 10 bit, 7: 9 bit, 8: 8 bit.
60 *
61 * @param dimensions the number of dimensions
62 * @return the maximum value
63 */
64 public int getMaxValue(int dimensions) {
65 if (dimensions < 2 || dimensions > 32) {
66 throw new IllegalArgumentException(Integer.toString(dimensions));
67 }
68 int bitsPerValue = getBitsPerValue(dimensions);
69 return (int) ((1L << bitsPerValue) - 1);
70 }
71
72 private static int getBitsPerValue(int dimensions) {
73 return Math.min(31, 64 / dimensions);
74 }
75
76 /**
77 * Convert the multi-dimensional value into a one-dimensional (scalar)
78 * value. This is done by interleaving the bits of the values. Each values
79 * must be between 0 (including) and the maximum value for the given number
80 * of dimensions (getMaxValue, excluding). To normalize values to this
81 * range, use the normalize function.
82 *
83 * @param values the multi-dimensional value
84 * @return the scalar value
85 */
86 public long interleave(int... values) {
87 int dimensions = values.length;
88 long max = getMaxValue(dimensions);
89 int bitsPerValue = getBitsPerValue(dimensions);
90 long x = 0;
91 for (int i = 0; i < dimensions; i++) {
92 long k = values[i];
93 if (k < 0 || k > max) {
94 throw new IllegalArgumentException(0 + "<" + k + "<" + max);
95 }
96 for (int b = 0; b < bitsPerValue; b++) {
97 x |= (k & (1L << b)) << (i + (dimensions - 1) * b);
98 }
99 }
100 return x;
101 }
102
103 /**
104 * Convert the two-dimensional value into a one-dimensional (scalar) value.
105 * This is done by interleaving the bits of the values.
106 * Each values must be between 0 (including) and the maximum value
107 * for the given number of dimensions (getMaxValue, excluding).
108 * To normalize values to this range, use the normalize function.
109 *
110 * @param x the value of the first dimension, normalized
111 * @param y the value of the second dimension, normalized
112 * @return the scalar value
113 */
114 public long interleave(int x, int y) {
115 if (x < 0) {
116 throw new IllegalArgumentException(0 + "<" + x);
117 }
118 if (y < 0) {
119 throw new IllegalArgumentException(0 + "<" + y);
120 }
121 long z = 0;
122 for (int i = 0; i < 32; i++) {
123 z |= (x & (1L << i)) << i;
124 z |= (y & (1L << i)) << (i + 1);
125 }
126 return z;
127 }
128
129 /**
130 * Gets one of the original multi-dimensional values from a scalar value.
131 *
132 * @param dimensions the number of dimensions
133 * @param scalar the scalar value
134 * @param dim the dimension of the returned value (starting from 0)
135 * @return the value
136 */
137 public int deinterleave(int dimensions, long scalar, int dim) {
138 int bitsPerValue = getBitsPerValue(dimensions);
139 int value = 0;
140 for (int i = 0; i < bitsPerValue; i++) {
141 value |= (scalar >> (dim + (dimensions - 1) * i)) & (1L << i);
142 }
143 return value;
144 }
145
146 /**
147 * Generates an optimized multi-dimensional range query. The query contains
148 * parameters. It can only be used with the H2 database.
149 *
150 * @param table the table name
151 * @param columns the list of columns
152 * @param scalarColumn the column name of the computed scalar column
153 * @return the query
154 */
155 public String generatePreparedQuery(String table, String scalarColumn,
156 String[] columns) {
157 StringBuilder buff = new StringBuilder("SELECT D.* FROM ");
158 StringUtils.quoteIdentifier(buff, table).
159 append(" D, TABLE(_FROM_ BIGINT=?, _TO_ BIGINT=?) WHERE ");
160 StringUtils.quoteIdentifier(buff, scalarColumn).
161 append(" BETWEEN _FROM_ AND _TO_");
162 for (String col : columns) {
163 buff.append(" AND ");
164 StringUtils.quoteIdentifier(buff, col).
165 append("+1 BETWEEN ?+1 AND ?+1");
166 }
167 return buff.toString();
168 }
169
170 /**
171 * Executes a prepared query that was generated using generatePreparedQuery.
172 *
173 * @param prep the prepared statement
174 * @param min the lower values
175 * @param max the upper values
176 * @return the result set
177 * @throws SQLException on failure
178 */
179 public ResultSet getResult(PreparedStatement prep, int[] min, int[] max)
180 throws SQLException {
181 long[][] ranges = getMortonRanges(min, max);
182 int len = ranges.length;
183 Long[] from = new Long[len];
184 Long[] to = new Long[len];
185 for (int i = 0; i < len; i++) {
186 from[i] = ranges[i][0];
187 to[i] = ranges[i][1];
188 }
189 prep.setObject(1, from);
190 prep.setObject(2, to);
191 len = min.length;
192 for (int i = 0, idx = 3; i < len; i++) {
193 prep.setInt(idx++, min[i]);
194 prep.setInt(idx++, max[i]);
195 }
196 return prep.executeQuery();
197 }
198
199 /**
200 * Gets a list of ranges to be searched for a multi-dimensional range query
201 * where min &lt;= value &lt;= max. In most cases, the ranges will be larger
202 * than required in order to combine smaller ranges into one. Usually, about
203 * double as many points will be included in the resulting range.
204 *
205 * @param min the minimum value
206 * @param max the maximum value
207 * @return the list of ranges (low, high pairs)
208 */
209 private long[][] getMortonRanges(int[] min, int[] max) {
210 int len = min.length;
211 if (max.length != len) {
212 throw new IllegalArgumentException(len + "=" + max.length);
213 }
214 for (int i = 0; i < len; i++) {
215 if (min[i] > max[i]) {
216 int temp = min[i];
217 min[i] = max[i];
218 max[i] = temp;
219 }
220 }
221 int total = getSize(min, max, len);
222 ArrayList<long[]> list = new ArrayList<>();
223 addMortonRanges(list, min, max, len, 0);
224 combineEntries(list, total);
225 return list.toArray(new long[0][]);
226 }
227
228 private static int getSize(int[] min, int[] max, int len) {
229 int size = 1;
230 for (int i = 0; i < len; i++) {
231 int diff = max[i] - min[i];
232 size *= diff + 1;
233 }
234 return size;
235 }
236
237 /**
238 * Combine entries if the size of the list is too large.
239 *
240 * @param list list of pairs(low, high)
241 * @param total product of the gap lengths
242 */
243 private void combineEntries(ArrayList<long[]> list, int total) {
244 list.sort(this);
245 for (int minGap = 10; minGap < total; minGap += minGap / 2) {
246 for (int i = 0; i < list.size() - 1; i++) {
247 long[] current = list.get(i);
248 long[] next = list.get(i + 1);
249 if (current[1] + minGap >= next[0]) {
250 current[1] = next[1];
251 list.remove(i + 1);
252 i--;
253 }
254 }
255 int searched = 0;
256 for (long[] range : list) {
257 searched += range[1] - range[0] + 1;
258 }
259 if (searched > 2 * total || list.size() < 100) {
260 break;
261 }
262 }
263 }
264
265 @Override
266 public int compare(long[] a, long[] b) {
267 return a[0] > b[0] ? 1 : -1;
268 }
269
270 private void addMortonRanges(ArrayList<long[]> list, int[] min, int[] max,
271 int len, int level) {
272 if (level > 100) {
273 throw new IllegalArgumentException(Integer.toString(level));
274 }
275 int largest = 0, largestDiff = 0;
276 long size = 1;
277 for (int i = 0; i < len; i++) {
278 int diff = max[i] - min[i];
279 if (diff < 0) {
280 throw new IllegalArgumentException(Integer.toString(diff));
281 }
282 size *= diff + 1;
283 if (size < 0) {
284 throw new IllegalArgumentException(Long.toString(size));
285 }
286 if (diff > largestDiff) {
287 largestDiff = diff;
288 largest = i;
289 }
290 }
291 long low = interleave(min), high = interleave(max);
292 if (high < low) {
293 throw new IllegalArgumentException(high + "<" + low);
294 }
295 long range = high - low + 1;
296 if (range == size) {
297 long[] item = { low, high };
298 list.add(item);
299 } else {
300 int middle = findMiddle(min[largest], max[largest]);
301 int temp = max[largest];
302 max[largest] = middle;
303 addMortonRanges(list, min, max, len, level + 1);
304 max[largest] = temp;
305 temp = min[largest];
306 min[largest] = middle + 1;
307 addMortonRanges(list, min, max, len, level + 1);
308 min[largest] = temp;
309 }
310 }
311
312 private static int roundUp(int x, int blockSizePowerOf2) {
313 return (x + blockSizePowerOf2 - 1) & -blockSizePowerOf2;
314 }
315
316 private static int findMiddle(int a, int b) {
317 int diff = b - a - 1;
318 if (diff == 0) {
319 return a;
320 }
321 if (diff == 1) {
322 return a + 1;
323 }
324 int scale = 0;
325 while ((1 << scale) < diff) {
326 scale++;
327 }
328 scale--;
329 int m = roundUp(a + 2, 1 << scale) - 1;
330 if (m <= a || m >= b) {
331 throw new IllegalArgumentException(a + "<" + m + "<" + b);
332 }
333 return m;
334 }
335
336 }