-
Notifications
You must be signed in to change notification settings - Fork 4
/
dggs.py
3002 lines (2649 loc) · 109 KB
/
dggs.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
"""
This Python 3.3 module implements the rHEALPix discrete global grid system.
CHANGELOG:
- Alexander Raichev (AR), 2012-11-12: Initial version based upon grids.py.
- AR, 2012-12-10: Corrected centroid() and moved some methods from graphics.py to here.
- AR, 2012-12-19: Tested all the methods and added examples.
- AR, 2013-01-01: Added ellipsoidal functionality to neighbor() and neighbors().
- AR, 2013-01-14: Added intersects_meridian(), cell_latitudes(), cells_from_meridian(), cells_from_parallel(), cells_from_region().
- AR, 2013-01-16: Changed the string keyword 'surface' to a boolean keyword 'plane'.
- AR, 2013-03-11: Added minimal_cover(), boundary(), interior(), triangle(), nw_vertex().
- AR, 2013-03-14: Fixed bug in nw_vertex().
- AR, 2013-07-23: Ported to Python 3.3.
- Robert Gibb (RG), 2020-07-13: Issue #1 Multiple tests fail due to rounding errors
NOTES:
All lengths are measured in meters and all angles are measured in radians
unless indicated otherwise.
By 'ellipsoid' throughout, i mean an ellipsoid of revolution and *not* a general (triaxial) ellipsoid.
Points lying on the plane are given in rectangular (horizontal, vertical) coordinates, and points lying on the ellipsoid are given in geodetic (longitude, latitude) coordinates unless indicated otherwise.
DGGS abbreviates 'discrete global grid system'.
Except when manipulating positive integers, I avoid the modulo function '%'
and insted write everything in terms of 'floor()'.
This is because Python interprets the sign of '%' differently than
Java or C, and I don't want to confuse people who are translating this code
to those languages.
EXAMPLES:
Create the (1, 2)-rHEALPix DGGS with N_side = 3 that is based on the WGS84 ellipsoid. Use degrees instead of the default radians for angular measurements ::
>>> from rhealpixdggs.ellipsoids import WGS84_ELLIPSOID
>>> E = WGS84_ELLIPSOID
>>> rdggs = RHEALPixDGGS(ellipsoid=E, north_square=1, south_square=2, N_side=3)
>>> print(rdggs)
rHEALPix DGGS:
N_side = 3
north_square = 1
south_square = 2
max_areal_resolution = 1
max_resolution = 15
ellipsoid:
R_A = 6374581.467096525
a = 6378137.0
b = 6356752.314140356
e = 0.0578063088401125
f = 0.003352810681182319
lat_0 = 0
lon_0 = 0
radians = False
sphere = False
NOTES:: .. Issue #1 was ..
ellipsoid:
R_A = 6374581.4671 *
a = 6378137.0
b = 6356752.314140356 *
e = 0.0578063088401
f = 0.003352810681182319
Pick a (longitude-latitude) point on the ellipsoid and find the resolution 1 cell that contains it ::
>>> p = (0, 45)
>>> c = rdggs.cell_from_point(1, p, plane=False); print(c)
N8
Find the ellipsoidal (edge) neighbors of this cell ::
>>> for (direction, cell) in sorted(c.neighbors(plane=False).items()):
... print(direction, cell)
east N5
south_east Q0
south_west P2
west N7
Find the planar (edge) neighbors of this cell ::
>>> for (direction, cell) in sorted(c.neighbors('plane').items()):
... print(direction, cell)
down P2
left N7
right Q0
up N5
Find all the resolution 1 cells intersecting the longitude-latitude aligned ellipsoidal quadrangle with given northwest and southeast corners ::
>>> nw = (0, 45)
>>> se = (90, 0)
>>> cells = rdggs.cells_from_region(1, nw, se, plane=False)
>>> for row in cells:
... print([str(cell) for cell in row])
['N8', 'N5', 'N2']
['Q0', 'Q1', 'Q2', 'R0']
['Q3', 'Q4', 'Q5', 'R3']
Compute the ellipsoidal nuclei of these cells ::
>>> for row in cells:
... for cell in row:
... print(cell, cell.nucleus(plane=False))
N8 (0.0, 58.47067782962736)
N5 (45.000000000000036, 58.47067782962736)
N2 (90.00000000000003, 58.470677829627355)
Q0 (14.999999999999998, 26.438744923100096)
Q1 (45.0, 26.438744923100096)
Q2 (74.99999999999999, 26.438744923100096)
R0 (105.00000000000001, 26.438744923100096)
Q3 (14.999999999999998, 3.560649871414923e-15)
Q4 (45.0, 3.560649871414923e-15)
Q5 (74.99999999999999, 3.560649871414923e-15)
R3 (105.00000000000001, 3.560649871414923e-15)
NOTES:: .. Issue #1 was ..
N8 (0.0, 58.470677829627363) *
N5 (45.000000000000036, 58.470677829627363) *
N2 (90.000000000000028, 58.470677829627355) *
Q0 (14.999999999999998, 26.438744923100096)
Q1 (45.0, 26.438744923100096)
Q2 (74.999999999999986, 26.438744923100096)
R0 (105.00000000000001, 26.438744923100096)
Q3 (14.999999999999998, 3.560649871414923e-15)
Q4 (45.0, 3.560649871414923e-15)
Q5 (74.999999999999986, 3.560649871414923e-15) *
R3 (105.00000000000001, 3.560649871414923e-15)
Create a (0, 0)-rHEALPix DGGS with N_side = 3 based on the WGS84 ellipsoid.
Use degrees instead of the default radians for angular measurements and
orient the DGGS so that the planar origin (0, 0) is on Auckland, New Zealand ::
>>> p = (174, -37) # Approximate Auckland lon-lat coordinates
>>> from rhealpixdggs.ellipsoids import *
>>> E = Ellipsoid(a=WGS84_A, f=WGS84_F, radians=False, lon_0=p[0], lat_0=p[1])
>>> rdggs = RHEALPixDGGS(E, N_side=3, north_square=0, south_square=0)
>>> print(rdggs)
rHEALPix DGGS:
N_side = 3
north_square = 0
south_square = 0
max_areal_resolution = 1
max_resolution = 15
ellipsoid:
R_A = 6374581.467096525
a = 6378137.0
b = 6356752.314140356
e = 0.0578063088401125
f = 0.003352810681182319
lat_0 = -37
lon_0 = 174
radians = False
sphere = False
NOTES:: .. Issue #1 was ..
ellipsoid:
R_A = 6374581.4671 *
a = 6378137.0
b = 6356752.314140356
e = 0.0578063088401 *
f = 0.003352810681182319
>>> print(rdggs.cell_from_point(1, p, plane=False))
Q3
"""
# *****************************************************************************
# Copyright (C) 2012 Alexander Raichev <alex.raichev@gmail.com>
#
# Distributed under the terms of the GNU Lesser General Public License (LGPL)
# http: //www.gnu.org/licenses/
# *****************************************************************************
# Import third-party modules.
from numpy import array, base_repr, ceil, log, pi, sign
from scipy import integrate
# Import standard modules.
from itertools import product
from random import uniform, randint
from colorsys import hsv_to_rgb
# Import my modules.
import rhealpixdggs.pj_rhealpix as pjr
import rhealpixdggs.projection_wrapper as pw
from rhealpixdggs.ellipsoids import (
WGS84_ELLIPSOID,
WGS84_ELLIPSOID_RADIANS,
UNIT_SPHERE,
UNIT_SPHERE_RADIANS,
)
from rhealpixdggs.utils import my_round
class RHEALPixDGGS(object):
"""
Represents an rHEALPix DGGS on a given ellipsoid.
CLASS ATTRIBUTES:
- `cells0` - A list of the resolution 0 cell IDs (strings).
INSTANCE ATTRIBUTES:
- `ellipsoid` - The underlying ellipsoid (Ellipsoid instance).
- `N_side` - An integer of size at least 2.
Each planar cell has N_side x N_side child cells.
- `(north_square, south_square)` - Integers between 0 and 3 indicating
the positions of north polar and south polar squares, respectively,
of the rHEALPix projection used.
- `max_areal_resolution` - An area measured in square meters that
upper bounds the area of the smallest ellipsoidal grid cells.
- `max_resolution` - A nonnegative integer that is the maximum grid
resolution needed to have ellipsoidal cells of area at most
`max_areal_resolution`.
- `child_order` - A dictionary of the ordering (Morton order) of child
cells of a cell in terms of the row-column coordinates in the matrix
of child cells. Child cell are numbered 0 to `N_side**2 -1` from
left to right and top to bottom.
- `ul_vertex` - A dictionary with key-value pairs (c, (x, y)), where
c is an element of `cells0` and (x, y) is the upper left corner point
of the resolution 0 planar cell c.
- `atomic_neighbors` - A dictionary with key-value pairs
(n, {'up': a, 'down': b, 'left': c, 'right': d}),
where n, a, b, c, and d are elements of `cells0` or
{0, 1, ..., `N_side**2 -1`}.
Describes the planar (edge) neighbors of cell0 letter / child cell number
n.
NOTE:
Several RHEALPixDGGS methods have the keyword argument 'plane'.
Setting it to True indicates that all input and output points and cells are
interpreted as lying in the planar DGGS.
Setting it to False indicates that they are interpreted as lying in
the ellipsoidal DGGS.
"""
# Level 0 cell IDs, which are anamolous.
cells0 = ["N", "O", "P", "Q", "R", "S"]
def __init__(
self,
ellipsoid=WGS84_ELLIPSOID,
N_side=3,
north_square=0,
south_square=0,
max_areal_resolution=1,
):
self.N_side = N_side
self.north_square = north_square % 4 # = 0, 1, 2, or 3.
self.south_square = south_square % 4 # = 0, 1, 2, or 3.
self.max_areal_resolution = max_areal_resolution
# Find the maximum grid resolution needed to have ellipsoidal
# cells of area at most max_areal_resolution.
self.max_resolution = int(
ceil(
log(ellipsoid.R_A ** 2 * (2 * pi / 3) / max_areal_resolution)
/ (2 * log(N_side))
)
)
self.ellipsoid = ellipsoid
# Dictionary of the ordering (Morton order) of child cells of a cell
# in terms of the row-column coordinates in the matrix of child cells.
# Child cell are numbered 0 to N_side**2 -1 from left to right and top
# to bottom.
# Here's a diagram of the ordering and coordinates for N_side=3:
#
# 0 | 0 1 2
# 1 | 3 4 5
# 2 | 6 7 8
# --------
# 0 1 2
#
child_order = {}
for (row, col) in product(list(range(N_side)), repeat=2):
order = row * N_side + col
# Handy to have both coordinates and order as dictionary keys.
child_order[(row, col)] = order
child_order[order] = (row, col)
self.child_order = child_order
# Store the upper left vertices of the resolution 0 cells
# in the rHEALPix grid hierarchy for this ellipsoid.
# The default layout by cells0 index is
#
# 0
# 1 2 3 4
# 5.
#
cells0 = RHEALPixDGGS.cells0
ul_vertex = { # Location for radius = 1
cells0[0]: (-pi + self.north_square * pi / 2, 3 * pi / 4),
cells0[1]: (-pi, pi / 4),
cells0[2]: (-pi / 2, pi / 4),
cells0[3]: (0, pi / 4),
cells0[4]: (pi / 2, pi / 4),
cells0[5]: (-pi + self.south_square * pi / 2, -pi / 4),
}
# Scale up ul_vertex by authalic radius of ellipsoid.
self.ul_vertex = {}
for k in list(ul_vertex.keys()):
self.ul_vertex[k] = tuple(self.ellipsoid.R_A * array(ul_vertex[k]))
# Initialize atomic neighbor relationships among cells.
# Dictionary of up, right, down, and left neighbors of
# resolution 0 cells and their subcells 0--(N_side**2 -1),
# aka the atomic neighbors.
# Based on the layouts
#
# 0
# 1 2 3 4 (but folded into a cube) and
# 5
#
# 0 1 2
# 3 4 5
# 6 7 8 (example for N_side=3).
#
an = {}
# Neighbors of cells0[1], ..., cells0[4]
an[cells0[1]] = {
"left": cells0[4],
"right": cells0[2],
"down": cells0[5],
"up": cells0[0],
}
an[cells0[2]] = {
"left": cells0[1],
"right": cells0[3],
"down": cells0[5],
"up": cells0[0],
}
an[cells0[3]] = {
"left": cells0[2],
"right": cells0[4],
"down": cells0[5],
"up": cells0[0],
}
an[cells0[4]] = {
"left": cells0[3],
"right": cells0[1],
"down": cells0[5],
"up": cells0[0],
}
# Neighbors of cells0[0] and cells0[5] depend on
# volues of north_square and south_square, respectively.
nn = self.north_square
an[cells0[0]] = {
"down": cells0[(nn + 0) % 4 + 1],
"right": cells0[(nn + 1) % 4 + 1],
"up": cells0[(nn + 2) % 4 + 1],
"left": cells0[(nn + 3) % 4 + 1],
}
ss = self.south_square
an[cells0[5]] = {
"up": cells0[(ss + 0) % 4 + 1],
"right": cells0[(ss + 1) % 4 + 1],
"down": cells0[(ss + 2) % 4 + 1],
"left": cells0[(ss + 3) % 4 + 1],
}
N = self.N_side
# Neighbors of 0, 1, ..., N**2 - 1.
for i in range(N ** 2):
an[i] = {
"left": i - 1,
"right": i + 1,
"up": (i - N) % N ** 2,
"down": (i + N) % N ** 2,
}
# Adjust left and right edge cases.
for i in range(0, N ** 2, N):
an[i]["left"] = an[i]["left"] + N
for i in range(N - 1, N ** 2, N):
an[i]["right"] = an[i]["right"] - N
self.atomic_neighbors = an
def __str__(self):
result = ["rHEALPix DGGS:"]
result.append(" N_side = %s" % self.N_side)
result.append(" north_square = %s" % self.north_square)
result.append(" south_square = %s" % self.south_square)
result.append(" max_areal_resolution = %s" % self.max_areal_resolution)
result.append(" max_resolution = %s" % self.max_resolution)
result.append(" ellipsoid:")
for (k, v) in sorted(self.ellipsoid.__dict__.items()):
if k == "phi_0":
continue
result.append(" " * 8 + k + " = " + str(v))
return "\n".join(result)
def __eq__(self, other):
return (
other is not None
and self.ellipsoid == other.ellipsoid
and self.N_side == other.N_side
and self.north_square == other.north_square
and self.south_square == other.south_square
and self.max_resolution == other.max_resolution
)
def __ne__(self, other):
return not self.__eq__(other)
def healpix(self, u, v, inverse=False):
"""
Return the HEALPix projection of point `(u, v)` (or its inverse if
`inverse` = True) appropriate to this rHEALPix DGGS.
EXAMPLES::
>>> rdggs = UNIT_003_RADIANS
>>> print(my_round(rdggs.healpix(-pi, pi/2), 14))
(-2.35619449019234, 1.5707963267949)
NOTES:: Issue #1 was ..
(-2.35619449019234, 1.5707963267949001) *
NOTE:
Uses ``pj_healpix`` instead of the PROJ.4 version of HEALPix.
"""
f = pw.Proj(ellipsoid=self.ellipsoid, proj="healpix")
return f(u, v, inverse=inverse)
def rhealpix(self, u, v, inverse=False):
"""
Return the rHEALPix projection of the point `(u, v)` (or its inverse if
`inverse` = True) appropriate to this rHEALPix DGGS.
EXAMPLES::
>>> rdggs = UNIT_003_RADIANS
>>> print(my_round(rdggs.rhealpix(0, pi/3), 14))
(-1.858272006684, 2.06871881030324)
NOTES:: Issue #1 was ..
(-1.8582720066839999, 2.0687188103032401)
NOTE:
Uses ``pj_rhealpix`` instead of the PROJ.4 version of rHEALPix.
"""
f = pw.Proj(
ellipsoid=self.ellipsoid,
proj="rhealpix",
north_square=self.north_square,
south_square=self.south_square,
)
return f(u, v, inverse=inverse)
def combine_triangles(self, u, v, inverse=False):
"""
Return the combine_triangles() transformation of the point `(u, v)`
(or its inverse if `inverse` = True) appropriate to the underlying
ellipsoid.
It maps the HEALPix projection to the rHEALPix projection.
EXAMPLES::
>>> rdggs = UNIT_003
>>> p = (0, 0)
>>> q = (-pi/4, pi/2)
>>> print(rdggs.combine_triangles(*p))
(0.0, 0.0)
>>> print(my_round(rdggs.combine_triangles(*q), 14))
(-2.35619449019234, 1.5707963267949)
NOTES:: Issue #1 was ..
(-2.35619449019234, 1.5707963267949001)
"""
R_A = self.ellipsoid.R_A
ns = self.north_square
ss = self.south_square
# Scale down.
u, v = array((u, v)) / R_A
# Combine triangles.
u, v = pjr.combine_triangles(
u, v, inverse=inverse, north_square=ns, south_square=ss
)
# Scale up.
return tuple(R_A * array((u, v)))
def triangle(self, x, y, inverse=True):
"""
If `inverse` = False, then assume `(x,y)` lies in the image of the
HEALPix projection that comes with this DGGS, and
return the number of the HEALPix polar triangle (0, 1, 2, 3, or None)
and the region ('north_polar', 'south_polar', or 'equatorial') that
`(x, y)` lies in.
If `inverse` = True, then assume `(x, y)` lies in the image of
the rHEALPix projection that comes with this DGGS, map `(x, y)`
to its HEALPix image (x', y'), and return the number of the HEALPix
polar triangle and the region that (x', y') lies in.
If `(x, y)` lies in the equatorial region, then the triangle number
returned is None.
OUTPUT:
The pair (triangle_number, region).
NOTES:
This is a wrapper for pjr.triangle().
EXAMPLES::
>>> rdggs = RHEALPixDGGS()
>>> c = rdggs.cell(['N', 7])
>>> print(rdggs.triangle(*c.nucleus(), inverse=True))
(0, 'north_polar')
>>> c = rdggs.cell(['N', 3])
>>> print(rdggs.triangle(*c.nucleus(), inverse=True))
(3, 'north_polar')
>>> c = rdggs.cell(['P', 3])
>>> print(rdggs.triangle(*c.nucleus(), inverse=True))
(None, 'equatorial')
>>> c = rdggs.cell(['S', 5, 2])
>>> print(rdggs.triangle(*c.nucleus(), inverse=True))
(1, 'south_polar')
"""
R_A = self.ellipsoid.R_A
ns = self.north_square
ss = self.south_square
# Scale down.
x, y = array((x, y)) / R_A
# Get triangle.
return pjr.triangle(x, y, inverse=inverse, north_square=ns, south_square=ss)
def xyz(self, u, v, lonlat=False):
"""
Given a point `(u, v)` in the planar image of the rHEALPix projection,
project it back to the ellipsoid and return its 3D rectangular
coordinates.
If `lonlat` = True, then assume `(u, v)` is a longitude-latitude
point.
EXAMPLES::
>>> rdggs = UNIT_003_RADIANS
>>> print(my_round(rdggs.xyz(0, pi/4, lonlat=True), 14))
(0.70710678118655, 0.0, 0.70710678118655)
NOTES:: Issue #1 was ..
(0.70710678118655002, 0.0, 0.70710678118655002)
"""
if lonlat:
lam, phi = u, v
else:
lam, phi = self.rhealpix(u, v, inverse=True)
return self.ellipsoid.xyz(lam, phi)
def xyz_cube(self, u, v, lonlat=False):
"""
Given a point `(u, v)` in the planar version of this rHEALPix DGGS,
fold the rHEALPix image into a cube centered at the origin,
and return the resulting point's 3D rectangular coordinates.
If `lonlat` = True, then assume `(u, v)` is a longitude-latitude
point.
EXAMPLES::
>>> rdggs = UNIT_003
>>> print(my_round(rdggs.xyz_cube(0, 0), 14))
(0.78539816339745, 0.0, -0.78539816339745)
NOTES:: Issue #1 was ..
(0.78539816339745006, 0.0, -0.78539816339745006)
"""
if lonlat:
x, y = self.rhealpix(u, v)
else:
x, y = u, v
w = self.cell_width(0)
north = self.north_square
south = self.south_square
# Shift rHEALPix projection (with (x, y) in it) so that cell O
# has downleft corner (0, 0).
x, y = array((x, y)) + array((2 * w, w / 2))
# Fold projection.
if y < 0:
# S
x += -south * w
if south == 0:
q = (x, 0, y)
elif south == 1:
q = (y + w, 0, -x)
elif south == 2:
q = (w - x, 0, -y - w)
else:
q = (-y, 0, x - w)
elif y > w:
# N
x += -north * w
if north == 0:
q = (x, w, -y + w)
elif north == 1:
q = (-y + 2 * w, w, -x)
elif north == 2:
q = (-x + w, w, y - 2 * w)
else:
q = (y - w, w, x - w)
elif x < w:
# O
q = (x, y, 0)
elif (x >= w) and (x < 2 * w):
# P
x += -w
q = (w, y, -x)
elif (x >= 2 * w) and (x < 3 * w):
# Q
x += -2 * w
q = (w - x, y, -w)
else:
# R
x += -3 * w
q = (0, y, x - w)
# Translate the cube's center to (0, 0).
q = array(q) + (w / 2) * array((-1, -1, 1))
return tuple(q)
def cell(self, suid=None, level_order_index=None, post_order_index=None):
"""
Return a cell (Cell instance) of this DGGS either from its ID or
from its resolution and index.
EXAMPLES::
>>> rdggs = RHEALPixDGGS()
>>> c = rdggs.cell(('N', 4, 5))
>>> print(isinstance(c, Cell))
True
>>> print(c)
N45
"""
return Cell(self, suid, level_order_index, post_order_index)
def grid(self, resolution):
"""
Generator function for all the cells at resolution `resolution`.
EXAMPLES::
>>> rdggs = RHEALPixDGGS()
>>> grid0 = rdggs.grid(0)
>>> print([str(x) for x in grid0])
['N', 'O', 'P', 'Q', 'R', 'S']
"""
suid = [RHEALPixDGGS.cells0[0]] + [0 for i in range(resolution)]
c = self.cell(suid)
yield c
cs = c.successor(resolution)
while cs:
yield cs
cs = cs.successor(resolution)
def num_cells(self, res_1, res_2=None, subcells=False):
"""
Return the number of cells of resolutions `res_1` to `res_2`
(inclusive).
Assume `res_1 <= res_2`.
If `subcells` = True, then return the number of subcells at resolutions
`res_1` to `res_2` (inclusive) of a cell at resolution `res_1`.
If `res_2=None` and `subcells=False, then return the number of
cells at resolution `res_1`.
If `res_2=None` and `subcells` = True, then return the number of
subcells from resolution `res_1` to resolution `self.max_resolution`.
EXAMPLES::
>>> rdggs = RHEALPixDGGS()
>>> rdggs.num_cells(0)
6
>>> rdggs.num_cells(0, 1)
60
>>> rdggs.num_cells(0, subcells=True)
231627523606480
>>> rdggs.num_cells(0, 1, subcells=True)
10
>>> rdggs.num_cells(5, 6, subcells=True)
10
"""
k = self.N_side ** 2
if subcells:
if (res_2 is None) or (res_2 < res_1):
res_2 = self.max_resolution
num = int((k ** (res_2 - res_1 + 1) - 1) / (k - 1))
else:
if (res_2 is None) or (res_2 < res_1):
res_2 = res_1
num = int(6 * (k ** (res_2 + 1) - k ** res_1) / (k - 1))
return num
def cell_width(self, resolution, plane=True):
"""
Return the width of a planar cell at the given resolution.
If `plane` = False, then return None,
because the ellipsoidal cells don't have constant width.
EXAMPLES::
>>> rdggs = UNIT_003
>>> print(rdggs.cell_width(0) == pi/2)
True
>>> print(rdggs.cell_width(1) == pi/6)
True
"""
if plane:
return self.ellipsoid.R_A * (pi / 2) * self.N_side ** (-resolution)
def cell_area(self, resolution, plane=True):
"""
Return the area of a planar or ellipsoidal cell at the given
resolution.
EXAMPLES::
>>> rdggs = UNIT_003
>>> a = rdggs.cell_area(1)
>>> print(a == (pi/6)**2)
True
>>> print(rdggs.cell_area(1, plane=False) == 8/(3*pi)*a)
True
"""
w = self.cell_width(resolution)
if plane:
return w ** 2
else:
return 8 / (3 * pi) * w ** 2
def interval(self, a, b):
"""
Generator function for all the resolution
`max(a.resolution, b.resolution)` cells between cell
`a` and cell `b` (inclusive and with respect to the
postorder ordering on cells).
Note that `a` and `b` don't have to lie at the same resolution.
EXAMPLES::
>>> rdggs = RHEALPixDGGS()
>>> a = rdggs.cell(('N', 1))
>>> b = rdggs.cell(('N',))
>>> print([str(c) for c in list(rdggs.interval(a, b))])
['N1', 'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'N8']
"""
# Choose the starting cell, which might not be A.
resolution = max(a.resolution, b.resolution)
if a.resolution < resolution:
cell = a.successor(resolution)
else:
cell = Cell(self, a.suid[: resolution + 1])
while cell <= b:
yield cell
cell = cell.successor(resolution)
def cell_from_point(self, resolution, p, plane=True):
"""
Return the resolution `resolution` cell that contains the point `p`.
If `plane` = True, then `p` and the output cell lie in the
planar DGGS.
Otherwise, `p` and the output cell lie in the ellipsoidal DGGS.
EXAMPLES::
>>> rdggs = RHEALPixDGGS()
>>> p = (0, 0)
>>> c = rdggs.cell_from_point(1, p)
>>> print(c)
Q3
"""
# Get the rectangular coordinates of p.
if plane:
x, y = p
else:
x, y = self.rhealpix(*p)
# Determine the resolution 0 cell c0 that (x, y) lies in,
# since resolution 0 cells are anamolous.
ns = self.north_square
ss = self.south_square
R = self.ellipsoid.R_A
if (
y > R * pi / 4
and y < R * 3 * pi / 4
and x > R * (-pi + ns * (pi / 2))
and x < R * (-pi / 2 + ns * (pi / 2))
):
s0 = RHEALPixDGGS.cells0[0]
elif (
y > -R * 3 * pi / 4
and y < -R * pi / 4
and x > R * (-pi + ss * (pi / 2))
and x < R * (-pi / 2 + ss * (pi / 2))
):
s0 = RHEALPixDGGS.cells0[5]
elif y >= -R * pi / 4 and y <= R * pi / 4 and x >= -R * pi and x < -R * pi / 2:
s0 = RHEALPixDGGS.cells0[1]
elif y >= -R * pi / 4 and y <= R * pi / 4 and x >= -R * pi / 2 and x < 0:
s0 = RHEALPixDGGS.cells0[2]
elif y >= -R * pi / 4 and y <= R * pi / 4 and x >= 0 and x < R * pi / 2:
s0 = RHEALPixDGGS.cells0[3]
elif y >= -R * pi / 4 and y <= R * pi / 4 and x >= R * pi / 2 and x < R * pi:
s0 = RHEALPixDGGS.cells0[4]
else:
# (x, y) doesn't lie in the DGGS.
return None
suid = [s0]
if resolution == 0:
# Done.
return Cell(self, suid)
# Compute the horizontal and vertical distances between (x, y) and
# the ul_vertex of c0 as fractions of the width of c0.
w = self.cell_width(0)
dx = abs(x - self.ul_vertex[suid[0]][0]) / w
dy = abs(y - self.ul_vertex[suid[0]][1]) / w
if dx == 1:
# This case is analytically impossible
# but, i guess, numerically possible because of rounding errors.
# Border case. Take a smidgen off dx.
dx -= 0.5 * self.cell_width(self.max_resolution) / w
if dy == 1:
# Border case. Take a smidgen off dy.
dy -= 0.5 * self.cell_width(self.max_resolution) / w
N = self.N_side
# Compute the base N expansions of dx and dy and truncate them
# at index resolution to get the row and column SUIDs of
# the resolution resolution cell c containing (x,y).
suid_row = base_repr(int(float(str(dy * N ** resolution))), N)
suid_col = base_repr(int(float(str(dx * N ** resolution))), N)
# Using int(float(str(.))) instead of the straightforward int(.),
# because the latter gave me rounding errors.
# Prefix with the appropriate amount of zeros.
suid_row = "0" * (resolution - len(suid_row)) + suid_row
suid_col = "0" * (resolution - len(suid_col)) + suid_col
# Use the column and row SUIDs of c to get the SUID of c.
for i in range(resolution):
suid.append(self.child_order[(int(suid_row[i]), int(suid_col[i]))])
return Cell(self, suid)
def cell_from_region(self, ul, dr, plane=True):
"""
Return the smallest planar or ellipsoidal cell wholly containing
the region bounded by the axis-aligned rectangle with upper left
and lower right vertices given by the the points `ul` and `dr`,
respectively.
If such as cell does not exist, then return None.
If `plane` = True, then `ul` and `dr` and the returned cell
lie in the planar DGGS.
Otherwise, `ul` and `dr` and the returned cell lie in the ellipsoidal
DGGS.
To specify an ellipsoidal cap region, set `ul` = (-pi, pi/2) and
`dr` = (-pi, phi) for a northern cap from latitudes pi/2 to phi, or
set `ul` = (-pi, phi) and `dr` = (-pi, -pi/2) for a southern cap from
latitudes phi to -pi/2.
(As usual, if `self.ellipsoid.radians` = False,
then use degrees instead of radians when specifying ul and dr.)
EXAMPLES::
>>> rdggs = UNIT_003
>>> p = (0, pi/12)
>>> q = (pi/6 - 1e-6, 0)
>>> c = rdggs.cell_from_region(p, q)
>>> print(c)
Q3
"""
if not plane:
# Compute planar ul and dr as follows.
# Get all four vertices of the ellipsoidal cap or quadrangle.
PI = self.ellipsoid.pi()
if ul == (-PI, PI / 2) or dr == (-PI, -PI / 2):
# Cap.
if dr[1] != -PI / 2:
phi = dr[1]
else:
phi = ul[1]
vertices = [
(-3 * PI / 4, phi),
(-PI / 4, phi),
(PI / 4, phi),
(3 * PI / 4, phi),
]
else:
# Quadrangle.
vertices = [ul, (ul[0], dr[1]), dr, (dr[0], ul[1])]
# Project the vertices onto the plane.
vertices = [self.rhealpix(*p) for p in vertices]
# Find the upper left and lower right vertices of the
# planar bounding rectangle.
ul = (min([p[0] for p in vertices]), max([p[1] for p in vertices]))
dr = (max([p[0] for p in vertices]), min([p[1] for p in vertices]))
# Find the resolution max_resolution cells containing ul and dr.
resolution = self.max_resolution
ul_cell = self.cell_from_point(resolution, ul)
dr_cell = self.cell_from_point(resolution, dr)
ul_suid = ul_cell.suid
dr_suid = dr_cell.suid
# Find the longest common prefix of ul_suid and dr_suid.
least = resolution + 1 # Default if the suids agree everywhere
for i in range(resolution + 1):
if ul_suid[i] != dr_suid[i]:
least = i
break
if least == 0:
# No one cell contains R.
return None
else:
return self.cell(ul_suid[:least])
def cell_latitudes(self, resolution, phi_min, phi_max, nucleus=True, plane=True):
"""
Return a list of every latitude phi whose parallel intersects
a resolution `resolution` cell nucleus and satisfies
`phi_min` < phi < `phi_max`.
If `plane` = True, then use rHEALPix y-coordinates for `phi_min`,
`phi_max`, and the result. Return the list in increasing order.
If `nucleus` = False, then return a list of every latitude phi whose
parallel intersects the north or south boundary of a resolution
`resolution` cell and that satisfies `phi_min` < phi < `phi_max`.
NOTE:
By convention, the pole latitudes pi/2 and -pi/2 (or their
corresponding rHEALPix y-coordinates) will be excluded.
There are 2*self.N_side**resolution - 1 nuclei
latitudes between the poles if self.N_side is odd and
2*self.N_side**resolution if self.N_side is even.
Consequently, there are 2*self.N_side**resolution
boundary latitudes between the poles if self.N_side is odd and
2*self.N_side**resolution - 1 boundary latitudes if self.N_side is
even.
EXAMPLES::
>>> rdggs = WGS84_003_RADIANS
>>> for phi in rdggs.cell_latitudes(1, -pi/2, pi/2, plane=False):
... print(my_round(phi, 14))
-1.02050584399985
-0.46144314900303
-0.0
0.46144314900303
1.02050584399985
1.5707963267949
NOTES:: .. Issue @1 was ..
-1.020505844
-0.461443149003
-0
0.461443149003
1.020505844
1.57079632679
>>> for phi in rdggs.cell_latitudes(1, -pi/2, pi/2, nucleus=False, plane=False):
... print(my_round(phi, 14))
-1.29836248988994
-0.73083668811327
-0.22457715619516
0.22457715619516
0.73083668811327
1.29836248988994
NOTES:: .. Issue @1 was ..
-1.29836248989
-0.730836688113
-0.224577156195
0.224577156195
0.730836688113
1.29836248989
"""
if phi_min > phi_max:
return []
# Work in the plane first, because that's easier.
R = self.ellipsoid.R_A