/
shgrid.py
3054 lines (2769 loc) · 128 KB
/
shgrid.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
"""
Spherical Harmonic Grid classes
"""
import numpy as _np
import matplotlib as _mpl
import matplotlib.pyplot as _plt
from mpl_toolkits.axes_grid1 import make_axes_locatable as _make_axes_locatable
import copy as _copy
import xarray as _xr
import tempfile as _tempfile
from ..backends import backend_module
from ..backends import preferred_backend
from ..backends import shtools as _shtools
try:
import cartopy.crs as _ccrs
from cartopy.mpl.ticker import LongitudeFormatter as _LongitudeFormatter
from cartopy.mpl.ticker import LatitudeFormatter as _LatitudeFormatter
_cartopy_module = True
except ModuleNotFoundError:
_cartopy_module = False
try:
import pygmt as _pygmt
_pygmt_module = True
except ModuleNotFoundError:
_pygmt_module = False
class SHGrid(object):
"""
Class for spatial gridded data on the sphere.
Grids can be initialized from:
x = SHGrid.from_array(array)
x = SHGrid.from_xarray(data_array)
x = SHGrid.from_netcdf(netcdf)
x = SHGrid.from_file('fname.dat')
x = SHGrid.from_zeros(lmax)
x = SHGrid.from_cap(theta, clat, clon, lmax)
x = SHGrid.from_ellipsoid(lmax, a, b, c)
The class instance defines the following class attributes:
data : Gridded array of the data.
nlat, nlon : The number of latitude and longitude bands in the grid.
n : The number of samples in latitude for 'DH' grids.
lmax : The maximum spherical harmonic degree that can be resolved
by the grid sampling.
sampling : The longitudinal sampling for Driscoll and Healy grids. Either
1 for equally sampled grids (nlat=nlon) or 2 for equally
spaced grids in degrees.
kind : Either 'real' or 'complex' for the data type.
grid : Either 'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-
Legendre Quadrature grids.
units : The units of the gridded data.
zeros : The cos(colatitude) nodes used with Gauss-Legendre
Quadrature grids. Default is None.
weights : The latitudinal weights used with Gauss-Legendre
Quadrature grids. Default is None.
extend : True if the grid contains the redundant column for 360 E and
(for 'DH' grids) the unnecessary row for 90 S.
Each class instance provides the following methods:
to_array() : Return the raw gridded data as a numpy array.
to_xarray() : Return the gridded data as an xarray DataArray.
to_file() : Save gridded data to a text or binary file.
to_netcdf() : Return the gridded data as a netcdf formatted file or
object.
to_real() : Return a new SHGrid class instance of the real component
of the data.
to_imag() : Return a new SHGrid class instance of the imaginary
component of the data.
lats() : Return a vector containing the latitudes of each row
of the gridded data.
lons() : Return a vector containing the longitudes of each column
of the gridded data.
histogram() : Return an area-weighted histogram of the gridded data.
expand() : Expand the grid into spherical harmonics.
max() : Return the maximum value of data using numpy.max().
min() : Return the minimum value of data using numpy.min().
copy() : Return a copy of the class instance.
plot() : Plot the data.
plotgmt() : Plot projected data using the generic mapping tools
(GMT).
plot3d() : Plot a 3-dimensional representation of the data.
plot_histogram() : Plot a histogram of the area-weighted gridded data.
info() : Print a summary of the data stored in the SHGrid
instance.
"""
def __init__():
"""Unused constructor of the super class."""
print('Initialize the class using one of the class methods:\n'
'>>> pyshtools.SHGrid.from_array\n'
'>>> pyshtools.SHGrid.from_xarray\n'
'>>> pyshtools.SHGrid.from_netcdf\n'
'>>> pyshtools.SHGrid.from_file\n'
'>>> pyshtools.SHGrid.from_zeros\n'
'>>> pyshtools.SHGrid.from_cap\n'
'>>> pyshtools.SHGrid.from_ellipsoid\n')
# ---- Factory methods ----
@classmethod
def from_array(self, array, grid='DH', units=None, copy=True):
"""
Initialize the class instance from an input array.
Usage
-----
x = SHGrid.from_array(array, [grid, units, copy])
Returns
-------
x : SHGrid class instance
Parameters
----------
array : ndarray, shape (nlat, nlon)
2-D numpy array of the gridded data, where nlat and nlon are the
number of latitudinal and longitudinal bands, respectively.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-Legendre
Quadrature grids, respectively.
units : str, optional, default = None
The units of the gridded data.
copy : bool, optional, default = True
If True (default), make a copy of array when initializing the class
instance. If False, initialize the class instance with a reference
to array.
"""
if _np.iscomplexobj(array):
kind = 'complex'
else:
kind = 'real'
if type(grid) is not str:
raise ValueError('grid must be a string. Input type is {:s}.'
.format(str(type(grid))))
if grid.upper() not in set(['DH', 'GLQ']):
raise ValueError(
"grid must be 'DH' or 'GLQ'. Input value is {:s}."
.format(repr(grid))
)
for cls in self.__subclasses__():
if cls.istype(kind) and cls.isgrid(grid):
return cls(array, units=units, copy=copy)
@classmethod
def from_zeros(self, lmax, grid='DH', kind='real', sampling=2,
units=None, extend=True, empty=False):
"""
Initialize the class instance using an array of zeros.
Usage
-----
x = SHGrid.from_zeros(lmax, [grid, kind, sampling, units, extend,
empty])
Returns
-------
x : SHGrid class instance
Parameters
----------
lmax : int
The maximum spherical harmonic degree resolvable by the grid.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss Legendre
Quadrature grids, respectively.
kind : str, optional, default = 'real'
Either 'real' or 'complex' for the data type.
sampling : int, optional, default = 2
The longitudinal sampling for Driscoll and Healy grids. Either 1
for equally sampled grids (nlong=nlat) or 2 for equally spaced
grids in degrees (nlong=2*nlat with extend=False or nlong=2*nlat-1
with extend=True).
units : str, optional, default = None
The units of the gridded data.
extend : bool, optional, default = True
If True, include the longitudinal band for 360 E (DH and GLQ grids)
and the latitudinal band for 90 S (DH grids only).
empty : bool, optional, default = False
If True, create the data array using numpy.empty() and do not
initialize with zeros.
"""
if type(grid) is not str:
raise ValueError('grid must be a string. Input type is {:s}.'
.format(str(type(grid))))
if grid.upper() not in set(['DH', 'GLQ']):
raise ValueError("grid must be 'DH' or 'GLQ'. " +
"Input value is {:s}.".format(repr(grid)))
if grid.upper() == 'DH':
nlat = 2 * lmax + 2
if sampling == 1:
nlon = nlat
else:
nlon = nlat * 2
if extend:
nlat += 1
nlon += 1
elif grid.upper() == 'GLQ':
nlat = lmax + 1
nlon = 2 * nlat - 1
if extend:
nlon += 1
if kind == 'real':
if empty:
array = _np.empty((nlat, nlon), dtype=_np.float64)
else:
array = _np.zeros((nlat, nlon), dtype=_np.float64)
else:
if empty:
array = _np.empty((nlat, nlon), dtype=_np.complex128)
else:
array = _np.zeros((nlat, nlon), dtype=_np.complex128)
for cls in self.__subclasses__():
if cls.istype(kind) and cls.isgrid(grid):
return cls(array, units=units, copy=False)
@classmethod
def from_ellipsoid(self, lmax, a, b=None, c=None, grid='DH', kind='real',
sampling=2, units=None, extend=True):
"""
Initialize the class instance with a triaxial ellipsoid whose principal
axes are aligned with the x, y, and z axes.
Usage
-----
x = SHGrid.from_ellipsoid(lmax, a, [b, c, grid, kind, sampling,
units, extend])
Returns
-------
x : SHGrid class instance
Parameters
----------
a : float
Length of the principal axis aligned with the x axis.
b : float, optional, default = a
Length of the principal axis aligned with the y axis.
c : float, optional, default = b
Length of the principal axis aligned with the z axis.
lmax : int
The maximum spherical harmonic degree resolvable by the grid.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-Legendre
Quadrature grids, respectively.
kind : str, optional, default = 'real'
Either 'real' or 'complex' for the data type.
sampling : int, optional, default = 2
The longitudinal sampling for Driscoll and Healy grids. Either 1
for equally sampled grids (nlong=nlat) or 2 for equally spaced
grids in degrees (nlong=2*nlat with extend=False or nlong=2*nlat-1
with extend=True).
units : str, optional, default = None
The units of the gridded data.
extend : bool, optional, default = True
If True, include the longitudinal band for 360 E (DH and GLQ grids)
and the latitudinal band for 90 S (DH grids only).
"""
temp = self.from_zeros(lmax, grid=grid, kind=kind, sampling=sampling,
units=units, extend=extend, empty=True)
if c is None and b is None:
temp.data[:, :] = a
elif c is not None and b is None:
for ilat, lat in enumerate(temp.lats()):
temp.data[ilat, :] = 1. / _np.sqrt(
_np.cos(_np.deg2rad(lat))**2 / a**2 +
_np.sin(_np.deg2rad(lat))**2 / c**2
)
else:
if c is None:
c = b
cos2 = _np.cos(_np.deg2rad(temp.lons()))**2
sin2 = _np.sin(_np.deg2rad(temp.lons()))**2
for ilat, lat in enumerate(temp.lats()):
temp.data[ilat, :] = 1. / _np.sqrt(
_np.cos(_np.deg2rad(lat))**2 * cos2 / a**2 +
_np.cos(_np.deg2rad(lat))**2 * sin2 / b**2 +
_np.sin(_np.deg2rad(lat))**2 / c**2
)
return temp
@classmethod
def from_cap(self, theta, clat, clon, lmax, grid='DH', kind='real',
sampling=2, degrees=True, units=None, extend=True):
"""
Initialize the class instance with an array equal to unity within
a spherical cap and zero elsewhere.
Usage
-----
x = SHGrid.from_cap(theta, clat, clon, lmax, [grid, kind, sampling,
degrees, units, extend])
Returns
-------
x : SHGrid class instance
Parameters
----------
theta : float
The angular radius of the spherical cap, default in degrees.
clat, clon : float
Latitude and longitude of the center of the rotated spherical cap
(default in degrees).
lmax : int
The maximum spherical harmonic degree resolvable by the grid.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-Legendre
Quadrature grids, respectively.
kind : str, optional, default = 'real'
Either 'real' or 'complex' for the data type.
sampling : int, optional, default = 2
The longitudinal sampling for Driscoll and Healy grids. Either 1
for equally sampled grids (nlong=nlat) or 2 for equally spaced
grids in degrees (nlong=2*nlat with extend=False or nlong=2*nlat-1
with extend=True).
degrees : bool, optional = True
If True, theta, clat, and clon are in degrees.
units : str, optional, default = None
The units of the gridded data.
extend : bool, optional, default = True
If True, include the longitudinal band for 360 E (DH and GLQ grids)
and the latitudinal band for 90 S (DH grids only).
"""
temp = self.from_zeros(lmax, grid=grid, kind=kind, sampling=sampling,
units=units, extend=extend)
if degrees is True:
theta = _np.deg2rad(theta)
clat = _np.deg2rad(clat)
clon = _np.deg2rad(clon)
# Set array equal to 1 within the cap
lats = temp.lats(degrees=False)
lons = temp.lons(degrees=False)
imin = _np.inf
imax = 0
for i, lat in enumerate(lats):
if lat <= clat + theta:
if i <= imin:
imin = i
if lat >= clat - theta:
if i >= imax:
imax = i
x = _np.cos(clat) * _np.cos(clon)
y = _np.cos(clat) * _np.sin(clon)
z = _np.sin(clat)
coslon = _np.cos(lons)
sinlon = _np.sin(lons)
costheta = _np.cos(theta)
for i in range(imin, imax+1):
coslat = _np.cos(lats[i])
sinlat = _np.sin(lats[i])
for j in range(0, temp.nlon):
dist = coslat * (x * coslon[j] + y * sinlon[j]) + z * sinlat
if dist >= costheta:
# ie. _np.arccos(dist) <= theta
# since 0 <= theta <= pi/2 and 0 <= dist <= 1
# cos is decreasing
temp.data[i, j] = 1.
return temp
@classmethod
def from_file(self, fname, binary=False, grid='DH', units=None, **kwargs):
"""
Initialize the class instance from gridded data in a file.
Usage
-----
x = SHGrid.from_file(fname, [binary, grid, units, **kwargs])
Returns
-------
x : SHGrid class instance
Parameters
----------
fname : str
The filename containing the gridded data. For text files (default)
the file is read using the numpy routine loadtxt(), whereas for
binary files, the file is read using numpy.load(). For Driscoll and
Healy grids, the dimensions of the array must be nlon=nlat,
nlon=2*nlat or nlon=2*nlat-1. For Gauss-Legendre Quadrature grids,
the dimensions of the array must be nlon=2*nlat-1 or nlon=2*nlat.
For text files, if the filename ends in '.gz', the file will be
decompressed using gzip.
binary : bool, optional, default = False
If False, read a text file. If True, read a binary 'npy' file.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-Legendre
Quadrature grids, respectively.
units : str, optional, default = None
The units of the gridded data.
**kwargs : keyword arguments, optional
Keyword arguments of numpy.loadtxt() or numpy.load().
"""
if binary is False:
data = _np.loadtxt(fname, **kwargs)
elif binary is True:
data = _np.load(fname, **kwargs)
else:
raise ValueError('binary must be True or False. '
'Input value is {:s}.'.format(binary))
return self.from_array(data, grid=grid, units=units, copy=False)
@classmethod
def from_xarray(self, data_array, grid='DH', units=None):
"""
Initialize the class instance from an xarray DataArray object.
Usage
-----
x = SHGrid.from_xarray(data_array, [grid])
Returns
-------
x : SHGrid class instance
Parameters
----------
xarray : xarray DataArray
The xarray DataArray containing the gridded data. For Driscoll and
Healy grids, the dimensions of the array must be nlon=nlat,
nlon=2*nlat or nlon=2*nlat-1. For Gauss-Legendre Quadrature grids,
the dimensions of the array must be nlon=2*nlat-1 or nlon=2*nlat.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-Legendre
Quadrature grids, respectively.
units : str, optional, default = None
The units of the gridded data.
"""
try:
units = data_array.units
except:
pass
return self.from_array(data_array.values, grid=grid, units=units)
@classmethod
def from_netcdf(self, netcdf, grid='DH', units=None):
"""
Initialize the class instance from a netcdf formatted file or object.
Usage
-----
x = SHGrid.from_netcdf(netcdf, [grid])
Returns
-------
x : SHGrid class instance
Parameters
----------
netcdf : str or netcdf object
The name of a netcdf file or object.
grid : str, optional, default = 'DH'
'DH' or 'GLQ' for Driscoll and Healy grids or Gauss-Legendre
Quadrature grids, respectively.
units : str, optional, default = None
The units of the gridded data.
"""
data_array = _xr.open_dataarray(netcdf)
try:
units = data_array.units
except:
pass
return self.from_array(data_array.values, grid=grid, units=units)
# ---- I/O methods ----
def copy(self):
"""
Return a deep copy of the class instance.
Usage
-----
copy = x.copy()
"""
return _copy.deepcopy(self)
def to_file(self, filename, binary=False, **kwargs):
"""
Save gridded data to a file.
Usage
-----
x.to_file(filename, [binary, **kwargs])
Parameters
----------
filename : str
Name of output file. For text files (default), the file will be
compressed using gzip if filename ends in '.gz.'
binary : bool, optional, default = False
If False, save as text using numpy.savetxt(). If True, save as a
'npy' binary file using numpy.save().
**kwargs : keyword arguments, optional
Keyword arguments of numpy.savetxt() and numpy.save().
"""
if binary is False:
_np.savetxt(filename, self.data, **kwargs)
elif binary is True:
_np.save(filename, self.data, **kwargs)
else:
raise ValueError('binary must be True or False. '
'Input value is {:s}.'.format(binary))
def to_xarray(self, title=None, comment='pyshtools grid',
long_name=None, units=None):
"""
Return the gridded data as an xarray DataArray.
Usage
-----
x.to_xarray([title, comment, long_name, units])
Parameters
----------
title : str, optional, default = None
Title of the dataset.
comment : str, optional, default = 'pyshtools grid'
Additional information about how the data were generated.
long_name : str, optional, default = None
A long descriptive name of the gridded data, used to label a
colorbar.
units : str, optional, default = None
Units of the gridded data, used to label a colorbar.
"""
attrs = {'actual_range': [self.min(), self.max()],
'comment': comment,
'nlat': self.nlat,
'nlon': self.nlon,
'lmax': self.lmax,
'kind': self.kind,
'grid': self.grid,
'extend': repr(self.extend)
}
if self.grid == 'GLQ':
attrs['zeros'] = self.zeros
attrs['weights'] = self.weights
else:
attrs['sampling'] = self.sampling
if title is not None:
attrs['title'] = title
if long_name is not None:
attrs['long_name'] = long_name
if units is None:
units = self.units
if units is not None:
attrs['units'] = units
da = _xr.DataArray(self.to_array(),
coords=[('lat', self.lats(),
{'long_name': 'latitude',
'units': 'degrees_north',
'actual_range': [self.lats()[0],
self.lats()[-1]]}),
('lon', self.lons(),
{'long_name': 'longitude',
'units': 'degrees_east',
'actual_range': [self.lons()[0],
self.lons()[-1]]})],
attrs=attrs)
if _pygmt_module:
da.gmt.registration = 0
da.gmt.gtype = 1
return da
def to_netcdf(self, filename=None, title=None, description=None,
comment='pyshtools grid', name='data',
long_name=None, units=None, dtype='d'):
"""
Return the gridded data as a netcdf formatted file or object.
Usage
-----
x.to_netcdf([filename, title, description, comment, name, long_name,
units, dtype])
Parameters
----------
filename : str, optional, default = None
Name of output file.
title : str, optional, default = None
Title of the dataset.
description : str, optional, default = None
Description of the dataset ('Remark' in gmt grd files).
comment : str, optional, default = 'pyshtools grid'
Additional information about how the data were generated.
name : str, optional, default = 'data'
Name of the data array.
long_name : str, optional, default = None
A long descriptive name of the gridded data.
units : str, optional, default = None
Units of the gridded data.
dtype : str, optional, default = 'd'
Data type of the output array. Either 'f' or 'd' for single or
double precision floating point, respectively.
"""
if self.kind == 'complex':
raise RuntimeError('netcdf files do not support complex data '
'formats.')
_data = self.to_xarray(title=title, comment=comment,
long_name=long_name, units=units)
if dtype == 'f':
_data.values = _data.values.astype(_np.float32)
elif dtype != 'd':
raise ValueError("dtype must be either 'f' or 'd' for single or "
"double precision floating point.")
attrs = {}
if title is not None:
attrs['title'] = title
if description is not None:
attrs['description'] = description
if comment is not None:
attrs['comment'] = comment
if units is None:
units = self.units
if units is not None:
attrs['units'] = units
_dataset = _xr.Dataset({name: _data}, attrs=attrs)
if filename is None:
return _dataset.to_netcdf()
else:
_dataset.to_netcdf(filename)
def to_array(self):
"""
Return the raw gridded data as a numpy array.
Usage
-----
grid = x.to_array()
Returns
-------
grid : ndarray, shape (nlat, nlon)
2-D numpy array of the gridded data.
"""
return _np.copy(self.data)
def to_real(self):
"""
Return a new SHGrid class instance of the real component of the data.
Usage
-----
grid = x.to_real()
Returns
-------
grid : SHGrid class instance
"""
return SHGrid.from_array(self.to_array().real, grid=self.grid,
units=self.units, copy=False)
def to_imag(self):
"""
Return a new SHGrid class instance of the imaginary component of the
data.
Usage
-----
grid = x.to_imag()
Returns
-------
grid : SHGrid class instance
"""
return SHGrid.from_array(self.to_array().imag, grid=self.grid,
units=self.units, copy=False)
def info(self):
"""
Print a summary of the data stored in the SHGrid instance.
Usage
-----
x.info()
"""
print(repr(self))
# -------------------------------------------------------------------------
# Mathematical operators
#
# All operations ignore the units of the coefficients, with the
# exception of multiplying and dividing by a scalar.
# -------------------------------------------------------------------------
def min(self):
"""
Return the minimum value of self.data using numpy.min().
Usage
-----
x.min()
"""
return _np.min(self.data)
def max(self):
"""
Return the maximum value of self.data using numpy.max().
Usage
-----
x.max()
"""
return _np.max(self.data)
def __add__(self, other):
"""Add two similar grids or a grid and a scaler: self + other."""
if isinstance(other, SHGrid):
if (self.grid == other.grid and self.data.shape ==
other.data.shape and self.kind == other.kind):
data = self.data + other.data
return SHGrid.from_array(data, grid=self.grid)
else:
raise ValueError('The two grids must be of the '
'same kind and have the same shape and '
'units.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not add a complex constant to a '
'real grid.')
data = self.data + other
return SHGrid.from_array(data, grid=self.grid)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __radd__(self, other):
"""Add two similar grids or a grid and a scaler: self + other."""
return self.__add__(other)
def __sub__(self, other):
"""Subtract two similar grids or a grid and a scaler: self - other."""
if isinstance(other, SHGrid):
if (self.grid == other.grid and self.data.shape ==
other.data.shape and self.kind == other.kind):
data = self.data - other.data
return SHGrid.from_array(data, grid=self.grid)
else:
raise ValueError('The two grids must be of the '
'same kind and have the same shape and '
'units.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not subtract a complex constant from '
'a real grid.')
data = self.data - other
return SHGrid.from_array(data, grid=self.grid)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __rsub__(self, other):
"""Subtract two similar grids or a grid and a scaler: other - self."""
if isinstance(other, SHGrid):
if (self.grid == other.grid and self.data.shape ==
other.data.shape and self.kind == other.kind):
data = other.data - self.data
return SHGrid.from_array(data, grid=self.grid)
else:
raise ValueError('The two grids must be of the '
'same kind and have the same shape and '
'units.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not subtract a complex constant from '
'a real grid.')
data = other - self.data
return SHGrid.from_array(data, grid=self.grid)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __mul__(self, other):
"""Multiply two similar grids or a grid and a scaler: self * other."""
if isinstance(other, SHGrid):
if (self.grid == other.grid and self.data.shape ==
other.data.shape and self.kind == other.kind):
data = self.data * other.data
return SHGrid.from_array(data, grid=self.grid)
else:
raise ValueError('The two grids must be of the '
'same kind and have the same shape.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not multiply a real grid by a complex '
'constant.')
data = self.data * other
return SHGrid.from_array(data, grid=self.grid, units=self.units)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __rmul__(self, other):
"""Multiply two similar grids or a grid and a scaler: other * self."""
return self.__mul__(other)
def __truediv__(self, other):
"""
Divide two similar grids or a grid and a scalar.
"""
if isinstance(other, SHGrid):
if (self.grid == other.grid and self.data.shape ==
other.data.shape and self.kind == other.kind):
data = self.data / other.data
return SHGrid.from_array(data, grid=self.grid)
else:
raise ValueError('The two grids must be of the '
'same kind and have the same shape.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not divide a real grid by a complex '
'constant.')
data = self.data / other
return SHGrid.from_array(data, grid=self.grid, units=self.units)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __pow__(self, other):
"""Raise a grid to a scalar power: pow(self, other)."""
if _np.isscalar(other) is True:
return SHGrid.from_array(pow(self.data, other), grid=self.grid)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __abs__(self):
"""Return the absolute value of the gridded data."""
return SHGrid.from_array(abs(self.data), grid=self.grid)
def __repr__(self):
str = ('kind = {:s}\n'
'grid = {:s}\n'.format(repr(self.kind), repr(self.grid)))
if self.grid == 'DH':
str += ('n = {:d}\n'
'sampling = {:d}\n'.format(self.n, self.sampling))
str += ('nlat = {:d}\n'
'nlon = {:d}\n'
'lmax = {:d}\n'
'units = {:s}\n'
'extend = {}'.format(self.nlat, self.nlon, self.lmax,
repr(self.units), self.extend))
return str
# ---- Extract grid properties ----
def lats(self, degrees=True):
"""
Return the latitudes of each row of the gridded data.
Usage
-----
lats = x.lats([degrees])
Returns
-------
lats : ndarray, shape (nlat)
1-D numpy array of size nlat containing the latitude of each row
of the gridded data.
Parameters
----------
degrees : bool, optional, default = True
If True, the output will be in degrees. If False, the output will
be in radians.
"""
if degrees is False:
return _np.radians(self._lats())
else:
return self._lats()
def lons(self, degrees=True):
"""
Return the longitudes of each column of the gridded data.
Usage
-----
lons = x.get_lon([degrees])
Returns
-------
lons : ndarray, shape (nlon)
1-D numpy array of size nlon containing the longitude of each row
of the gridded data.
Parameters
----------
degrees : bool, optional, default = True
If True, the output will be in degrees. If False, the output will
be in radians.
"""
if degrees is False:
return _np.radians(self._lons())
else:
return self._lons()
# ---- Functions that act on the data ----
def histogram(self, bins=10, range=None):
"""
Return an area-weighted histogram of the gridded data, normalized such
that the integral over the range is unity.
Usage
-----
hist, bin_edges = x.historgram([bins, range])
Returns
-------
hist : array
The values of the histogram, normalized such that the integral over
the range in unity.
bin_edges : array
The values of the edges of the histogram bins.
Parameters
----------
bins : int or sequence of scalars or str, optional, default = 10
If bins is an int, it defines the number of equal-width bins in
the given range. If bins is a sequence, it defines a monotonically
increasing array of bin edges, including the rightmost edge,
allowing for non-uniform bin widths. If bins is a string, it
defines the method used to calculate the optimal bin width, as
defined by numpy.histogram_bin_edges.
range : (float, float), optional, default = None
The lower and upper range of the bins.
Notes
-----
This method does not work with complex data.
"""
return self._histogram(bins=bins, range=range)
def expand(self, normalization='4pi', csphase=1, lmax_calc=None,
backend=None, nthreads=None):
"""
Expand the grid into spherical harmonics.
Usage
-----
clm = x.expand([normalization, csphase, lmax_calc, backend, nthreads])
Returns
-------
clm : SHCoeffs class instance
Parameters
----------
normalization : str, optional, default = '4pi'
Normalization of the output class: '4pi', 'ortho', 'schmidt', or
'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt
semi-normalized, or unnormalized coefficients, respectively.
csphase : int, optional, default = 1
Condon-Shortley phase convention: 1 to exclude the phase factor,
or -1 to include it.
lmax_calc : int, optional, default = x.lmax
Maximum spherical harmonic degree to return.
backend : str, optional, default = preferred_backend()
Name of the preferred backend, either 'shtools' or 'ducc'.
nthreads : int, optional, default = 1
Number of threads to use for the 'ducc' backend. Setting this
parameter to 0 will use as many threads as there are hardware
threads on the system.
Notes
-----
When expanding a Driscoll and Healy (1994) sampled grid (grid='DH' or
'DH2') into spherical harmonic coefficients, the latitudinal bands at
90 N and S are downweighted to zero and have no influence on the
returned spherical harmonic coefficients.
"""
if type(normalization) is not str:
raise ValueError('normalization must be a string. ' +
'Input type is {:s}.'
.format(str(type(normalization))))