/
shwindow.py
1977 lines (1761 loc) · 84.3 KB
/
shwindow.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
"""
Class for localized spectral analyses on the sphere.
SHWindow: SHWindowCap, SHWindowMask
"""
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
from ..backends import shtools as _shtools
from ..spectralanalysis import spectrum as _spectrum
from .shcoeffs import SHCoeffs
from .shgrid import SHGrid
__all__ = ['SHWindow', 'SHWindowCap', 'SHWindowMask']
class SHWindow(object):
"""
Class for localized spectral analyses on the sphere.
The windows can be initialized from:
>>> x = SHWindow.from_cap()
>>> x = SHWindow.from_mask()
Each class instance defines the following class attributes:
name : The name of the class isntance.
kind : Either 'cap' or 'mask'.
tapers : Matrix containing the spherical harmonic coefficients
(in packed form) of either the unrotated spherical cap
localization windows or the localization windows
corresponding to the input mask.
coeffs : Array of spherical harmonic coefficients of the
rotated spherical cap localization windows. These are
'4pi' normalized and do not use the Condon-Shortley phase
factor.
shannon : The Shannon number, which approximates the number of
well localized windows.
area : Area of the concentration domain, in radians.
eigenvalues : Concentration factors of the localization windows.
orders : The angular orders for each of the spherical cap
localization windows.
weights : Taper weights used with the multitaper spectral analyses.
Defaut is None.
lwin : Spherical harmonic bandwidth of the localization windows.
theta : Angular radius of the spherical cap localization domain
(default in degrees).
theta_degrees : True (default) if theta is in degrees.
nwin : The number of localization windows. Default is
(lwin+1)**2.
nwinrot : The number of best-concentrated spherical cap
localization windows that were rotated
and whose coefficients are stored in coeffs.
clat, clon : Latitude and longitude of the center of the rotated
spherical cap localization windows (default in degrees).
coord_degrees : True (default) if clat and clon are in degrees.
taper_degrees : Boolean or int array defining which spherical harmonic
degrees were used to construct the windows.
Each class instance provides the following methods:
to_array() : Return an array of the spherical harmonic
coefficients for taper i, where i=0 is the best
concentrated, optionally using a different
normalization convention.
to_shcoeffs() : Return the spherical harmonic coefficients of taper
i, where i=0 is the best concentrated, as a new
SHCoeffs class instance, optionally using a
different normalization convention.
to_shgrid() : Return as a new SHGrid instance a grid of taper i,
where i=0 is the best concentrated window.
number_concentrated() : Return the number of windows that have
concentration factors greater or equal to a
specified value.
degrees() : Return an array containing the spherical harmonic
degrees of the localization windows, from 0 to
lwin.
spectra() : Return the spectra of one or more localization
windows.
rotate() : Rotate the spherical cap tapers, originally located
at the north pole, to clat and clon and save the
spherical harmonic coefficients in the attribute
coeffs.
coupling_matrix() : Return the coupling matrix of the first nwin
localization windows.
biased_spectrum() : Calculate the multitaper (cross-) spectrum
expectation of a localized function.
multitaper_spectrum() : Return the multitaper power spectrum
estimate and uncertainty for the input
SHCoeffs class instance.
multitaper_cross_spectrum() : Return the multitaper cross-power
spectrum estimate and uncertainty for
two input SHCoeffs class instances.
variance() : Compute the theoretical variance of a windowed
function for a given input power spectrum.
copy() : Return a copy of the class instance.
plot_windows() : Plot the best concentrated localization windows
using a simple cylindrical projection.
plot_spectra() : Plot the spectra of the best-concentrated
localization windows.
plot_coupling_matrix() : Plot the multitaper coupling matrix.
info() : Print a summary of the data stored in the SHWindow
instance.
"""
def __init__(self):
"""Initialize with a factory method."""
print('Initialize the class using one of the class methods:\n'
'>>> pyshtools.SHWindow.from_cap\n'
'>>> pyshtools.SHWindow.from_mask')
# ---- factory methods:
@classmethod
def from_cap(cls, theta, lwin, clat=None, clon=None, nwin=None,
theta_degrees=True, coord_degrees=True, dj_matrix=None,
weights=None, taper_degrees=None, name=None):
"""
Construct spherical cap localization windows.
Usage
-----
x = SHWindow.from_cap(theta, lwin, [clat, clon, nwin, theta_degrees,
coord_degrees, dj_matrix, weights,
taper_degrees, name])
Returns
-------
x : SHWindow class instance
Parameters
----------
theta : float
Angular radius of the spherical cap localization domain (default
in degrees).
lwin : int
Spherical harmonic bandwidth of the localization windows.
clat, clon : float, optional, default = None
Latitude and longitude of the center of the rotated spherical cap
localization windows (default in degrees).
nwin : int, optional, default = (lwin+1)**2
Number of localization windows.
theta_degrees : bool, optional, default = True
True if theta is in degrees.
coord_degrees : bool, optional, default = True
True if clat and clon are in degrees.
dj_matrix : ndarray, optional, default = None
The djpi2 rotation matrix computed by a call to djpi2.
weights : ndarray, optional, default = None
Taper weights used with the multitaper spectral analyses.
taper_degrees : bool or int, optional, dimension (lmax+1),
default = None
Boolean or int array defining which spherical harmonic degrees were
used (True or 1) to construct the windows.
name : str, optional, default = None
The name of the class instance.
"""
if theta_degrees:
tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(
_np.radians(theta), lwin, degrees=taper_degrees)
else:
tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(
theta, lwin, degrees=taper_degrees)
return SHWindowCap(theta, tapers, eigenvalues, taper_order,
clat, clon, nwin, theta_degrees, coord_degrees,
dj_matrix, weights, taper_degrees, copy=False,
name=name)
@classmethod
def from_mask(cls, dh_mask, lwin, nwin=None, weights=None,
taper_degrees=None, name=None):
"""
Construct localization windows that are optimally concentrated within
the region specified by a mask.
Usage
-----
x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights, taper_degrees,
name])
Returns
-------
x : SHWindow class instance
Parameters
----------
dh_mask :ndarray or SHGrid class instance, shape (nlat, nlon)
A Driscoll and Healy sampled grid describing the concentration
region R. All elements should either be 1 or 0 for inside or
outside of the concentration region, respectively. The grid must
have dimensions nlon=nlat, nlon=2*nlat, or nlon=2*nlat-1.
lwin : int
The spherical harmonic bandwidth of the localization windows.
nwin : int, optional, default = (lwin+1)**2
The number of best-concentrated eigenvalues and eigenfunctions to
return.
weights : ndarray, optional, default = None
Taper weights used with the multitaper spectral analyses.
taper_degrees : bool or int, optional, dimension (lmax+1),
default = None
Boolean or int array defining which spherical harmonic degrees were
used (True or 1) to construct the windows.
name : str, optional, default = None
The name of the class instance.
"""
if nwin is None:
nwin = (lwin + 1)**2
else:
if nwin > (lwin + 1)**2:
raise ValueError('nwin must be less than or equal to ' +
'(lwin + 1)**2. lwin = {:d} and nwin = {:d}.'
.format(lwin, nwin))
if isinstance(dh_mask, _np.ndarray):
mask = SHGrid.from_array(dh_mask, grid='DH', copy=False)
data = mask.data[:mask.nlat-mask.extend, :mask.nlon-mask.extend]
area = 4 * _np.pi * mask.expand(lmax_calc=0).coeffs[0, 0, 0]
elif isinstance(dh_mask, SHGrid):
if dh_mask.grid != 'DH':
raise ValueError("The grid type of dh_mask must be 'DH'. "
'Input grid is {:s}.'
.format(repr(dh_mask.grid)))
data = dh_mask.data[:dh_mask.nlat-dh_mask.extend,
:dh_mask.nlon-dh_mask.extend]
area = 4 * _np.pi * dh_mask.expand(lmax_calc=0).coeffs[0, 0, 0]
else:
raise ValueError('dh_mask must be an numpy.ndarrary or '
'pyshtools.SHGrid class instance. '
'Input type is {:s}.'
.format(str(type(dh_mask))))
tapers, eigenvalues = _shtools.SHReturnTapersMap(
data, lwin, ntapers=nwin, degrees=taper_degrees)
return SHWindowMask(tapers, eigenvalues, weights, area, taper_degrees,
copy=False, name=name)
def copy(self):
"""Return a deep copy of the class instance."""
return _copy.deepcopy(self)
def degrees(self):
"""
Return a numpy array listing the spherical harmonic degrees of the
localization windows from 0 to lwin.
Usage
-----
degrees = x.degrees()
Returns
-------
degrees : ndarray, shape (lwin+1)
numpy ndarray containing a list of the spherical harmonic degrees.
"""
return _np.arange(self.lwin + 1)
def number_concentrated(self, concentration):
"""
Return the number of localization windows that have concentration
factors greater or equal to alpha.
Usage
-----
k = x.number_concentrated(alpha)
Returns
-------
k : int
The number of windows with concentration factors greater or equal
to alpha.
Parameters
----------
alpha : float
The concentration factor, which is the power of the window within
the concentration region divided by the total power.
"""
return len(self.eigenvalues[self.eigenvalues >= concentration])
def to_array(self, itaper, normalization='4pi', csphase=1):
"""
Return the spherical harmonic coefficients of taper i as a numpy
array.
Usage
-----
coeffs = x.to_array(itaper, [normalization, csphase])
Returns
-------
coeffs : ndarray, shape (2, lwin+1, lwin+11)
3-D numpy ndarray of the spherical harmonic coefficients of the
window.
Parameters
----------
itaper : int
Taper number, where itaper=0 is the best concentrated.
normalization : str, optional, default = '4pi'
Normalization of the output coefficients: '4pi', 'ortho' or
'schmidt' for geodesy 4pi normalized, orthonormalized, or Schmidt
semi-normalized coefficients, respectively.
csphase : int, optional, default = 1
Condon-Shortley phase convention: 1 to exclude the phase factor,
or -1 to include it.
"""
if not isinstance(normalization, str):
raise ValueError('normalization must be a string. ' +
'Input type is {:s}.'
.format(str(type(normalization))))
if normalization.lower() not in ('4pi', 'ortho', 'schmidt'):
raise ValueError(
"normalization must be '4pi', 'ortho' " +
"or 'schmidt'. Provided value is {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be 1 or -1. Input value is {:s}."
.format(repr(csphase))
)
return self._to_array(
itaper, normalization=normalization.lower(), csphase=csphase)
def to_shcoeffs(self, itaper, normalization='4pi', csphase=1, name=None):
"""
Return the spherical harmonic coefficients of taper i as a SHCoeffs
class instance.
Usage
-----
clm = x.to_shcoeffs(itaper, [normalization, csphase, name])
Returns
-------
clm : SHCoeffs class instance
Parameters
----------
itaper : int
Taper number, where itaper=0 is the best concentrated.
normalization : str, optional, default = '4pi'
Normalization of the output class: '4pi', 'ortho' or 'schmidt' for
geodesy 4pi-normalized, orthonormalized, or Schmidt semi-normalized
coefficients, respectively.
csphase : int, optional, default = 1
Condon-Shortley phase convention: 1 to exclude the phase factor,
or -1 to include it.
name : str, optional, default = None
The name of the SHCoeffs class instance.
"""
if not isinstance(normalization, str):
raise ValueError('normalization must be a string. ' +
'Input type is {:s}.'
.format(str(type(normalization))))
if normalization.lower() not in set(['4pi', 'ortho', 'schmidt']):
raise ValueError(
"normalization must be '4pi', 'ortho' " +
"or 'schmidt'. Provided value is {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be 1 or -1. Input value is {:s}."
.format(repr(csphase))
)
coeffs = self.to_array(itaper, normalization=normalization.lower(),
csphase=csphase)
return SHCoeffs.from_array(coeffs, normalization=normalization.lower(),
csphase=csphase, copy=False, name=name)
def to_shgrid(self, itaper, grid='DH2', lmax=None, zeros=None,
extend=True, name=None):
"""
Evaluate the coefficients of taper i on a spherical grid and return
a SHGrid class instance.
Usage
-----
f = x.to_shgrid(itaper, [grid, lmax, zeros, extend, name])
Returns
-------
f : SHGrid class instance
Parameters
----------
itaper : int
Taper number, where itaper=0 is the best concentrated.
grid : str, optional, default = 'DH2'
'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2'
for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a
Gauss-Legendre quadrature grid.
lmax : int, optional, default = x.lwin
The maximum spherical harmonic degree, which determines the grid
spacing of the output grid.
zeros : ndarray, optional, default = None
The cos(colatitude) nodes used in the Gauss-Legendre Quadrature
grids.
extend : bool, optional, default = True
If True, compute the longitudinal band for 360 E (DH and GLQ grids)
and the latitudinal band for 90 S (DH grids only).
name : str, optional, default = None
The name of the SHGrid class instance.
Notes
-----
For more information concerning the spherical harmonic expansions and
the properties of the output grids, see the documentation for
SHExpandDH and SHExpandGLQ.
"""
if lmax is None:
lmax = self.lwin
if not isinstance(grid, str):
raise ValueError('grid must be a string. Input type is {:s}.'
.format(str(type(grid))))
if grid.upper() in ('DH', 'DH1'):
gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=1,
lmax=lmax, norm=1, csphase=1,
extend=extend)
return SHGrid.from_array(gridout, grid='DH', copy=False, name=name)
elif grid.upper() == 'DH2':
gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=2,
lmax=lmax, norm=1, csphase=1,
extend=extend)
return SHGrid.from_array(gridout, grid='DH', copy=False, name=name)
elif grid.upper() == 'GLQ':
if zeros is None:
zeros, weights = _shtools.SHGLQ(self.lmax)
gridout = _shtools.MakeGridGLQ(self.to_array(itaper), zeros,
lmax=lmax, norm=1, csphase=1,
extend=extend)
return SHGrid.from_array(gridout, grid='GLQ', copy=False,
name=name)
else:
raise ValueError(
"grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " +
"Input value is {:s}.".format(repr(grid)))
def multitaper_spectrum(self, clm, k, convention='power', unit='per_l',
lmax=None, weights=None, clat=None, clon=None,
coord_degrees=True):
"""
Return the multitaper spectrum estimate and standard error.
Usage
-----
mtse, sd = x.multitaper_spectrum(clm, k, [convention, unit, lmax,
clat, clon, weights
coord_degrees])
Returns
-------
mtse : ndarray, shape (lmax-lwin+1)
The localized multitaper spectrum estimate, where lmax is the
spherical-harmonic bandwidth of clm, and lwin is the
spherical-harmonic bandwidth of the localization windows.
sd : ndarray, shape (lmax-lwin+1)
The standard error of the localized multitaper spectrum
estimate.
Parameters
----------
clm : SHCoeffs class instance
SHCoeffs class instance containing the spherical harmonic
coefficients of the global field to analyze.
k : int
The number of tapers to be utilized in performing the multitaper
spectral analysis.
convention : str, optional, default = 'power'
The type of output spectra: 'power' for power spectra, and
'energy' for energy spectra.
unit : str, optional, default = 'per_l'
The units of the output spectra. If 'per_l', the spectra contain
the total contribution for each spherical harmonic degree l. If
'per_lm', the spectra contain the average contribution for each
coefficient at spherical harmonic degree l.
lmax : int, optional, default = clm.lmax
The maximum spherical-harmonic degree of clm to use.
weights : ndarray, optional, dimension (k), default = x.weights
1-D numpy array of the weights used in calculating the multitaper
spectral estimates and standard error.
clat, clon : float, optional, default = 90., 0.
When using spherical-cap localization windows, rotate the center of
the localization windows to the latitude and longitude coordinates
clat and clon, respectively.
coord_degrees : bool, optional, default = True
True if clat and clon are in degrees.
"""
if weights is not None:
if len(weights) != k:
raise ValueError('Length of weights must be equal to k. '
'len(weights) = {:d}, k = {:d}.'
.format(len(weights), k))
else:
weights = self.weights
return self._multitaper_spectrum(clm, k, convention=convention,
unit=unit, lmax=lmax, weights=weights,
clat=clat, clon=clon,
coord_degrees=coord_degrees)
def multitaper_cross_spectrum(self, clm, slm, k, convention='power',
unit='per_l', lmax=None, weights=None,
clat=None, clon=None, coord_degrees=True):
"""
Return the multitaper cross-spectrum estimate and standard error.
Usage
-----
mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit,
lmax, weights,
clat, clon,
coord_degrees])
Returns
-------
mtse : ndarray, shape (lmax-lwin+1)
The localized multitaper cross-spectrum estimate, where lmax is the
smaller of the two spherical-harmonic bandwidths of clm and slm,
and lwin is the spherical-harmonic bandwidth of the localization
windows.
sd : ndarray, shape (lmax-lwin+1)
The standard error of the localized multitaper cross-spectrum
estimate.
Parameters
----------
clm : SHCoeffs class instance
SHCoeffs class instance containing the spherical harmonic
coefficients of the first global field to analyze.
slm : SHCoeffs class instance
SHCoeffs class instance containing the spherical harmonic
coefficients of the second global field to analyze.
k : int
The number of tapers to be utilized in performing the multitaper
spectral analysis.
convention : str, optional, default = 'power'
The type of output spectra: 'power' for power spectra, and
'energy' for energy spectra.
unit : str, optional, default = 'per_l'
The units of the output spectra. If 'per_l', the spectra contain
the total contribution for each spherical harmonic degree l. If
'per_lm', the spectra contain the average contribution for each
coefficient at spherical harmonic degree l.
lmax : int, optional, default = min(clm.lmax, slm.lmax)
The maximum spherical-harmonic degree of the input coefficients
to use.
weights : ndarray, optional, dimension (k), default = x.weights
The weights used in calculating the multitaper cross-spectral
estimates and standard error.
clat, clon : float, optional, default = 90., 0.
When using spherical-cap localization windows, rotate the center of
the localization windows to the latitude and longitude coordinates
clat and clon, respectively.
coord_degrees : bool, optional, default = True
True if clat and clon are in degrees.
"""
if weights is not None:
if len(weights) != k:
raise ValueError('Length of weights must be equal to k. '
'len(weights) = {:d}, k = {:d}.'
.format(len(weights), k))
else:
weights = self.weights
return self._multitaper_cross_spectrum(clm, slm, k,
convention=convention,
unit=unit, lmax=lmax,
weights=weights,
clat=clat, clon=clon,
coord_degrees=coord_degrees)
def biased_spectrum(self, power, k, convention='power', unit='per_l',
weights=None, save_cg=None, ldata=None):
"""
Calculate the multitaper (cross-)spectrum expectation of a
localized function.
Usage
-----
outspectrum = x.biased_spectrum(spectrum, k, [convention, unit,
weights, save_cg, ldata])
Returns
-------
outspectrum : ndarray, shape (ldata+lwin+1)
The expectation of the windowed spectrum, where ldata is the
spherical-harmonic bandwidth of the input spectrum, and lwin is the
spherical-harmonic bandwidth of the localization windows.
Parameters
----------
spectrum : ndarray, shape (ldata+1)
The global spectrum.
k : int
The number of best-concentrated localization windows to use in
constructing the windowed spectrum.
convention : str, optional, default = 'power'
The type of input global and output biased spectra: 'power' for
power spectra, and 'energy' for energy spectra.
unit : str, optional, default = 'per_l'
The units of the input global and output biased spectra. If
'per_l', the spectra contain the total contribution for each
spherical harmonic degree l. If 'per_lm', the spectra contain the
average contribution for each coefficient at spherical harmonic
degree l.
weights : ndarray, optional, dimension (k), default = x.weights
The weights used in calculating the multitaper spectral estimates
and standard error.
save_cg : int, optional, default = 0
If 1, the Clebsch-Gordon coefficients will be precomputed and saved
for future use. If 0, the Clebsch-Gordon coefficients will be
recomputed for each call.
ldata : int, optional, default = len(power)-1
The maximum degree of the global unwindowed spectrum.
"""
if weights is not None:
if len(weights) != k:
raise ValueError('Length of weights must be equal to k. '
'len(weights) = {:d}, k = {:d}.'
.format(len(weights), k))
else:
weights = self.weights
return self._biased_spectrum(power, k, convention=convention,
unit=unit, weights=weights,
save_cg=save_cg, ldata=ldata)
def spectra(self, itaper=None, nwin=None, convention='power', unit='per_l',
base=10.):
"""
Return the spectra of one or more localization windows.
Usage
-----
spectra = x.spectra([itaper, nwin, convention, unit, base])
Returns
-------
spectra : ndarray, shape (lwin+1, nwin)
A matrix with each column containing the spectrum of a
localization window, and where the windows are arranged with
increasing concentration factors. If itaper is set, only a single
vector is returned, whereas if nwin is set, the first nwin spectra
are returned.
Parameters
----------
itaper : int, optional, default = None
The taper number of the output spectrum, where itaper=0
corresponds to the best concentrated taper.
nwin : int, optional, default = 1
The number of best concentrated localization window power spectra
to return.
convention : str, optional, default = 'power'
The type of spectrum to return: 'power' for power spectrum,
'energy' for energy spectrum, and 'l2norm' for the l2 norm
spectrum.
unit : str, optional, default = 'per_l'
If 'per_l', return the total contribution to the spectrum for each
spherical harmonic degree l. If 'per_lm', return the average
contribution to the spectrum for each coefficient at spherical
harmonic degree l. If 'per_dlogl', return the spectrum per log
interval dlog_a(l).
base : float, optional, default = 10.
The logarithm base when calculating the 'per_dlogl' spectrum.
Notes
-----
This function returns either the power spectrum, energy spectrum, or
l2-norm spectrum of one or more of the localization windows.
Total power is defined as the integral of the function squared over all
space, divided by the area the function spans. If the mean of the
function is zero, this is equivalent to the variance of the function.
The total energy is the integral of the function squared over all space
and is 4pi times the total power. The l2-norm is the sum of the
magnitude of the coefficients squared.
The output spectrum can be expresed using one of three units. 'per_l'
returns the contribution to the total spectrum from all angular orders
at degree l. 'per_lm' returns the average contribution to the total
spectrum from a single coefficient at degree l. The 'per_lm' spectrum
is equal to the 'per_l' spectrum divided by (2l+1). 'per_dlogl' returns
the contribution to the total spectrum from all angular orders over an
infinitessimal logarithmic degree band. The contrubution in the band
dlog_a(l) is spectrum(l, 'per_dlogl')*dlog_a(l), where a is the base,
and where spectrum(l, 'per_dlogl) is equal to
spectrum(l, 'per_l')*l*log(a).
"""
if itaper is None:
if nwin is None:
nwin = self.nwin
spectra = _np.zeros((self.lwin+1, nwin))
for iwin in range(nwin):
coeffs = self.to_array(iwin)
spectra[:, iwin] = _spectrum(coeffs, normalization='4pi',
convention=convention, unit=unit,
base=base)
else:
coeffs = self.to_array(itaper)
spectra = _spectrum(coeffs, normalization='4pi',
convention=convention, unit=unit, base=base)
return spectra
def coupling_matrix(self, lmax, k=None, weights=None, mode='full'):
"""
Return the coupling matrix of the first nwin tapers. This matrix
relates the global power spectrum to the expectation of the localized
multitaper spectrum.
Usage
-----
Mmt = x.coupling_matrix(lmax, [k, weights, mode])
Returns
-------
Mmt : ndarray, shape (lmax+lwin+1, lmax+1) or (lmax+1, lmax+1) or
(lmax-lwin+1, lmax+1)
Parameters
----------
lmax : int
Spherical harmonic bandwidth of the global power spectrum.
k : int, optional, default = x.nwin
Number of tapers used in the mutlitaper spectral analysis.
weights : ndarray, optional, dimension (k), default = x.weights
Taper weights used with the multitaper spectral analyses.
mode : str, opitonal, default = 'full'
'full' returns a biased output spectrum of size lmax+lwin+1. The
input spectrum is assumed to be zero for degrees l>lmax.
'same' returns a biased output spectrum with the same size
(lmax+1) as the input spectrum. The input spectrum is assumed to be
zero for degrees l>lmax.
'valid' returns a biased spectrum with size lmax-lwin+1. This
returns only that part of the biased spectrum that is not
influenced by the input spectrum beyond degree lmax.
"""
if weights is not None:
if k is not None:
if len(weights) != k:
raise ValueError(
'Length of weights must be equal to k. '
'len(weights) = {:d}, k = {:d}.'
.format(len(weights), k))
else:
if len(weights) != self.nwin:
raise ValueError(
'Length of weights must be equal to nwin when k is '
'not specified. len(weights) = {:d}, nwin = {:d}.'
.format(len(weights), self.nwin))
else:
weights = self.weights
if mode == 'full':
return self._coupling_matrix(lmax, k=k, weights=weights)
elif mode == 'same':
cmatrix = self._coupling_matrix(lmax, k=k, weights=weights)
return cmatrix[:lmax+1, :]
elif mode == 'valid':
cmatrix = self._coupling_matrix(lmax, k=k, weights=weights)
return cmatrix[:lmax - self.lwin+1, :]
else:
raise ValueError("mode has to be 'full', 'same' or 'valid', not "
"{}.".format(mode))
def variance(self, power, k, lmax=None, weights=None):
"""
Compute the theoretical variance of a windowed function for a given
input power spectrum (using spherical-cap localization windows only).
Usage
-----
variance = x.variance(power, k, [lmax, weights])
Returns
-------
variance : ndarray, shape (min(lmax+1, lmax_in+1-lwin))
The theoretical variance of the windowed function.
Parameters
----------
power : ndarray, dimension (lmax_in+1)
The input global power spectrum.
k : int
The number of tapers to be utilized in performing the multitaper
spectral analysis.
lmax : int, optional, default = lmax_in
The maximum spherical harmonic degree of the variance to compute.
weights : ndarray, optional, dimension (k), default = x.weights
Taper weights used with the multitaper spectral analyses.
"""
if weights is not None:
if len(weights) != k:
raise ValueError(
'Length of weights must be equal to k. '
'len(weights) = {:d}, k = {:d}.'
.format(len(weights), k))
else:
weights = self.weights
if lmax is None:
lmax = len(power) - 1 - self.lwin
else:
if lmax > len(power) - 1 - self.lwin:
raise ValueError('lmax must be less than or equal to '
'len(power) - 1 - lwin.')
return self._variance(power, k, lmax=lmax, weights=weights)
def plot_windows(self, nwin, projection=None, lmax=None, maxcolumns=3,
tick_interval=[60, 45], minor_tick_interval=[None, None],
ticks='WSen', xlabel='Longitude', ylabel='Latitude',
title=True, title_offset=None, colorbar=None,
cmap='viridis', cmap_limits=None, cmap_rlimits=None,
cmap_reverse=False, cmap_scale='lin', cb_offset=None,
cb_triangles='neither', cb_label=None, cb_ylabel=None,
cb_tick_interval=None, cb_minor_tick_interval=None,
grid=False, loss=False, axes_labelsize=None,
tick_labelsize=None, titlesize=9, show=True, ax=None,
cb_width=None, fname=None):
"""
Plot the best-concentrated localization windows.
Usage
-----
x.plot_windows(nwin, [projection, lmax, maxcolumns, tick_interval,
minor_tick_interval, ticks, xlabel, ylabel,
title, title_offset, colorbar, cmap, cmap_limits,
cmap_rlimits, cmap_reverse, cmap_scale,
cb_triangles, cb_label, cb_ylabel,
cb_tick_interval, cb_minor_tick_interval,
cb_offset, cb_width, grid, loss, titlesize,
axes_labelsize, tick_labelsize, ax, show, fname])
Parameters
----------
nwin : int
The number of localization windows to plot.
projection : Cartopy projection class, optional, default = None
The Cartopy projection class used to project the gridded data,
for Driscoll and Healy sampled grids only.
lmax : int, optional, default = self.lwin
The maximum degree to use when plotting the windows, which controls
the number of samples in latitude and longitude.
maxcolumns : int, optional, default = 3
The maximum number of columns to use when plotting multiple
localization windows.
tick_interval : list or tuple, optional, default = [60, 45]
Intervals to use when plotting the x and y ticks. If set to None,
ticks will not be plotted.
minor_tick_interval : list or tuple, optional, default = [None, None]
Intervals to use when plotting the minor x and y ticks. If set to
None, minor ticks will not be plotted.
ticks : str, optional, default = 'WSen'
Specify which axes should have ticks drawn and annotated. Capital
letters will plot the ticks and annotations, whereas small letters
will plot only the ticks. 'W', 'S', 'E', and 'N' denote the west,
south, east and north boundaries of the plot.
xlabel : str, optional, default = 'longitude'
Label for the longitude axis.
ylabel : str, optional, default = 'latitude'
Label for the latitude axis.
title : bool, optional, default = True
If True, plot a title on top of each subplot providing the taper
number and 1 minus the concentration factor.
title_offset : float, optional, default = None
The offset between the title and top of the plot in points.
colorbar : str, optional, default = None
Plot a colorbar along the 'top', 'right', 'bottom', or 'left' axis.
cmap : str, optional, default = 'viridis'
The color map to use when plotting the data.
cmap_limits : list, optional, default = [self.min(), self.max()]
Set the lower and upper limits of the data used by the colormap,
and optionally an interval for each color band. If the
interval is specified, the number of discrete colors will be
(cmap_limits[1]-cmap_limits[0])/cmap_limits[2].
cmap_rlimits : list, optional, default = None
Same as cmap_limits, except the provided upper and lower values are
relative with respect to the maximum value of the data.
cmap_reverse : bool, optional, default = False
Set to True to reverse the sense of the color progression in the
color table.
cmap_scale : str, optional, default = 'lin'
Scale of the color axis: 'lin' for linear or 'log' for logarithmic.
cb_triangles : str, optional, default = 'neither'
Add triangles to the edges of the colorbar for minimum and maximum
values. Can be 'neither', 'both', 'min', or 'max'.
cb_label : str, optional, default = None
Text label for the colorbar.
cb_ylabel : str, optional, default = None
Text label for the y axis of the colorbar
cb_tick_interval : float, optional, default = None
Colorbar major tick and annotation interval.
cb_minor_tick_interval : float, optional, default = None
Colorbar minor tick interval.
cb_offset : float or int, optional, default = None
Offset of the colorbar from the map edge in points. If None,
the offset will be calculated automatically.
cb_width : float, optional, default = None
Width of the colorbar in percent with respect to the width of the
respective image axis. Defaults are 2.5 and 5 for vertical and
horizontal colorbars, respectively.
grid : bool, optional, default = False
If True, plot grid lines.
loss : bool, optional, default = False
When plotting titles, provide the loss factor instead of the
concentration factor (loss=1-concentration).
titlesize : int, optional, default = 9
The font size for the subplot titles.
axes_labelsize : int, optional, default = None
The font size for the x and y axes labels.
tick_labelsize : int, optional, default = None
The font size for the x and y tick labels.
ax : matplotlib axes object, optional, default = None
An array of matplotlib axes objects where the plots will appear.
show : bool, optional, default = True
If True, plot the image to the screen.
fname : str, optional, default = None
If present, save the image to the specified file.
"""
if self.kind == 'cap':
if self.nwinrot is not None and self.nwinrot <= nwin:
nwin = self.nwinrot
ncolumns = min(maxcolumns, nwin)
nrows = _np.ceil(nwin / ncolumns).astype(int)
figsize = (_mpl.rcParams['figure.figsize'][0],
_mpl.rcParams['figure.figsize'][0]
* 0.6 * nrows / ncolumns + 0.41)
if ax is None:
fig, axes = _plt.subplots(nrows, ncolumns, figsize=figsize,
sharex='all', sharey='all')
else:
if hasattr(ax, 'flatten') and ax.size < nwin:
raise ValueError('ax.size must be greater or equal to nwin. ' +
'nwin = {:s}'.format(repr(nwin)) +
' and ax.size = {:s}.'.format(repr(ax.size)))
axes = ax
for itaper in range(min(self.nwin, nwin)):
evalue = self.eigenvalues[itaper]
if min(self.nwin, nwin) == 1 and ax is None:
axtemp = axes
elif hasattr(axes, 'flatten'):
axtemp = axes.flatten()[itaper]
else:
axtemp = axes[itaper]
coeffs = self.to_shcoeffs(itaper)
if lmax is not None:
coeffs = coeffs.pad(lmax=lmax, copy=False)
grid_temp = coeffs.expand()
if title:
if loss:
title_str = '#{:d} [loss={:2.2g}]'.format(itaper, 1-evalue)
else:
title_str = '#{:d} [concentration={:2.2g}]'.format(
itaper, evalue)
else:
title_str = None
grid_temp.plot(projection=projection, tick_interval=tick_interval,
minor_tick_interval=minor_tick_interval,
title=title_str, title_offset=title_offset,
ticks=ticks, xlabel=xlabel, ylabel=ylabel,
grid=grid, cmap=cmap, cmap_reverse=cmap_reverse,
cmap_rlimits=cmap_rlimits, cmap_scale=cmap_scale,
axes_labelsize=axes_labelsize,
tick_labelsize=tick_labelsize,
colorbar=colorbar, cmap_limits=cmap_limits,
cb_triangles=cb_triangles, cb_label=cb_label,
cb_ylabel=cb_ylabel, cb_offset=cb_offset,
cb_tick_interval=cb_tick_interval,
cb_width=cb_width,
cb_minor_tick_interval=cb_minor_tick_interval,
titlesize=titlesize, ax=axtemp)
if ax is None and projection is None:
if nrows > 1:
for axtemp in axes[:-1, :].flatten():
for xlabel_i in axtemp.get_xticklabels():