forked from qedus/sphere
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsphere.py
2660 lines (2220 loc) · 89.2 KB
/
sphere.py
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function, unicode_literals, division
import bisect
import math
import decimal
import heapq
class Angle(object):
def __init__(self, radians=0):
if not isinstance(radians, (long, float, int)):
raise ValueError()
self.__radians = radians
def __eq__(self, other):
return isinstance(other, self.__class__) \
and self.__radians == other.__radians
def __add__(self, other):
return self.__class__.from_radians(self.__radians + other.__radians)
def __repr__(self):
return '{}: {}'.format(self.__class__.__name__, self.__radians)
@classmethod
def from_degrees(cls, degrees):
return cls(math.radians(degrees))
@classmethod
def from_radians(cls, radians):
return cls(radians)
@property
def radians(self):
return self.__radians
@property
def degrees(self):
return math.degrees(self.__radians)
class Point(object):
def __init__(self, x, y, z):
self.__point = (x, y, z)
def __getitem__(self, index):
return self.__point[index]
def __neg__(self):
return self.__class__(-self[0], -self[1], -self[2])
def __eq__(self, other):
return isinstance(other, self.__class__) \
and self.__point == other.__point
def __ne_(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.__point)
def __repr__(self):
return 'Point: {}'.format(self.__point)
def __add__(self, other):
return self.__class__(self[0] + other[0],
self[1] + other[1],
self[2] + other[2])
def __sub__(self, other):
return self.__class__(self[0] - other[0],
self[1] - other[1],
self[2] - other[2])
def __mul__(self, other):
return self.__class__(self[0] * other,
self[1] * other,
self[2] * other)
def __rmul__(self, other):
return self.__class__(self[0] * other,
self[1] * other,
self[2] * other)
def abs(self):
return self.__class__(math.fabs(self.__point[0]),
math.fabs(self.__point[1]),
math.fabs(self.__point[2]))
def largest_abs_component(self):
temp = self.abs()
if temp[0] > temp[1]:
if temp[0] > temp[2]:
return 0
else:
return 2
else:
if temp[1] > temp[2]:
return 1
else:
return 2
def angle(self, other):
return math.atan2(self.cross_prod(other).norm(), self.dot_prod(other))
def cross_prod(self, other):
x, y, z = self.__point
ox, oy, oz = other.__point
return self.__class__(y * oz - z * oy,
z * ox - x * oz,
x * oy - y * ox)
def dot_prod(self, other):
x, y, z = self.__point
ox, oy, oz = other.__point
return x * ox + y * oy + z * oz
def norm2(self):
x, y, z = self.__point
return x * x + y * y + z * z
def norm(self):
return math.sqrt(self.norm2())
def normalize(self):
n = self.norm()
if n != 0:
n = 1.0 / n
return self.__class__(self[0] * n, self[1] * n, self[2] * n)
class LatLon(object):
@classmethod
def from_degrees(cls, lat, lon):
return cls(math.radians(lat), math.radians(lon))
@classmethod
def from_radians(cls, lat, lon):
return cls(lat, lon)
@classmethod
def from_point(cls, point):
return cls(LatLon.latitude(point).radians,
LatLon.longitude(point).radians)
@classmethod
def from_angles(cls, lat, lon):
return cls(lat.radians, lon.radians)
@classmethod
def default(cls):
return cls(0, 0)
@classmethod
def invalid(cls):
return cls(math.pi, 2 * math.pi)
def __init__(self, lat, lon):
self.__coords = (lat, lon)
def __eq__(self, other):
return isinstance(other, LatLon) and self.__coords == other.__coords
def __hash__(self):
return hash(self.__coords)
def __repr__(self):
return 'LatLon: {},{}'.format(math.degrees(self.__coords[0]),
math.degrees(self.__coords[1]))
def __add__(self, other):
return self.__class__(self.lat().radians + other.lat().radians,
self.lon().radians + other.lon().radians)
def __sub__(self, other):
return self.__class__(self.lat().radians - other.lat().radians,
self.lon().radians - other.lon().radians)
# only implemented so we can do scalar * LatLon
def __rmul__(self, other):
return self.__class__(other * self.lat().radians,
other * self.lon().radians)
@staticmethod
def latitude(point):
return Angle.from_radians(math.atan2(point[2],
math.sqrt(point[0] * point[0] + point[1] * point[1])))
@staticmethod
def longitude(point):
return Angle.from_radians(math.atan2(point[1], point[0]))
def lat(self):
return Angle.from_radians(self.__coords[0])
def lon(self):
return Angle.from_radians(self.__coords[1])
def is_valid(self):
return abs(self.lat().radians) <= (math.pi / 2) \
and abs(self.lon().radians) <= math.pi
def to_point(self):
phi = self.lat().radians
theta = self.lon().radians
cosphi = math.cos(phi)
return Point(math.cos(theta) * cosphi,
math.sin(theta) * cosphi,
math.sin(phi))
def normalized(self):
return self.__class__(
max(-math.pi / 2.0, min(math.pi / 2.0, self.lat().radians)),
drem(self.lon().radians, 2 * math.pi))
def approx_equals(self, other, max_error=1e-15):
return math.fabs(self.lat().radians - other.lat().radians) \
< max_error and \
math.fabs(self.lon().radians - other.lon().radians) < max_error
def get_distance(self, other):
assert self.is_valid()
assert other.is_valid()
from_lat = self.lat().radians
to_lat = other.lat().radians
from_lon = self.lon().radians
to_lon = other.lon().radians
dlat = math.sin(0.5 * (to_lat - from_lat))
dlon = math.sin(0.5 * (to_lon - from_lon))
x = dlat * dlat + dlon * dlon * math.cos(from_lat) * math.cos(to_lat)
return Angle.from_radians(2 * math.atan2(
math.sqrt(x), math.sqrt(max(0.0, 1.0 - x))))
class Cap(object):
ROUND_UP = 1.0 + 1.0 / (1 << 52)
def __init__(self, axis=Point(1, 0, 0), height=-1):
self.__axis = axis
self.__height = height
def __repr__(self):
return '{}: {} {}'.format(self.__class__.__name__, self.__axis,
self.__height)
@classmethod
def from_axis_height(cls, axis, height):
assert is_unit_length(axis)
return cls(axis, height)
@classmethod
def from_axis_angle(cls, axis, angle):
assert is_unit_length(axis)
assert angle.radians >= 0
return cls(axis, cls.get_height_for_angle(angle.radians))
@classmethod
def get_height_for_angle(cls, radians):
assert radians >= 0
if radians >= math.pi:
return 2
d = math.sin(0.5 * radians)
return 2 * d * d
@classmethod
def from_axis_area(cls, axis, area):
assert is_unit_length(axis)
return cls(axis, area / (2 * math.pi))
@classmethod
def empty(cls):
return cls()
@classmethod
def full(cls):
return cls(Point(1, 0, 0), 2)
def height(self):
return self.__height
def axis(self):
return self.__axis
def area(self):
return 2 * math.pi * max(0.0, self.height())
def angle(self):
if self.is_empty():
return Angle.from_radians(-1)
return Angle.from_radians(2 * math.asin(math.sqrt(0.5 * self.height())))
def is_valid(self):
return is_unit_length(self.axis()) and self.height() <= 2
def is_empty(self):
return self.height() < 0
def is_full(self):
return self.height() >= 2
def get_cap_bound(self):
return self
def add_point(self, point):
assert is_unit_length(point)
if self.is_empty():
self.__axis = point
self.__height = 0
else:
dist2 = (self.axis() - point).norm2()
self.__height = max(self.__height,
self.__class__.ROUND_UP * 0.5 * dist2)
def complement(self):
if self.is_full():
height = -1
else:
height = 2 - max(self.height(), 0.0)
return self.__class__.from_axis_height(-self.axis(), height)
def contains(self, other):
if isinstance(other, self.__class__):
if self.is_full() or other.is_empty():
return True
return self.angle().radians >= self.axis().angle(other.axis()) \
+ other.angle().radians
elif isinstance(other, Point):
assert is_unit_length(other)
return (self.axis() - other).norm2() <= 2 * self.height()
elif isinstance(other, Cell):
vertices = []
for k in xrange(4):
vertices.append(other.get_vertex(k))
if not self.contains(vertices[k]):
return False
return not self.complement().intersects(other, vertices)
else:
raise NotImplementedError()
def interior_contains(self, other):
if isinstance(other, Point):
assert is_unit_length(other)
return self.is_full() \
or (self.axis() - other).norm2() < 2 * self.height()
else:
raise NotImplementedError()
def intersects(self, *args):
if len(args) == 1 and isinstance(args[0], self.__class__):
other = args[0]
if self.is_empty() or other.is_empty():
return False
return self.angle().radians + other.angle().radians \
>= self.axis().angle(other.axis())
elif len(args) == 2 and isinstance(args[0], Cell) \
and isinstance(args[1], (list, tuple)):
cell, vertices = args
if self.height() >= 1:
return False
if self.is_empty():
return False
if cell.contains(self.axis()):
return True
sin2_angle = self.height() * (2 - self.height())
for k in xrange(4):
edge = cell.get_edge_raw(k)
dot = self.axis().dot_prod(edge)
if dot > 0:
continue
if dot * dot > sin2_angle * edge.norm2():
return False
dir = edge.cross_prod(self.axis())
if dir.dot_prod(vertices[k]) < 0 \
and dir.dot_prod(vertices[(k + 1) & 3]) > 0:
return True
return False
else:
raise NotImplementedError()
def may_intersect(self, other):
vertices = []
for k in xrange(4):
vertices.append(other.get_vertex(k))
if self.contains(vertices[k]):
return True
return self.intersects(other, vertices)
def interior_intersects(self, other):
if self.height() <= 0 or other.is_empty():
return False
return self.angle().radians + other.angle().radians > \
self.axis().angle(other.axis())
def get_rect_bound(self):
if self.is_empty():
return LatLonRect.empty()
axis_ll = LatLon.from_point(self.axis())
cap_angle = self.angle().radians
all_longitudes = False
lat, lon = [], []
lon.append(-math.pi)
lon.append(math.pi)
lat.append(axis_ll.lat().radians - cap_angle)
if lat[0] <= -math.pi / 2.0:
lat[0] = -math.pi / 2.0
all_longitudes = True
lat.append(axis_ll.lat().radians + cap_angle)
if lat[1] >= math.pi / 2.0:
lat[1] = math.pi / 2.0
all_longitudes = True
if not all_longitudes:
sin_a = math.sqrt(self.height() * (2 - self.height()))
sin_c = math.cos(axis_ll.lat().radians)
if sin_a <= sin_c:
angle_a = math.asin(sin_a / sin_c)
lon[0] = drem(axis_ll.lon().radians - angle_a, 2 * math.pi)
lon[1] = drem(axis_ll.lon().radians + angle_a, 2 * math.pi)
return LatLonRect(LineInterval(*lat), SphereInterval(*lon))
def approx_equals(self, other, max_error=1e-14):
return (self.axis().angle(other.axis()) <= max_error \
and math.fabs(self.height() - other.height()) <= max_error) \
or (self.is_empty() and other.height() <= max_error) \
or (other.is_empty() and self.height() <= max_error) \
or (self.is_full() and other.height() >= 2 - max_error) \
or (other.is_full() and self.height() >= 2 - max_error)
def expanded(self, distance):
assert distance.radians >= 0
if self.is_empty():
return self.__class__.empty()
return self.__class__.from_axis_angle(self.axis(),
self.angle() + distance)
class LatLonRect(object):
def __init__(self, *args):
if len(args) == 0:
self.__lat = LineInterval.empty()
self.__lon = SphereInterval.empty()
elif isinstance(args[0], LatLon) and isinstance(args[1], LatLon):
lo, hi = args
self.__lat = LineInterval(lo.lat().radians, hi.lat().radians)
self.__lon = SphereInterval(lo.lon().radians, hi.lon().radians)
elif isinstance(args[0], LineInterval) \
and isinstance(args[1], SphereInterval):
self.__lat, self.__lon = args
else:
raise NotImplementedError()
def __eq__(self, other):
return isinstance(other, self.__class__) \
and self.lat() == other.lat() and self.lon() == other.lon()
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '{}: {}, {}'.format(self.__class__.__name__,
self.lat(), self.lon())
def lat(self):
return self.__lat
def lon(self):
return self.__lon
def lat_lo(self):
return Angle.from_radians(self.lat().lo())
def lat_hi(self):
return Angle.from_radians(self.lat().hi())
def lon_lo(self):
return Angle.from_radians(self.lon().lo())
def lon_hi(self):
return Angle.from_radians(self.lon().hi())
def lo(self):
return LatLon.from_angles(self.lat_lo(), self.lon_lo())
def hi(self):
return LatLon.from_angles(self.lat_hi(), self.lon_hi())
# Construct a rectangle of the given size centered around the given point.
# "center" needs to be normalized, but "size" does not. The latitude
# interval of the result is clamped to [-90,90] degrees, and the longitude
# interval of the result is Full() if and only if the longitude size is
# 360 degrees or more. Examples of clamping (in degrees):
#
# center=(80,170), size=(40,60) -> lat=[60,90], lng=[140,-160]
# center=(10,40), size=(210,400) -> lat=[-90,90], lng=[-180,180]
# center=(-90,180), size=(20,50) -> lat=[-90,-80], lng=[155,-155]
@classmethod
def from_center_size(cls, center, size):
return cls.from_point(center).expanded(0.5 * size)
@classmethod
def from_point(cls, p):
assert p.is_valid()
return cls(p, p)
@classmethod
def from_point_pair(cls, a, b):
assert a.is_valid()
assert b.is_valid()
return LatLonRect(LineInterval.from_point_pair(a.lat().radians,
b.lat().radians),
SphereInterval.from_point_pair(a.lon().radians,
b.lon().radians))
@classmethod
def full_lat(cls):
return LineInterval(-math.pi / 2.0, math.pi / 2.0)
@classmethod
def full_lon(cls):
return SphereInterval.full()
@classmethod
def full(cls):
return cls(cls.full_lat(), cls.full_lon())
def is_full(self):
return self.lat() == self.__class__.full_lat() and self.lon().is_full()
def is_valid(self):
return math.fabs(self.lat().lo()) <= math.pi / 2.0 \
and math.fabs(self.lat().hi()) <= math.pi / 2.0 \
and self.lon().is_valid() \
and self.lat().is_empty() == self.lon().is_empty()
@classmethod
def empty(cls):
return cls()
def get_center(self):
return LatLon.from_radians(self.lat().get_center(),
self.lon().get_center())
def get_size(self):
return LatLon.from_radians(self.lat().get_length(),
self.lon().get_length())
def get_vertex(self, k):
# Twiddle bits to return the points in CCW order (SW, SE, NE, NW)
return LatLon.from_radians(self.lat().bound(k >> 1),
self.lon().bound((k >> 1) ^ (k & 1)))
def is_empty(self):
return self.lat().is_empty()
def is_point(self):
return self.lat().lo() == self.lat().hi() \
and self.lon().lo() == self.lon().hi()
def convolve_with_cap(self, angle):
cap = Cap.from_axis_angle(Point(1, 0, 0), angle)
r = self
for k in xrange(4):
vertex_cap = Cap.from_axis_height(self.get_vertex(k).to_point(),
cap.height())
r = r.union(vertex_cap.get_rect_bound())
return r
def contains(self, *args):
if isinstance(args[0], Point):
point = args[0]
return self.contains(LatLon.from_point(point))
elif isinstance(args[0], LatLon):
ll = args[0]
assert ll.is_valid()
return self.lat().contains(ll.lat().radians) \
and self.lon().contains(ll.lon().radians)
elif isinstance(args[0], self.__class__):
other = args[0]
return self.lat().contains(other.lat()) \
and self.lon().contains(other.lon())
elif isinstance(args[0], Cell):
cell = args[0]
return self.contains(cell.get_rect_bound())
else:
raise NotImplementedError()
def interior_contains(self, *args):
if isinstance(args[0], Point):
self.interior_contains(LatLon(args[0]))
elif isinstance(args[0], LatLon):
ll = args[0]
assert ll.is_valid()
return self.lat().interior_contains(ll.lat().radians) \
and self.lon().interior_contains(ll.lon().radians)
elif isinstance(args[0], self.__class__):
other = args[0]
return self.lat().interior_contains(other.lat()) \
and self.lon().interior_contains(other.lon())
else:
raise NotImplementedError()
def may_intersect(self, cell):
return self.intersects(cell.get_rect_bound())
def intersects(self, *args):
if isinstance(args[0], self.__class__):
other = args[0]
return self.lat().intersects(other.lat()) \
and self.lon().intersects(other.lon())
elif isinstance(args[0], Cell):
cell = args[0]
if self.is_empty():
return False
if self.contains(cell.get_center_raw()):
return True
if cell.contains(self.get_center().to_point()):
return True
if not self.intersects(cell.get_rect_bound()):
return False
cell_v = []
cell_ll = []
for i in xrange(4):
cell_v.append(cell.get_vertex(i))
cell_ll.append(LatLon.from_point(cell_v[i]))
if self.contains(cell_ll[i]):
return True
if cell.contains(self.get_vertex(i).to_point()):
return True
for i in xrange(4):
edge_lon = SphereInterval.from_point_pair(
cell_ll[i].lon().radians,
cell_ll[(i + 1) & 3].lon().radians)
if not self.lon().intersects(edge_lon):
continue
a = cell_v[i]
b = cell_v[(i + 1) & 3]
if edge_lon.contains(self.lon().lo()):
if self.__class__.intersects_lon_edge(a, b,
self.lat(), self.lon().lo()):
return True
if edge_lon.contains(self.lon().hi()):
if self.__class__.intersects_lon_edge(a, b,
self.lat(), self.lon().hi()):
return True
if self.__class__.intersects_lat_edge(a, b,
self.lat().lo(), self.lon()):
return True
if self.__class__.intersects_lat_edge(a, b,
self.lat().hi(), self.lon()):
return True
return False
else:
raise NotImplementedError()
@classmethod
def intersects_lon_edge(cls, a, b, lat, lon):
return simple_crossing(a, b,
LatLon.from_radians(lat.lo(), lon).to_point(),
LatLon.from_radians(lat.hi(), lon).to_point())
@classmethod
def intersects_lat_edge(cls, a, b, lat, lon):
assert is_unit_length(a)
assert is_unit_length(b)
z = robust_cross_prod(a, b).normalize()
if z[2] < 0:
z = -z
y = robust_cross_prod(z, Point(0, 0, 1)).normalize()
x = y.cross_prod(z)
assert is_unit_length(x)
assert x[2] >= 0
sin_lat = math.sin(lat)
if math.fabs(sin_lat) >= x[2]:
return False
assert x[2] > 0
cos_theta = sin_lat / x[2]
sin_theta = math.sqrt(1 - cos_theta * cos_theta)
theta = math.atan2(sin_theta, cos_theta)
ab_theta = SphereInterval.from_point_pair(
math.atan2(a.dot_prod(y), a.dot_prod(x)),
math.atan2(b.dot_prod(y), b.dot_prod(x)))
if ab_theta.contains(theta):
isect = x * cos_theta + y * sin_theta
if lon.contains(math.atan2(isect[1], isect[0])):
return True
if ab_theta.contains(-theta):
isect = x * cos_theta - y * sin_theta
if lon.contains(math.atan2(isect[1], isect[0])):
return True
return False
def interior_intersects(self, *args):
if isinstance(args[0], self.__class__):
other = args[0]
return self.lat().interior_intersects(other.lat()) \
and self.lon().interior_intersects(other.lon())
else:
raise NotImplementedError()
def union(self, other):
return self.__class__(self.lat().union(other.lat()),
self.lon().union(other.lon()))
def intersection(self, other):
lat = self.lat().intersection(other.lat())
lon = self.lon().intersection(other.lon())
if lat.is_empty() or lon.is_empty():
return self.__class__.empty()
return self.__class__(lat, lon)
# Return a rectangle that contains all points whose latitude distance from
# this rectangle is at most margin.lat(), and whose longitude distance
# from this rectangle is at most margin.lng(). In particular, latitudes
# are clamped while longitudes are wrapped. Note that any expansion of an
# empty interval remains empty, and both components of the given margin
# must be non-negative. "margin" does not need to be normalized.
#
# NOTE: If you are trying to grow a rectangle by a certain *distance* on
# the sphere (e.g. 5km), use the ConvolveWithCap() method instead.
def expanded(self, margin):
assert margin.lat().radians > 0
assert margin.lon().radians > 0
return self.__class__(
self.lat().expanded(margin.lat().radians) \
.intersection(self.full_lat()),
self.lon().expanded(margin.lon().radians))
def approx_equals(self, other, max_error=1e-15):
return self.lat().approx_equals(other.lat(), max_error) \
and self.lon().approx_equals(other.lon(), max_error)
def get_cap_bound(self):
if self.is_empty():
return Cap.empty()
if self.lat().lo() + self.lat().hi() < 0:
pole_z = -1
pole_angle = math.pi / 2.0 + self.lat().hi()
else:
pole_z = 1
pole_angle = math.pi / 2.0 - self.lat().lo()
pole_cap = Cap.from_axis_angle(Point(0, 0, pole_z),
Angle.from_radians(pole_angle))
lon_span = self.lon().hi() - self.lon().lo()
if drem(lon_span, 2 * math.pi) >= 0:
if lon_span < 2 * math.pi:
mid_cap = Cap.from_axis_angle(self.get_center().to_point(),
Angle.from_radians(0))
for k in xrange(4):
mid_cap.add_point(self.get_vertex(k).to_point())
if mid_cap.height() < pole_cap.height():
return mid_cap
return pole_cap
# Constants for CellId
LOOKUP_BITS = 4
SWAP_MASK = 0x01
INVERT_MASK = 0x02
POS_TO_IJ = ((0, 1, 3, 2),
(0, 2, 3, 1),
(3, 2, 0, 1),
(3, 1, 0, 2))
POS_TO_ORIENTATION = [SWAP_MASK, 0, 0, INVERT_MASK | SWAP_MASK]
LOOKUP_POS = [None] * (1 << (2 * LOOKUP_BITS + 2))
LOOKUP_IJ = [None] * (1 << (2 * LOOKUP_BITS + 2))
def _init_lookup_cell(level, i, j, orig_orientation, pos, orientation):
if level == LOOKUP_BITS:
ij = (i << LOOKUP_BITS) + j
LOOKUP_POS[(ij << 2) + orig_orientation] = (pos << 2) + orientation
LOOKUP_IJ[(pos << 2) + orig_orientation] = (ij << 2) + orientation
else:
level = level + 1
i <<= 1
j <<= 1
pos <<= 2
r = POS_TO_IJ[orientation]
for index in xrange(4):
_init_lookup_cell(level, i + (r[index] >> 1),
j + (r[index] & 1), orig_orientation,
pos + index, orientation ^ POS_TO_ORIENTATION[index])
_init_lookup_cell(0, 0, 0, 0, 0, 0)
_init_lookup_cell(0, 0, 0, SWAP_MASK, 0, SWAP_MASK)
_init_lookup_cell(0, 0, 0, INVERT_MASK, 0, INVERT_MASK)
_init_lookup_cell(0, 0, 0, SWAP_MASK | INVERT_MASK, 0, SWAP_MASK | INVERT_MASK)
class CellId(object):
# projection types
LINEAR_PROJECTION = 0
TAN_PROJECTION = 1
QUADRATIC_PROJECTION = 2
# current projection used
PROJECTION = QUADRATIC_PROJECTION
FACE_BITS = 3
NUM_FACES = 6
MAX_LEVEL = 30
POS_BITS = 2 * MAX_LEVEL + 1
MAX_SIZE = 1 << MAX_LEVEL
WRAP_OFFSET = NUM_FACES << POS_BITS
def __init__(self, *args, **kwargs):
if len(args) == 0:
self.__id = long(0)
elif len(args) == 1:
# modulus to ensure wrap around
self.__id = long(args[0]) % 0xffffffffffffffff
else:
raise ValueError()
def __repr__(self):
return 'CellId: {}'.format(self.id())
def __hash__(self):
return hash(self.id())
def __cmp__(self, other):
if not isinstance(other, self.__class__):
raise NotImplementedError('Only supports comparison with same type')
else:
return self.id().__cmp__(other.id())
@classmethod
def from_lat_lon(cls, ll):
return cls.from_point(ll.to_point())
@classmethod
def from_point(cls, p):
face, u, v = xyz_to_face_uv(p)
i = cls.st_to_ij(cls.uv_to_st(u))
j = cls.st_to_ij(cls.uv_to_st(v))
return cls.from_face_ij(face, i, j)
@classmethod
def from_face_pos_level(cls, face, pos, level):
return cls((face << cls.POS_BITS) + (pos | 1)).parent(level)
@classmethod
def from_face_ij(cls, face, i, j):
n = face << (cls.POS_BITS - 1)
bits = face & SWAP_MASK
for k in xrange(7, -1, -1):
mask = (1 << LOOKUP_BITS) - 1
bits += (((i >> (k * LOOKUP_BITS)) & mask) << (LOOKUP_BITS + 2))
bits += (((j >> (k * LOOKUP_BITS)) & mask) << 2)
bits = LOOKUP_POS[bits]
n |= (bits >> 2) << (k * 2 * LOOKUP_BITS)
bits &= (SWAP_MASK | INVERT_MASK)
return cls(n * 2 + 1)
@classmethod
def from_face_ij_wrap(cls, face, i, j):
# Convert i and j to the coordinates of a leaf cell just beyond the
# boundary of this face. This prevents 32-bit overflow in the case
# of finding the neighbors of a face cell
i = max(-1, min(cls.MAX_SIZE, i))
j = max(-1, min(cls.MAX_SIZE, j))
# Find the (u,v) coordinates corresponding to the center of cell (i,j).
# For our purposes it's sufficient to always use the linear projection
# from (s,t) to (u,v): u=2*s-1 and v=2*t-1.
scale = 1.0 / cls.MAX_SIZE
u = scale * (( i << 1) + 1 - cls.MAX_SIZE)
v = scale * (( j << 1) + 1 - cls.MAX_SIZE)
# Find the leaf cell coordinates on the adjacent face, and convert
# them to a cell id at the appropriate level. We convert from (u,v)
# back to (s,t) using s=0.5*(u+1), t=0.5*(v+1).
face, u, v = xyz_to_face_uv(face_uv_to_xyz(face, u, v))
return cls.from_face_ij(face, cls.st_to_ij(0.5 * (u + 1)),
cls.st_to_ij(0.5 * (v + 1)))
@classmethod
def from_face_ij_same(cls, face, i, j, same_face):
if same_face:
return cls.from_face_ij(face, i, j)
else:
return cls.from_face_ij_wrap(face, i, j)
@classmethod
def st_to_ij(cls, s):
return max(0, min(cls.MAX_SIZE - 1, int(math.floor(cls.MAX_SIZE * s))))
@classmethod
def lsb_for_level(cls, level):
return 1 << (2 * (cls.MAX_LEVEL - level))
def parent(self, *args):
assert self.is_valid()
if len(args) == 0:
assert not self.is_face()
new_lsb = self.lsb() << 2
return self.__class__((self.id() & -new_lsb) | new_lsb)
elif len(args) == 1:
level = args[0]
assert level >= 0
assert level <= self.level()
new_lsb = self.__class__.lsb_for_level(level)
return self.__class__((self.id() & -new_lsb) | new_lsb)
def child(self, pos):
assert self.is_valid()
assert not self.is_leaf()
new_lsb = self.lsb() >> 2
return self.__class__(self.id() + (2 * pos + 1 - 4) * new_lsb)
def contains(self, other):
assert self.is_valid()
assert other.is_valid()
return other >= self.range_min() and other <= self.range_max()
def intersects(self, other):
assert self.is_valid()
assert other.is_valid()
return other.range_min() <= self.range_max() \
and other.range_max() >= self.range_min()
def is_face(self):
return (self.id() & (self.lsb_for_level(0) - 1)) == 0
def id(self):
return self.__id
def is_valid(self):
return (self.face() < self.__class__.NUM_FACES) \
and (self.lsb() & 0x1555555555555555) != 0
def lsb(self):
return self.id() & -self.id()
def face(self):
return self.id() >> self.__class__.POS_BITS
def pos(self):
# is this correct?
return self.id() & (0xffffffffffffffff >> self.__class__.FACE_BITS)
def is_leaf(self):
return (self.id() & 1) != 0
def level(self):
if self.is_leaf():
return self.__class__.MAX_LEVEL
x = (self.id() & 0xffffffff)
level = -1
if x != 0:
level += 16
else:
# is this correct?
x = ((self.id() >> 32) & 0xffffffff)
x &= -x
if x & 0x00005555:
level += 8
if x & 0x00550055:
level += 4
if x & 0x05050505:
level += 2
if x & 0x11111111:
level += 1
assert level >= 0
assert level <= self.__class__.MAX_LEVEL
return level
def child_begin(self, *args):
assert self.is_valid()
if len(args) == 0:
assert not self.is_leaf()
old_lsb = self.lsb()
return self.__class__(self.id() - old_lsb + (old_lsb >> 2))