summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/common/geo/GeoDistance.java
blob: 2a31596eab94a2b0ebc79cb95fef014bfd3b01cb (plain)
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.
 */

package org.elasticsearch.common.geo;

import org.apache.lucene.util.Bits;
import org.apache.lucene.util.SloppyMath;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.GeoPointValues;
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
import org.elasticsearch.index.fielddata.NumericDoubleValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.index.fielddata.SortingNumericDoubleValues;
import java.io.IOException;
import java.util.Locale;

/**
 * Geo distance calculation.
 */
public enum GeoDistance implements Writeable<GeoDistance> {
    /**
     * Calculates distance as points on a plane. Faster, but less accurate than {@link #ARC}.
     */
    PLANE {
        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            double px = targetLongitude - sourceLongitude;
            double py = targetLatitude - sourceLatitude;
            return Math.sqrt(px * px + py * py) * unit.getDistancePerDegree();
        }

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return distance;
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new PlaneFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    },

    /**
     * Calculates distance factor.
     */
    FACTOR {
        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            double longitudeDifference = targetLongitude - sourceLongitude;
            double a = Math.toRadians(90D - sourceLatitude);
            double c = Math.toRadians(90D - targetLatitude);
            return (Math.cos(a) * Math.cos(c)) + (Math.sin(a) * Math.sin(c) * Math.cos(Math.toRadians(longitudeDifference)));
        }

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return Math.cos(distance / unit.getEarthRadius());
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new FactorFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    },
    /**
     * Calculates distance as points on a globe.
     */
    ARC {
        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            double x1 = sourceLatitude * Math.PI / 180D;
            double x2 = targetLatitude * Math.PI / 180D;
            double h1 = 1D - Math.cos(x1 - x2);
            double h2 = 1D - Math.cos((sourceLongitude - targetLongitude) * Math.PI / 180D);
            double h = (h1 + Math.cos(x1) * Math.cos(x2) * h2) / 2;
            double averageLatitude = (x1 + x2) / 2;
            double diameter = GeoUtils.earthDiameter(averageLatitude);
            return unit.fromMeters(diameter * Math.asin(Math.min(1, Math.sqrt(h))));
        }

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return distance;
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new ArcFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    },
    /**
     * Calculates distance as points on a globe in a sloppy way. Close to the pole areas the accuracy
     * of this function decreases.
     */
    SLOPPY_ARC {

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return distance;
        }

        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            return unit.fromMeters(SloppyMath.haversin(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude) * 1000.0);
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new SloppyArcFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    };

    /** Returns a GeoDistance object as read from the StreamInput. */
    @Override
    public GeoDistance readFrom(StreamInput in) throws IOException {
        int ord = in.readVInt();
        if (ord < 0 || ord >= values().length) {
            throw new IOException("Unknown GeoDistance ordinal [" + ord + "]");
        }
        return GeoDistance.values()[ord];
    }

    public static GeoDistance readGeoDistanceFrom(StreamInput in) throws IOException {
        return DEFAULT.readFrom(in);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVInt(this.ordinal());
    }

    /**
     * Default {@link GeoDistance} function. This method should be used, If no specific function has been selected.
     * This is an alias for <code>SLOPPY_ARC</code>
     */
    public static final GeoDistance DEFAULT = SLOPPY_ARC;

    public abstract double normalize(double distance, DistanceUnit unit);

    public abstract double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit);

    public abstract FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit);

    private static final double MIN_LAT = Math.toRadians(-90d);  // -PI/2
    private static final double MAX_LAT = Math.toRadians(90d);   //  PI/2
    private static final double MIN_LON = Math.toRadians(-180d); // -PI
    private static final double MAX_LON = Math.toRadians(180d);  //  PI

    public static DistanceBoundingCheck distanceBoundingCheck(double sourceLatitude, double sourceLongitude, double distance, DistanceUnit unit) {
        // angular distance in radians on a great circle
        // assume worst-case: use the minor axis
        double radDist = unit.toMeters(distance) / GeoUtils.EARTH_SEMI_MINOR_AXIS;

        double radLat = Math.toRadians(sourceLatitude);
        double radLon = Math.toRadians(sourceLongitude);

        double minLat = radLat - radDist;
        double maxLat = radLat + radDist;

        double minLon, maxLon;
        if (minLat > MIN_LAT && maxLat < MAX_LAT) {
            double deltaLon = Math.asin(Math.sin(radDist) / Math.cos(radLat));
            minLon = radLon - deltaLon;
            if (minLon < MIN_LON) minLon += 2d * Math.PI;
            maxLon = radLon + deltaLon;
            if (maxLon > MAX_LON) maxLon -= 2d * Math.PI;
        } else {
            // a pole is within the distance
            minLat = Math.max(minLat, MIN_LAT);
            maxLat = Math.min(maxLat, MAX_LAT);
            minLon = MIN_LON;
            maxLon = MAX_LON;
        }

        GeoPoint topLeft = new GeoPoint(Math.toDegrees(maxLat), Math.toDegrees(minLon));
        GeoPoint bottomRight = new GeoPoint(Math.toDegrees(minLat), Math.toDegrees(maxLon));
        if (minLon > maxLon) {
            return new Meridian180DistanceBoundingCheck(topLeft, bottomRight);
        }
        return new SimpleDistanceBoundingCheck(topLeft, bottomRight);
    }

    /**
     * Get a {@link GeoDistance} according to a given name. Valid values are
     *
     * <ul>
     *     <li><b>plane</b> for <code>GeoDistance.PLANE</code></li>
     *     <li><b>sloppy_arc</b> for <code>GeoDistance.SLOPPY_ARC</code></li>
     *     <li><b>factor</b> for <code>GeoDistance.FACTOR</code></li>
     *     <li><b>arc</b> for <code>GeoDistance.ARC</code></li>
     * </ul>
     *
     * @param name name of the {@link GeoDistance}
     * @return a {@link GeoDistance}
     */
    public static GeoDistance fromString(String name) {
        name = name.toLowerCase(Locale.ROOT);
        if ("plane".equals(name)) {
            return PLANE;
        } else if ("arc".equals(name)) {
            return ARC;
        } else if ("sloppy_arc".equals(name)) {
            return SLOPPY_ARC;
        } else if ("factor".equals(name)) {
            return FACTOR;
        }
        throw new IllegalArgumentException("No geo distance for [" + name + "]");
    }

    public static interface FixedSourceDistance {

        double calculate(double targetLatitude, double targetLongitude);
    }

    public static interface DistanceBoundingCheck {

        boolean isWithin(double targetLatitude, double targetLongitude);

        GeoPoint topLeft();

        GeoPoint bottomRight();
    }

    public static final AlwaysDistanceBoundingCheck ALWAYS_INSTANCE = new AlwaysDistanceBoundingCheck();

    private static class AlwaysDistanceBoundingCheck implements DistanceBoundingCheck {
        @Override
        public boolean isWithin(double targetLatitude, double targetLongitude) {
            return true;
        }

        @Override
        public GeoPoint topLeft() {
            return null;
        }

        @Override
        public GeoPoint bottomRight() {
            return null;
        }
    }

    public static class Meridian180DistanceBoundingCheck implements DistanceBoundingCheck {

        private final GeoPoint topLeft;
        private final GeoPoint bottomRight;

        public Meridian180DistanceBoundingCheck(GeoPoint topLeft, GeoPoint bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }

        @Override
        public boolean isWithin(double targetLatitude, double targetLongitude) {
            return (targetLatitude >= bottomRight.lat() && targetLatitude <= topLeft.lat()) &&
                    (targetLongitude >= topLeft.lon() || targetLongitude <= bottomRight.lon());
        }

        @Override
        public GeoPoint topLeft() {
            return topLeft;
        }

        @Override
        public GeoPoint bottomRight() {
            return bottomRight;
        }
    }

    public static class SimpleDistanceBoundingCheck implements DistanceBoundingCheck {
        private final GeoPoint topLeft;
        private final GeoPoint bottomRight;

        public SimpleDistanceBoundingCheck(GeoPoint topLeft, GeoPoint bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }

        @Override
        public boolean isWithin(double targetLatitude, double targetLongitude) {
            return (targetLatitude >= bottomRight.lat() && targetLatitude <= topLeft.lat()) &&
                    (targetLongitude >= topLeft.lon() && targetLongitude <= bottomRight.lon());
        }

        @Override
        public GeoPoint topLeft() {
            return topLeft;
        }

        @Override
        public GeoPoint bottomRight() {
            return bottomRight;
        }
    }

    public static class PlaneFixedSourceDistance implements FixedSourceDistance {

        private final double sourceLatitude;
        private final double sourceLongitude;
        private final double distancePerDegree;

        public PlaneFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            this.sourceLatitude = sourceLatitude;
            this.sourceLongitude = sourceLongitude;
            this.distancePerDegree = unit.getDistancePerDegree();
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            double px = targetLongitude - sourceLongitude;
            double py = targetLatitude - sourceLatitude;
            return Math.sqrt(px * px + py * py) * distancePerDegree;
        }
    }

    public static class FactorFixedSourceDistance implements FixedSourceDistance {

        private final double sourceLongitude;

        private final double a;
        private final double sinA;
        private final double cosA;

        public FactorFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            this.sourceLongitude = sourceLongitude;
            this.a = Math.toRadians(90D - sourceLatitude);
            this.sinA = Math.sin(a);
            this.cosA = Math.cos(a);
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            double longitudeDifference = targetLongitude - sourceLongitude;
            double c = Math.toRadians(90D - targetLatitude);
            return (cosA * Math.cos(c)) + (sinA * Math.sin(c) * Math.cos(Math.toRadians(longitudeDifference)));
        }
    }

    /**
     * Basic implementation of {@link FixedSourceDistance}. This class keeps the basic parameters for a distance
     * functions based on a fixed source. Namely latitude, longitude and unit.
     */
    public static abstract class FixedSourceDistanceBase implements FixedSourceDistance {
        protected final double sourceLatitude;
        protected final double sourceLongitude;
        protected final DistanceUnit unit;

        public FixedSourceDistanceBase(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            this.sourceLatitude = sourceLatitude;
            this.sourceLongitude = sourceLongitude;
            this.unit = unit;
        }
    }

    public static class ArcFixedSourceDistance extends FixedSourceDistanceBase {

        public ArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            super(sourceLatitude, sourceLongitude, unit);
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            return ARC.calculate(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, unit);
        }

    }

    public static class SloppyArcFixedSourceDistance extends FixedSourceDistanceBase {

        public SloppyArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            super(sourceLatitude, sourceLongitude, unit);
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            return SLOPPY_ARC.calculate(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, unit);
        }
    }


    /**
     * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points for each document.
     */
    public static SortedNumericDoubleValues distanceValues(final MultiGeoPointValues geoPointValues, final FixedSourceDistance... distances) {
        final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues);
        if (singleValues != null && distances.length == 1) {
            final Bits docsWithField = FieldData.unwrapSingletonBits(geoPointValues);
            return FieldData.singleton(new NumericDoubleValues() {

                @Override
                public double get(int docID) {
                    if (docsWithField != null && !docsWithField.get(docID)) {
                        return 0d;
                    }
                    final GeoPoint point = singleValues.get(docID);
                    return distances[0].calculate(point.lat(), point.lon());
                }

            }, docsWithField);
        } else {
            return new SortingNumericDoubleValues() {

                @Override
                public void setDocument(int doc) {
                    geoPointValues.setDocument(doc);
                    resize(geoPointValues.count() * distances.length);
                    int valueCounter = 0;
                    for (FixedSourceDistance distance : distances) {
                        for (int i = 0; i < geoPointValues.count(); ++i) {
                            final GeoPoint point = geoPointValues.valueAt(i);
                            values[valueCounter] = distance.calculate(point.lat(), point.lon());
                            valueCounter++;
                        }
                    }
                    sort();
                }
            };
        }
    }
}