-
Notifications
You must be signed in to change notification settings - Fork 106
/
shcoeffsgrid.py
4514 lines (3980 loc) · 185 KB
/
shcoeffsgrid.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 Coefficient and 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 warnings as _warnings
from scipy.special import factorial as _factorial
import xarray as _xr
from .. import shtools as _shtools
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
try:
import pygmt2 as _pygmt
except ModuleNotFoundError:
print('\n*** Could not import the module pygmt. ***')
# =============================================================================
# ========= COEFFICIENT CLASSES =========================================
# =============================================================================
class SHCoeffs(object):
"""
Spherical Harmonics Coefficient 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_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.
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'.
header : A list of values (of type str) from the header line of the
input file used to initialize the class (for 'shtools'
formatted files).
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.
volume() : Calculate the volume 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.
plot_spectrum() : Plot the spectrum as a function of spherical
harmonic degree.
plot_cross_spectrum() : Plot the cross-spectrum of two functions.
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.
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_cap\n'
)
# ---- Factory methods ----
@classmethod
def from_zeros(self, lmax, kind='real', normalization='4pi', csphase=1):
"""
Initialize class with spherical harmonic coefficients set to zero from
degree 0 to lmax.
Usage
-----
x = SHCoeffs.from_zeros(lmax, [normalization, csphase])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
lmax : int
The highest spherical harmonic degree l of the 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.
kind : str, optional, default = 'real'
'real' or 'complex' spherical harmonic coefficients.
"""
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"Kind must be 'real' or 'complex'. " +
"Input value was {: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 was {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value was {: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 was {:d}.".format(lmax),
category=RuntimeWarning)
lmax = 85
nl = lmax + 1
if kind.lower() == 'real':
coeffs = _np.zeros((2, nl, nl))
else:
coeffs = _np.zeros((2, nl, nl), dtype=complex)
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, normalization=normalization.lower(),
csphase=csphase)
@classmethod
def from_array(self, coeffs, normalization='4pi', csphase=1, lmax=None,
copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHCoeffs.from_array(array, [normalization, csphase, lmax, copy])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmaxin+1, lmaxin+1).
The input 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.
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.
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) != 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 normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. Input value was {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value was {:s}."
.format(repr(csphase))
)
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 was {:d}.".format(lmax),
category=RuntimeWarning)
lmax = 85
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs[:, 0:lmax+1, 0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, copy=copy)
@classmethod
def from_random(self, power, lmax=None, kind='real', normalization='4pi',
csphase=1, exact_power=False, 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,
exact_power, seed])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
power : ndarray, shape (L+1)
numpy array of shape (L+1) that specifies the expected power per
degree l of the random coefficients, where L is the maximum
spherical harmonic bandwidth.
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.
exact_power : bool, optional, default = False
The total variance of the coefficients is set exactly to the input
power. The distribution of power at degree l amongst the angular
orders is random, but the total power is fixed.
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 at degree l is equal to the total power at degree
l divided by the number of coefficients 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) != 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))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be 1 or -1. Input value was {:s}"
.format(repr(csphase))
)
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"kind must be 'real' or 'complex'. " +
"Input value was {:s}.".format(repr(kind)))
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 was {: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=complex)
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_per_l = _spectrum(coeffs, normalization='4pi', unit='per_l')
coeffs *= _np.sqrt(
power[0:nl] / power_per_l)[_np.newaxis, :, _np.newaxis]
else:
coeffs *= _np.sqrt(
power[0:nl] / (2 * degrees + 1))[_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, normalization=normalization.lower(),
csphase=csphase)
@classmethod
def from_file(self, fname, lmax=None, format='shtools', kind='real',
normalization='4pi', skip=0, header=False,
csphase=1, **kwargs):
"""
Initialize the class with spherical harmonic coefficients from a file.
Usage
-----
x = SHCoeffs.from_file(filename, [format='shtools', lmax,
normalization, csphase, skip,
header])
x = SHCoeffs.from_file(filename, [format='npy', normalization,
csphase, **kwargs])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
filename : str
File name or URL containing the text-formatted spherical harmonic
coefficients. filename will be treated as a URL if it starts with
'http:https://', 'https://', or 'ftp:https://'.
format : str, optional, default = 'shtools'
'shtools' format or binary numpy 'npy' format.
lmax : int, optional, default = None
The maximum spherical harmonic degree to read from 'shtools'
formatted files.
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 when format is
'shtools'.
header : bool, optional, default = False
If True, read a list of values from the header line of an 'shtools'
formatted file.
**kwargs : keyword argument list, optional for format = 'npy'
Keyword arguments of numpy.load() when format is 'npy'.
Notes
-----
If format='shtools', spherical harmonic coefficients will be read from
a text file. 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. All lines that do not start with 2
integers and that are less than 3 words long will be treated as
comments and ignored. For this format, each line of the file must
contain
l, m, coeffs[0, l, m], coeffs[1, l, m]
where l and m are the spherical harmonic degree and order,
respectively. The terms coeffs[1, l, 0] can be neglected as they are
zero. For more information, see `shio.shread()`.
If filename starts with http:https://, https://, or ftp:https://, the file will be
treated as a URL. In this case, the file will be downloaded in its
entirety before it is parsed.
If format='npy', a binary numpy 'npy' file will be read using
numpy.load().
"""
if type(normalization) != 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))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be 1 or -1. Input value was {:s}"
.format(repr(csphase))
)
header_list = None
if format.lower() == 'shtools':
if header is True:
coeffs, lmaxout, header_list = _shread(fname, lmax=lmax,
skip=skip, header=True)
else:
coeffs, lmaxout = _shread(fname, lmax=lmax, skip=skip)
elif format.lower() == 'npy':
coeffs = _np.load(fname, **kwargs)
lmaxout = coeffs.shape[1] - 1
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 was {:d}.".format(lmaxout),
category=RuntimeWarning)
lmaxout = 85
if _np.iscomplexobj(coeffs):
kind = 'complex'
else:
kind = 'real'
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, normalization=normalization.lower(),
csphase=csphase, header=header_list)
@classmethod
def from_cap(self, theta, lmax, clat=None, clon=None, normalization='4pi',
csphase=1, kind='real', degrees=True, copy=True):
"""
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, degrees, copy])
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.
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.
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) != 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 normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. Input value was {:s}."
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value was {:s}."
.format(repr(csphase))
)
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"kind must be 'real' or 'complex'. " +
"Input value was {: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, copy=copy)
if clat is not None and clon is not None:
if degrees is True:
temp = temp.rotate(0., -90 + clat, -clon, degrees=True)
else:
temp = temp.rotate(0., -_np.pi/2. + clat, -clon,
degrees=False)
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, **kwargs):
"""
Save raw spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format='shtools', header])
x.to_file(filename, [format='npy', **kwargs])
Parameters
----------
filename : str
Name of the output file.
format : str, optional, default = 'shtools'
'shtools' or 'npy'. See method from_file() for more information.
header : str, optional, default = None
A header string written to an 'shtools'-formatted file directly
before the spherical harmonic coefficients.
**kwargs : keyword argument list, optional for format = 'npy'
Keyword arguments of numpy.save().
Notes
-----
If format='shtools', the coefficients will be written to an ascii
formatted file. The first line of the file is an optional user provided
header line, and the spherical harmonic coefficients are then listed,
with increasing degree and order, with the format
l, m, coeffs[0, l, m], coeffs[1, l, m]
where l and m are the spherical harmonic degree and order,
respectively.
If format='npy', the spherical harmonic coefficients will be saved to
a binary numpy 'npy' file using numpy.save().
"""
if format == 'shtools':
with open(filename, mode='w') as file:
if header is not None:
file.write(header + '\n')
for l in range(self.lmax+1):
for m in range(l+1):
file.write('{:d}, {:d}, {:.16e}, {:.16e}\n'
.format(l, m, self.coeffs[0, l, m],
self.coeffs[1, l, m]))
elif format == 'npy':
_np.save(filename, self.coeffs, **kwargs)
else:
raise NotImplementedError(
'format={:s} not implemented'.format(repr(format)))
def to_array(self, normalization=None, csphase=None, lmax=None):
"""
Return spherical harmonic coefficients as a numpy array.
Usage
-----
coeffs = x.to_array([normalization, csphase, lmax])
Returns
-------
coeffs : ndarry, shape (2, lmax+1, lmax+1)
numpy ndarray of the spherical harmonic coefficients.
Parameters
----------
normalization : str, optional, default = x.normalization
Normalization of the output coefficients: '4pi', 'ortho',
'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized,
Schmidt semi-normalized, or unnormalized coefficients,
respectively.
csphase : int, optional, default = x.csphase
Condon-Shortley phase convention: 1 to exclude the phase factor,
or -1 to include it.
lmax : int, optional, default = x.lmax
Maximum spherical harmonic degree to output. If lmax is greater
than x.lmax, the array will be zero padded.
Notes
-----
This method will return an array of the spherical harmonic coefficients
using a different normalization and Condon-Shortley phase convention,
and a different maximum spherical harmonic degree. If the maximum
degree is smaller than the maximum degree of the class instance, the
coefficients will be truncated. Conversely, if this degree is larger
than the maximum degree of the class instance, the output array will be
zero padded.
"""
if normalization is None:
normalization = self.normalization
if csphase is None:
csphase = self.csphase
if lmax is None:
lmax = self.lmax
coeffs = _convert(self.coeffs, normalization_in=self.normalization,
normalization_out=normalization,
csphase_in=self.csphase, csphase_out=csphase,
lmax=lmax)
return coeffs
def copy(self):
"""
Return a deep copy of the class instance.
Usage
-----
copy = x.copy()
"""
return _copy.deepcopy(self)
def info(self):
"""
Print a summary of the data stored in the SHCoeffs instance.
Usage
-----
x.info()
"""
print(repr(self))
# ---- Mathematical operators ----
def __add__(self, other):
"""
Add two similar sets of coefficients or coefficients and a scalar:
self + other. For the addition of a scalar, only the degree 0
term is modified.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind and
self.lmax == other.lmax):
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = (self.coeffs[self.mask] +
other.coeffs[self.mask])
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('The two sets of coefficients must have the '
'same kind, normalization, csphase and '
'lmax.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not add a complex constant to real '
'coefficients.')
coeffs = self.coeffs.copy()
coeffs[0, 0, 0] += other
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __radd__(self, other):
"""
Add two similar sets of coefficients or coefficients and a scalar:
other + self. For the addition of a scalar, only the degree 0
term is modified.
"""
return self.__add__(other)
def __sub__(self, other):
"""
Subtract two similar sets of coefficients or coefficients and a scalar:
self - other. For the subtraction of a scalar, only the degree 0
term is modified.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind and
self.lmax == other.lmax):
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = (self.coeffs[self.mask] -
other.coeffs[self.mask])
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('The two sets of coefficients must have the '
'same kind, normalization, csphase and '
'lmax.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not subtract a complex constant from '
'real coefficients.')
coeffs = self.coeffs.copy()
coeffs[0, 0, 0] -= other
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __rsub__(self, other):
"""
Subtract two similar sets of coefficients or coefficients and a scalar:
other - self. For the subtraction from a scalar, self is multiplied by
-1 and then other is added to the degree 0 coefficient.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind and
self.lmax == other.lmax):
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = (other.coeffs[self.mask] -
self.coeffs[self.mask])
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('The two sets of coefficients must have the '
'same kind, normalization, csphase and '
'lmax.')
elif _np.isscalar(other) is True:
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not subtract a complex constant from '
'real coefficients.')
coeffs = - self.coeffs.copy()
coeffs[0, 0, 0] += other
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __mul__(self, other):
"""
Multiply two similar sets of coefficients or coefficients and a scalar:
self * other.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind and
self.lmax == other.lmax):
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = (self.coeffs[self.mask] *
other.coeffs[self.mask])
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('The two sets of coefficients must have the '
'same kind, normalization, csphase and '
'lmax.')
elif _np.isscalar(other) is True:
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not multiply real coefficients by '
'a complex constant.')
coeffs[self.mask] = self.coeffs[self.mask] * other
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __rmul__(self, other):
"""
Multiply two similar sets of coefficients or coefficients and a scalar:
other * self.
"""
return self.__mul__(other)
def __truediv__(self, other):
"""
Divide two similar sets of coefficients or coefficients and a scalar:
self / other.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind and
self.lmax == other.lmax):
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = (self.coeffs[self.mask] /
other.coeffs[self.mask])
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('The two sets of coefficients must have the '
'same kind, normalization, csphase and '
'lmax.')
elif _np.isscalar(other) is True:
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
if self.kind == 'real' and _np.iscomplexobj(other):
raise ValueError('Can not multiply real coefficients by '
'a complex constant.')
coeffs[self.mask] = self.coeffs[self.mask] / other
return SHCoeffs.from_array(coeffs, csphase=self.csphase,
normalization=self.normalization)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __pow__(self, other):
"""
Raise the spherical harmonic coefficients to a scalar power:
pow(self, other).
"""
if _np.isscalar(other) is True:
return SHCoeffs.from_array(pow(self.coeffs, other),
csphase=self.csphase,
normalization=self.normalization)
else:
raise NotImplementedError('Mathematical operator not implemented '
'for these operands.')
def __repr__(self):
return ('kind = {:s}\n'
'normalization = {:s}\n'
'csphase = {:d}\n'
'lmax = {:d}\n'
'header = {:s}'.format(
repr(self.kind), repr(self.normalization), self.csphase,
self.lmax, repr(self.header)))
# ---- Extract data ----
def degrees(self):
"""
Return a numpy array with the spherical harmonic degrees from 0 to
lmax.
Usage
-----
degrees = x.degrees()
Returns
-------
degrees : ndarray, shape (lmax+1)
1-D numpy ndarray listing the spherical harmonic degrees, where
lmax is the maximum spherical harmonic degree.
"""
return _np.arange(self.lmax + 1)