-
Notifications
You must be signed in to change notification settings - Fork 103
/
shcoeffs.py
4483 lines (4050 loc) · 197 KB
/
shcoeffs.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 Coefficients classes
"""
import os as _os
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 gzip as _gzip
import shutil as _shutil
import warnings as _warnings
from scipy.special import factorial as _factorial
import xarray as _xr
from ..spectralanalysis import spectrum as _spectrum
from ..spectralanalysis import cross_spectrum as _cross_spectrum
from ..shio import convert as _convert
from ..shio import shread as _shread
from ..shio import shwrite as _shwrite
from ..shio import read_dov as _read_dov
from ..shio import write_dov as _write_dov
from ..shio import read_bshc as _read_bshc
from ..shio import write_bshc as _write_bshc
from ..backends import backend_module
from ..backends import preferred_backend
from ..backends import shtools as _shtools
class SHCoeffs(object):
"""
Spherical Harmonic Coefficients class.
The coefficients of this class can be initialized using one of the four
constructor methods:
x = SHCoeffs.from_array(array)
x = SHCoeffs.from_random(powerspectrum)
x = SHCoeffs.from_zeros(lmax)
x = SHCoeffs.from_file('fname.dat')
x = SHCoeffs.from_netcdf('ncname.nc')
x = SHCoeffs.from_cap(theta, lmax)
The normalization convention of the input coefficents is specified
by the normalization and csphase parameters, which take the following
values:
normalization : '4pi' (default), geodesy 4-pi normalized.
: 'ortho', orthonormalized.
: 'schmidt', Schmidt semi-normalized.
: 'unnorm', unnormalized.
csphase : 1 (default), exlcude the Condon-Shortley phase factor.
: -1, include the Condon-Shortley phase factor.
See the documentation for each constructor method for further options.
Once initialized, each class instance defines the following class
attributes:
lmax : The maximum spherical harmonic degree of the coefficients.
coeffs : The raw coefficients with the specified normalization and
csphase conventions. This is a three-dimensional array
formatted as coeffs[i, degree, order], where i=0
corresponds to positive orders and i=1 to negative orders.
errors : The uncertainties of the spherical harmonic coefficients.
error_kind : An arbitrary string describing the kind of errors, such as
'unknown', 'unspecified', 'calibrated', 'formal' or None.
normalization : The normalization of the coefficients: '4pi', 'ortho',
'schmidt', or 'unnorm'.
csphase : Defines whether the Condon-Shortley phase is used (1)
or not (-1).
mask : A boolean mask that is True for the permissible values of
degree l and order m.
kind : The coefficient data type: either 'complex' or 'real'.
name : The name of the dataset.
units : The units of the spherical harmonic coefficients.
header : A list of values (of type str) from the header line of the
input file used to initialize the class (for 'shtools'
and 'dov' formatted files).
header2 : A list of values (of type str) from the second header line
of the input file used to initialize the class (for
'shtools' and 'dov' formatted files only).
Each class instance provides the following methods:
degrees() : Return an array listing the spherical harmonic
degrees from 0 to lmax.
spectrum() : Return the spectrum of the function as a function
of spherical harmonic degree.
cross_spectrum() : Return the cross-spectrum of two functions as a
function of spherical harmonic degree.
admittance() : Return the admittance with another function.
correlation() : Return the spectral correlation with another
function.
admitcorr() : Return the admittance and spectral correlation with
another function.
volume() : Calculate the volume of the body.
centroid() : Compute the centroid of the body.
set_coeffs() : Set coefficients in-place to specified values.
rotate() : Rotate the coordinate system used to express the
spherical harmonic coefficients and return a new
class instance.
convert() : Return a new class instance using a different
normalization convention.
pad() : Return a new class instance that is zero padded or
truncated to a different lmax.
expand() : Evaluate the coefficients either on a spherical
grid and return an SHGrid class instance, or for
a list of latitude and longitude coordinates.
gradient() : Compute the horizontal gradient of the function and
return an SHGradient class instance.
plot_spectrum() : Plot the spectrum as a function of spherical
harmonic degree.
plot_cross_spectrum() : Plot the cross-spectrum of two functions.
plot_admittance() : Plot the admittance with another function.
plot_correlation() : Plot the spectral correlation with another
function.
plot_admitcorr() : Plot the admittance and spectral correlation with
another function.
plot_spectrum2d() : Plot the 2D spectrum of all spherical harmonic
degrees and orders.
plot_cross_spectrum2d() : Plot the 2D cross-spectrum of all spherical
harmonic degrees and orders.
to_array() : Return an array of spherical harmonic coefficients
with a different normalization convention.
to_file() : Save raw spherical harmonic coefficients as a file.
to_netcdf() : Save raw spherical harmonic coefficients as a
netcdf file.
copy() : Return a copy of the class instance.
info() : Print a summary of the data stored in the SHCoeffs
instance.
"""
def __init__(self):
"""Unused constructor of the super class."""
print('Initialize the class using one of the class methods:\n'
'>>> pyshtools.SHCoeffs.from_array\n'
'>>> pyshtools.SHCoeffs.from_random\n'
'>>> pyshtools.SHCoeffs.from_zeros\n'
'>>> pyshtools.SHCoeffs.from_file\n'
'>>> pyshtools.SHCoeffs.from_netcdf\n'
'>>> pyshtools.SHCoeffs.from_cap\n'
)
# ---- Factory methods ----
@classmethod
def from_array(self, coeffs, errors=None, error_kind=None,
normalization='4pi', csphase=1, lmax=None, name=None,
units=None, copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHCoeffs.from_array(array, [errors, error_kind, normalization,
csphase, lmax, name, units, copy])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmaxin+1, lmaxin+1).
The input spherical harmonic coefficients. This is a three-
dimensional array formatted as coeffs[i, degree, order], where i=0
corresponds to positive orders and i=1 to negative orders.
errors : ndarray, optional, default = None
The uncertainties of the spherical harmonic coefficients.
error_kind : str, optional, default = None
An arbitrary string describing the kind of errors, such as None,
'unspecified', 'calibrated' or 'formal'.
normalization : str, optional, default = '4pi'
'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 : int, optional, default = None
The maximum spherical harmonic degree to include in the returned
class instance. This must be less than or equal to lmaxin.
name : str, optional, default = None
The name of the dataset.
units : str, optional, default = None
The units of the spherical harmonic coefficients.
copy : bool, optional, default = True
If True, make a copy of array when initializing the class instance.
If False, initialize the class instance with a reference to array.
"""
if _np.iscomplexobj(coeffs):
kind = 'complex'
else:
kind = 'real'
if type(normalization) is not str:
raise ValueError('normalization must be a string. ' +
'Input type is {:s}.'
.format(str(type(normalization))))
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. Input value is {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value is {:s}."
.format(repr(csphase))
)
if errors is not None:
if coeffs.shape != errors.shape:
raise ValueError(
"The shape of coeffs and errors must be the same."
"Shape of coeffs = {:s}, shape of errors = {:s}."
.format(repr(coeffs.shape), repr(coeffs.errors))
)
if error_kind is None:
error_kind = 'unspecified'
lmaxin = coeffs.shape[1] - 1
if lmax is None:
lmax = lmaxin
else:
if lmax > lmaxin:
lmax = lmaxin
if normalization.lower() == 'unnorm' and lmax > 85:
_warnings.warn("Calculations using unnormalized coefficients " +
"are stable only for degrees less than or equal " +
"to 85. lmax for the coefficients will be set to " +
"85. Input value is {:d}.".format(lmax),
category=RuntimeWarning)
lmax = 85
for cls in self.__subclasses__():
if cls.istype(kind):
if errors is not None:
return cls(coeffs[:, 0:lmax+1, 0:lmax+1],
errors=errors[:, 0:lmax+1, 0:lmax+1],
error_kind=error_kind,
normalization=normalization.lower(),
csphase=csphase, name=name, units=units,
copy=copy)
else:
return cls(coeffs[:, 0:lmax+1, 0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, name=name, units=units,
copy=copy)
@classmethod
def from_zeros(self, lmax, errors=None, error_kind=None, kind='real',
normalization='4pi', csphase=1, name=None, units=None):
"""
Initialize class with spherical harmonic coefficients set to zero from
degree 0 to lmax.
Usage
-----
x = SHCoeffs.from_zeros(lmax, [errors, error_kind, normalization,
csphase, kind, name, units])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
lmax : int
The highest spherical harmonic degree l of the coefficients.
errors : bool, optional, default = None
If True, initialize the attribute errors with zeros.
error_kind : str, optional, default = None
An arbitrary string describing the kind of errors, such as None,
'unspecified', 'calibrated' or 'formal'.
normalization : str, optional, default = '4pi'
'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.
kind : str, optional, default = 'real'
'real' or 'complex' spherical harmonic coefficients.
name : str, optional, default = None
The name of the dataset.
units : str, optional, default = None
The units of the spherical harmonic coefficients.
"""
error_coeffs = None
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"Kind must be 'real' or 'complex'. Input value is {:s}."
.format(repr(kind))
)
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. Input value is {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value is {:s}."
.format(repr(csphase))
)
if normalization.lower() == 'unnorm' and lmax > 85:
_warnings.warn("Calculations using unnormalized coefficients " +
"are stable only for degrees less than or equal " +
"to 85. lmax for the coefficients will be set to " +
"85. Input value is {:d}.".format(lmax),
category=RuntimeWarning)
lmax = 85
if kind.lower() == 'real':
coeffs = _np.zeros((2, lmax + 1, lmax + 1))
if errors:
error_coeffs = _np.zeros((2, lmax + 1, lmax + 1))
else:
coeffs = _np.zeros((2, lmax + 1, lmax + 1), dtype=_np.complex128)
if errors:
error_coeffs = _np.zeros((2, lmax + 1, lmax + 1),
dtype=_np.complex128)
if errors is True and error_kind is None:
error_kind = 'unspecified'
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, errors=error_coeffs, error_kind=error_kind,
normalization=normalization.lower(),
csphase=csphase, name=name, units=units)
@classmethod
def from_file(self, fname, lmax=None, format='shtools', kind='real',
errors=None, error_kind=None, normalization='4pi', skip=0,
header=False, header2=False, csphase=1, name=None,
units=None, encoding=None, **kwargs):
"""
Initialize the class with spherical harmonic coefficients from a file.
Usage
-----
x = SHCoeffs.from_file(filename, [format='shtools' or 'dov', lmax,
errors, error_kind, normalization, csphase,
skip, header, header2, name, units, encoding])
x = SHCoeffs.from_file(filename, format='bshc', [lmax, normalization,
csphase, name, units])
x = SHCoeffs.from_file(filename, format='npy', [lmax, normalization,
csphase, name, units, **kwargs])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
filename : str
File name or URL containing the spherical harmonic coefficients.
filename will be treated as a URL if it starts with 'http://',
'https://', or 'ftp://'. For 'shtools' and 'bshc' formatted files,
if filename ends with '.gz' or '.zip', the file will be
uncompressed before parsing.
format : str, optional, default = 'shtools'
'shtools' for generic text files, 'dov' for [degree, order, value]
text files, 'bshc' for binary spherical harmonic coefficient
files, or 'npy' for binary numpy files.
lmax : int, optional, default = None
The maximum spherical harmonic degree to read from the file. The
default is to read the entire file.
errors : bool, optional, default = None
If True, read errors from the file (for 'shtools' and 'dov'
formatted files only).
error_kind : str, optional, default = None
For 'shtools' and 'dov' formatted files: An arbitrary string
describing the kind of errors, such as None, 'unspecified',
'calibrated' or 'formal'.
normalization : str, optional, default = '4pi'
'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.
skip : int, optional, default = 0
Number of lines to skip at the beginning of the file for 'shtools'
formatted files.
header : bool, optional, default = False
If True, read a list of values from the header line of an 'shtools'
or 'dov' formatted file.
header2 : bool, optional, default = False
If True, read a list of values from a second header line of an
'shtools' or 'dov' formatted file.
name : str, optional, default = None
The name of the dataset.
units : str, optional, default = None
The units of the spherical harmonic coefficients.
encoding : str, optional, default = None
Encoding of the input file when format is 'shtools' or 'dov'. The
default is to use the system default.
**kwargs : keyword argument list, optional for format = 'npy'
Keyword arguments of numpy.load() when format is 'npy'.
Notes
-----
Supported file formats:
'shtools' (see pyshtools.shio.shread)
'dov' (see pyshtools.shio.read_dov)
'bshc' (see pyshtools.shio.read_bshc)
'npy' (see numpy.load)
For 'shtools', 'dov' or 'bshc' formatted files, if filename starts with
'http://', 'https://', or 'ftp://', the file will be treated as a URL.
In this case, the file will be downloaded in its entirety before it is
parsed. If the filename ends with '.gz' or '.zip', the file will be
automatically uncompressed before parsing. For zip files, archives with
only a single file are supported. Note that reading '.gz' and '.zip'
files will be extremely slow if lmax is not specified.
For 'shtools' and 'dov' formatted files, the optional parameter `skip`
specifies how many lines should be skipped before attempting to parse
the file, the optional parameter `header` specifies whether to read a
list of values from a header line, and the optional parameter `lmax`
specifies the maximum degree to read from the file.
"""
error_coeffs = None
header_list = None
header2_list = None
if type(normalization) is not str:
raise ValueError('normalization must be a string. '
'Input type is {:s}.'
.format(str(type(normalization))))
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The input normalization must be '4pi', 'ortho', 'schmidt', "
"or 'unnorm'. 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))
)
if format.lower() == 'shtools' or format.lower() == 'dov':
if format.lower() == 'shtools':
read_func = _shread
else:
read_func = _read_dov
if header is True:
if errors:
if header2:
coeffs, error_coeffs, lmaxout, header_list, \
header2_list = read_func(fname, lmax=lmax,
skip=skip, header=True,
header2=True, error=True,
encoding=encoding)
else:
coeffs, error_coeffs, lmaxout, header_list = read_func(
fname, lmax=lmax, skip=skip, header=True,
error=True, encoding=encoding)
else:
if header2:
coeffs, lmaxout, header_list, header2_list = read_func(
fname, lmax=lmax, skip=skip, header=True,
header2=True, encoding=encoding)
else:
coeffs, lmaxout, header_list = read_func(
fname, lmax=lmax, skip=skip, header=True,
encoding=encoding)
else:
if errors:
coeffs, error_coeffs, lmaxout = read_func(
fname, lmax=lmax, skip=skip, error=True,
encoding=encoding)
else:
coeffs, lmaxout = read_func(fname, lmax=lmax, skip=skip,
encoding=encoding)
if errors is True and error_kind is None:
error_kind = 'unspecified'
elif format.lower() == 'bshc':
coeffs, lmaxout = _read_bshc(fname, lmax=lmax)
elif format.lower() == 'npy':
coeffs = _np.load(fname, **kwargs)
lmaxout = coeffs.shape[1] - 1
if lmax is not None:
if lmax < lmaxout:
coeffs = coeffs[:, :lmax+1, :lmax+1]
lmaxout = lmax
else:
raise NotImplementedError(
'format={:s} not implemented.'.format(repr(format)))
if normalization.lower() == 'unnorm' and lmaxout > 85:
_warnings.warn("Calculations using unnormalized coefficients "
"are stable only for degrees less than or equal "
"to 85. lmax for the coefficients will be set to "
"85. Input value is {:d}.".format(lmaxout),
category=RuntimeWarning)
lmaxout = 85
coeffs = coeffs[:, :lmaxout+1, :lmaxout+1]
if _np.iscomplexobj(coeffs):
kind = 'complex'
else:
kind = 'real'
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, errors=error_coeffs, error_kind=error_kind,
normalization=normalization.lower(),
csphase=csphase, header=header_list,
header2=header2_list, name=name, units=units)
@classmethod
def from_random(self, power, lmax=None, kind='real', normalization='4pi',
csphase=1, name=None, units=None, exact_power=False,
power_unit='per_l', seed=None):
"""
Initialize the class with spherical harmonic coefficients as random
variables with a given spectrum.
Usage
-----
x = SHCoeffs.from_random(power, [lmax, kind, normalization, csphase,
name, units, exact_power, power_unit,
seed])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
power : ndarray, shape (L+1)
numpy array of shape (L+1) that specifies the expected power
spectrum of the random coefficients, where L is the maximum
spherical harmonic bandwidth. By default, the power spectrum
represents the power of all angular orders as a function of
spherical harmonic degree (see power_unit).
lmax : int, optional, default = len(power) - 1
The maximum spherical harmonic degree l of the output coefficients.
The coefficients will be set to zero for degrees greater than L.
kind : str, optional, default = 'real'
'real' or 'complex' spherical harmonic coefficients.
normalization : str, optional, default = '4pi'
'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.
name : str, optional, default = None
The name of the dataset.
units : str, optional, default = None
The units of the spherical harmonic coefficients.
exact_power : bool, optional, default = False
If True, the spherical harmonic coefficients of the random
realization will be rescaled such that the power spectrum is
exactly equal to the input spectrum.
power_unit : str, optional, default = 'per_l'
If 'per_l', the input power spectrum represents the total power of
all angular orders as a function of spherical harmonic degree. If
'per_lm', the input power spectrum represents the power per
coefficient (which is assumed isotropic and varies only as a
function of spherical harmonic degree).
seed : int, optional, default = None
Set the seed for the numpy random number generator.
Notes
-----
This routine returns a random realization of spherical harmonic
coefficients obtained from a normal distribution. The variance of each
coefficient is determined by the input power spectrum and the type of
spectrum (as specified by power_unit). If power_unit is 'per_l'
(default), the variance of each coefficient at spherical harmonic
degree l is equal to the total power at degree l divided by the number
of coefficients at that degree. If power_unit is 'per_lm', the variance
of each coefficient at degree l is equal to the input power at that
degree. The power spectrum of the random realization can be fixed
exactly to the input spectrum by setting exact_power to True.
"""
# check if all arguments are correct
if type(normalization) is not str:
raise ValueError('normalization must be a string. ' +
'Input type is {:s}.'
.format(str(type(normalization))))
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The input normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. 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))
)
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"kind must be 'real' or 'complex'. " +
"Input value is {:s}.".format(repr(kind)))
if power_unit.lower() not in ('per_l', 'per_lm'):
raise ValueError("power_unit must be 'per_l' or 'per_lm'. " +
"Input value was {:s}".format(repr(power_unit)))
if lmax is None:
nl = len(power)
lmax = nl - 1
else:
if lmax <= len(power) - 1:
nl = lmax + 1
else:
nl = len(power)
degrees = _np.arange(nl)
if normalization.lower() == 'unnorm' and nl - 1 > 85:
_warnings.warn("Calculations using unnormalized coefficients " +
"are stable only for degrees less than or equal " +
"to 85. lmax for the coefficients will be set to " +
"85. Input value is {:d}.".format(nl-1),
category=RuntimeWarning)
nl = 85 + 1
lmax = 85
# Create coefficients with unit variance, which returns an expected
# total power per degree of (2l+1) for 4pi normalized harmonics.
if seed is not None:
_np.random.seed(seed=seed)
if kind.lower() == 'real':
coeffs = _np.zeros((2, nl, nl))
for l in degrees:
coeffs[:2, l, :l+1] = _np.random.normal(size=(2, l+1))
elif kind.lower() == 'complex':
# - need to divide by sqrt 2 as there are two terms for each coeff.
coeffs = _np.zeros((2, nl, nl), dtype=_np.complex128)
for l in degrees:
coeffs[:2, l, :l+1] = (_np.random.normal(size=(2, l+1)) +
1j * _np.random.normal(size=(2, l+1))
) / _np.sqrt(2.)
if exact_power:
power_realization = _spectrum(coeffs, normalization='4pi',
unit=power_unit)
coeffs *= _np.sqrt(
power[0:nl] / power_realization)[_np.newaxis, :, _np.newaxis]
else:
if power_unit == 'per_l':
coeffs *= \
_np.sqrt(power[0:nl] / (2 * degrees + 1))[_np.newaxis, :,
_np.newaxis]
elif power_unit == 'per_lm':
coeffs *= _np.sqrt(power[0:nl])[_np.newaxis, :, _np.newaxis]
if normalization.lower() == '4pi':
pass
elif normalization.lower() == 'ortho':
coeffs = _convert(coeffs, normalization_in='4pi',
normalization_out='ortho')
elif normalization.lower() == 'schmidt':
coeffs = _convert(coeffs, normalization_in='4pi',
normalization_out='schmidt')
elif normalization.lower() == 'unnorm':
coeffs = _convert(coeffs, normalization_in='4pi',
normalization_out='unnorm')
if lmax > nl - 1:
coeffs = _np.pad(coeffs, ((0, 0), (0, lmax - nl + 1),
(0, lmax - nl + 1)), 'constant')
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, errors=None,
normalization=normalization.lower(),
csphase=csphase, name=name, units=units)
@classmethod
def from_netcdf(self, filename, lmax=None, normalization='4pi', csphase=1,
name=None, units=None):
"""
Initialize the class with spherical harmonic coefficients from a
netcdf file.
Usage
-----
x = SHCoeffs.from_netcdf(filename, [lmax, normalization, csphase,
name, units])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
filename : str
Name of the file, including path.
lmax : int, optional, default = None
The maximum spherical harmonic degree to read.
normalization : str, optional, default = '4pi'
Spherical harmonic normalization if not specified in the netcdf
file: '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 if not specified in the netcdf
file: 1 to exclude the phase factor, or -1 to include it.
name : str, optional, default = None
The name of the dataset.
units : str, optional, default = None
The units of the spherical harmonic coefficients.
Description
-----------
The format of the netcdf file has to be exactly as the format that is
used in SHCoeffs.to_netcdf().
"""
ds = _xr.open_dataset(filename)
try:
normalization = ds.coeffs.normalization
except:
pass
if type(normalization) is not str:
raise ValueError('normalization must be a string. '
'Input type was {:s}'
.format(str(type(normalization))))
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The input normalization must be '4pi', 'ortho', "
"'schmidt', or 'unnorm'. Provided value was {:s}"
.format(repr(normalization))
)
try:
csphase = ds.coeffs.csphase
except:
pass
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be 1 or -1. Input value was {:s}"
.format(repr(csphase))
)
try:
units = ds.coeffs.units
except:
pass
lmaxout = ds.dims['degree'] - 1
c = _np.tril(ds.coeffs.data)
s = _np.triu(ds.coeffs.data, k=1)
s = _np.vstack([s[-1], s[:-1]])
s = _np.transpose(s)
if isinstance(lmax, int):
c, s = c[:lmax+1, :lmax+1], s[:lmax+1, :lmax+1]
lmaxout = lmax
if normalization.lower() == 'unnorm' and lmaxout > 85:
_warnings.warn("Calculations using unnormalized coefficients " +
"are stable only for degrees less than or equal " +
"to 85. lmax for the coefficients will be set to " +
"85. Input value was {:d}.".format(lmaxout),
category=RuntimeWarning)
lmaxout = 85
c, s = c[:lmaxout+1, :lmaxout+1], s[:lmaxout+1, :lmaxout+1]
coeffs = _np.array([c, s])
try:
cerrors = _np.tril(ds.errors.data)
serrors = _np.triu(ds.errors.data, k=1)
serrors = _np.vstack([serrors[-1], serrors[:-1]])
serrors = _np.transpose(serrors)
cerrors = cerrors[:lmaxout+1, :lmaxout+1]
serrors = serrors[:lmaxout+1, :lmaxout+1]
errors = _np.array([cerrors, serrors])
error_kind = ds.errors.error_kind
except:
errors = None
error_kind = None
if _np.iscomplexobj(coeffs):
kind = 'complex'
else:
kind = 'real'
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, errors=errors, error_kind=error_kind,
normalization=normalization.lower(),
csphase=csphase, name=name, units=units)
@classmethod
def from_cap(self, theta, lmax, clat=None, clon=None, normalization='4pi',
csphase=1, kind='real', name=None, units=None, degrees=True,
copy=True, backend=None, nthreads=None):
"""
Initialize the class with spherical harmonic coefficients of a
spherical cap centered at the north pole.
Usage
-----
x = SHCoeffs.from_cap(theta, lmax, [clat, clon, normalization, csphase,
kind, name, units, degrees, copy,
backend, nthreads])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
theta : float
The angular radius of the spherical cap, default in degrees.
lmax : int
The maximum spherical harmonic degree of the coefficients.
clat, clon : float, optional, default = None
Latitude and longitude of the center of the rotated spherical cap
(default in degrees).
normalization : str, optional, default = '4pi'
'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.
kind : str, optional, default = 'real'
'real' or 'complex' spherical harmonic coefficients.
name : str, optional, default = None
The name of the dataset.
units : str, optional, default = None
The units of the spherical harmonic coefficients.
degrees : bool, optional = True
If True, theta, clat, and clon are in degrees.
copy : bool, optional, default = True
If True, make a copy of array when initializing the class instance.
If False, initialize the class instance with a reference to array.
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
-----
The spherical harmonic coefficients are normalized such that the
average value of the function is equal to 1. To rotate the cap to a
specified latitude and longitude, specify the optional parameters clat
and clon.
"""
if type(normalization) is not str:
raise ValueError('normalization must be a string. ' +
'Input type is {:s}.'
.format(str(type(normalization))))
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. Input value is {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value is {:s}."
.format(repr(csphase))
)
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"kind must be 'real' or 'complex'. " +
"Input value is {:s}.".format(repr(kind)))
if (clat is None and clon is not None) or \
(clat is not None and clon is None):
raise ValueError('clat and clon must both be input. ' +
'clat = {:s}, clon = {:s}.'
.format(repr(clat), repr(clon)))
if degrees is True:
theta = _np.deg2rad(theta)
cl = _shtools.SphericalCapCoef(theta, lmax)
coeffs = _np.zeros((2, lmax+1, lmax+1))
coeffs[0, 0:lmax+1, 0] = cl[0:lmax+1]
coeffs = _convert(coeffs, normalization_in='4pi',
normalization_out=normalization,
csphase_in=1, csphase_out=csphase
)
if kind == 'complex':
coeffs = _shtools.SHrtoc(coeffs)
for cls in self.__subclasses__():
if cls.istype(kind):
temp = cls(coeffs[:, 0:lmax+1, 0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, name=name, units=units, copy=copy)
if clat is not None and clon is not None:
if backend is None:
backend = preferred_backend()
if degrees is True:
temp = temp.rotate(0., -90 + clat, -clon, degrees=True,
backend=backend, nthreads=nthreads)
else:
temp = temp.rotate(0., -_np.pi/2. + clat, -clon,
degrees=False, backend=backend,
nthreads=nthreads)
return temp
# ---- Define methods that modify internal variables ----
def set_coeffs(self, values, ls, ms):
"""
Set spherical harmonic coefficients in-place to specified values.
Usage
-----
x.set_coeffs(values, ls, ms)
Parameters
----------
values : float or complex (list)
The value(s) of the spherical harmonic coefficient(s).
ls : int (list)
The degree(s) of the coefficient(s) that should be set.
ms : int (list)
The order(s) of the coefficient(s) that should be set. Positive
and negative values correspond to the cosine and sine
components, respectively.
Examples
--------
x.set_coeffs(10., 1, 1) # x.coeffs[0, 1, 1] = 10.
x.set_coeffs(5., 1, -1) # x.coeffs[1, 1, 1] = 5.
x.set_coeffs([1., 2], [1, 2], [0, -2]) # x.coeffs[0, 1, 0] = 1.
# x.coeffs[1, 2, 2] = 2.
"""
# Ensure that the type is correct
values = _np.array(values)
ls = _np.array(ls)
ms = _np.array(ms)
mneg_mask = (ms < 0).astype(_np.int_)
self.coeffs[mneg_mask, ls, _np.abs(ms)] = values
# ---- IO Routines
def to_file(self, filename, format='shtools', header=None, header2=None,
errors=True, lmax=None, encoding=None, **kwargs):
"""
Save raw spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format='shtools', header, header2, errors, lmax,
encoding])
x.to_file(filename, format='dov', [header, header2, errors, lmax,
encoding])
x.to_file(filename, format='bshc', [lmax])
x.to_file(filename, format='npy', [**kwargs])
Parameters
----------
filename : str
Name of the output file. If the filename ends with '.gz', the file
will be compressed using gzip.
format : str, optional, default = 'shtools'
'shtools', 'dov', 'bshc' or 'npy'.
header : str, optional, default = None
A header string written to an 'shtools' or 'dov' formatted file
directly before the spherical harmonic coefficients.
header2 : str, optional, default = None
A second header string written to an 'shtools' or 'dov' formatted
file directly before the spherical harmonic coefficients.
errors : bool, optional, default = False
If True, save the errors in the file (for 'shtools' formatted
files only).
lmax : int, optional, default = self.lmax