/
shcoeffsgrid.py
2614 lines (2273 loc) · 103 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 Coefficients classes
SHCoeffs : SHRealCoeffs, SHComplexCoeffs
"""
from __future__ import absolute_import as _absolute_import
from __future__ import division as _division
from __future__ import print_function as _print_function
import numpy as _np
import matplotlib as _mpl
import matplotlib.pyplot as _plt
import copy as _copy
from .. import shtools as _shtools
from ..spectralanalysis import spectrum as _spectrum
# =============================================================================
# ========= 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(numpy.zeros((2, lmax+1, lmax+1)))
>>> x = SHCoeffs.from_random(powerspectrum[0:lmax+1])
>>> x = SHCoeffs.from_zeros(lmax)
>>> x = SHCoeffs.from_file('fname.dat')
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.
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', or
'schmidt'.
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'.
Each class instance provides the following methods:
to_array() : Return an array of spherical harmonic coefficients
with a different normalization convention.
to_file() : Save raw spherical harmonic coefficients as a file.
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.
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.
expand() : Evaluate the coefficients either on a spherical
grid and return an SHGrid class instance, or for
a list of latitude and longitude coordinates.
copy() : Return a copy of the class instance.
plot_spectrum() : Plot the spectrum as a function of spherical
harmonic degree.
plot_spectrum2d() : Plot the 2D spectrum of all spherical harmonic
coefficients.
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'
'>>> SHCoeffs.from_array?\n'
'>>> SHCoeffs.from_random?\n'
'>>> SHCoeffs.from_zeros?\n'
'>>> SHCoeffs.from_file?\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' 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.
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'):
raise ValueError(
"The normalization must be '4pi', 'ortho' " +
"or 'schmidt'. 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))
)
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, copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHCoeffs.from_array(array, [normalization, csphase, copy])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmax+1, lmax+1).
The input spherical harmonic coefficients.
normalization : str, optional, default = '4pi'
'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.
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'):
raise ValueError(
"The normalization must be '4pi', 'ortho' " +
"or 'schmidt'. 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))
)
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, normalization=normalization.lower(),
csphase=csphase, copy=copy)
@classmethod
def from_random(self, power, kind='real', normalization='4pi', csphase=1,
exact_power=False):
"""
Initialize the class with spherical harmonic coefficients as random
variables.
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 using the keyword exact_power.
Usage
-----
x = SHCoeffs.from_random(power, [kind, normalization, csphase,
exact_power])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
power : ndarray, shape (lmax+1)
numpy array of shape (lmax+1) that specifies the expected power per
degree l of the random coefficients.
kind : str, optional, default = 'real'
'real' or 'complex' spherical harmonic coefficients.
normalization : str, optional, default = '4pi'
'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.
exact_power : bool, optional, default = False
The total variance of the coefficients is set exactly to the input
power. This means that the distribution of power at degree l
amongst the angular orders is random, but the total power is fixed.
"""
# 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'):
raise ValueError(
"The input normalization must be '4pi', 'ortho' " +
"or 'schmidt'. 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)))
nl = len(power)
l = _np.arange(nl)
# create coefficients with unit variance, which returns an expected
# total power per degree of (2l+1)
if kind.lower() == 'real':
coeffs = _np.random.normal(size=(2, nl, nl))
elif kind.lower() == 'complex':
# - need to divide by sqrt 2 as there are two terms for each coeff.
coeffs = (_np.random.normal(size=(2, nl, nl)) +
1j * _np.random.normal(size=(2, nl, nl))) / _np.sqrt(2.)
if exact_power:
power_per_l = _spectrum(coeffs, normalization=normalization,
unit='per_l')
coeffs *= _np.sqrt(
power / power_per_l)[_np.newaxis, :, _np.newaxis]
else:
if normalization.lower() == '4pi':
coeffs *= _np.sqrt(
power / (2.0 * l + 1.0))[_np.newaxis, :, _np.newaxis]
elif normalization.lower() == 'ortho':
coeffs *= _np.sqrt(
4.0 * _np.pi * power / (2.0 * l + 1.0)
)[_np.newaxis, :, _np.newaxis]
elif normalization.lower() == 'schmidt':
coeffs *= _np.sqrt(power)[_np.newaxis, :, _np.newaxis]
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', csphase=1, **kwargs):
"""
Initialize the class with spherical harmonic coefficients from a file.
Usage
-----
x = SHCoeffs.from_file(filename, lmax, [format='shtools', kind,
normalization, csphase, skip])
x = SHCoeffs.from_file(filename, [format='npy', kind, normalization,
csphase, **kwargs])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
filename : str
Name of the file, including path.
lmax : int, required when format = 'shtools'
Maximum spherical harmonic degree to read from the file when format
is 'shtools'.
format : str, optional, default = 'shtools'
'shtools' format or binary numpy 'npy' format.
kind : str, optional, default = 'real'
'real' or 'complex' spherical harmonic coefficients.
normalization : str, optional, default = '4pi'
'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.
skip : int, required when format = 'shtools'
Number of lines to skip at the beginning of the file when format is
'shtools'.
**kwargs : keyword argument list, optional for format = 'npy'
Keyword arguments of numpy.load() when format is 'npy'.
Description
-----------
If format='shtools', spherical harmonic coefficients will be read from
an ascii-formatted file. The maximum spherical harmonic degree that is
read is determined by the input value lmax. If the optional value skip
is specified, parsing of the file will commence after the first skip
lines. For this format, each line of the file must contain
l, m, cilm[0, l, m], cilm[1, l, m]
For each value of increasing l, increasing from zero, all the angular
orders are listed in inceasing order, from 0 to l. For more
information, see SHRead.
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'):
raise ValueError(
"The input normalization must be '4pi', 'ortho' " +
"or 'schmidt'. 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 format.lower() == 'shtools' and lmax is None:
raise ValueError("lmax must be specified when format is 'shtools'")
if format.lower() == 'shtools':
if kind.lower() == 'real':
coeffs, lmax = _shtools.SHRead(fname, lmax, **kwargs)
else:
raise NotImplementedError(
"Complex coefficients are not yet implemented for "
"format='shtools'")
elif format.lower() == 'npy':
coeffs = _np.load(fname, **kwargs)
else:
raise NotImplementedError(
'format={:s} not yet implemented'.format(repr(format)))
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs, normalization=normalization.lower(),
csphase=csphase)
def copy(self):
"""Return a deep copy of the class instance."""
return _copy.deepcopy(self)
def to_file(self, filename, format='shtools', **kwargs):
"""
Save raw spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format, **kwargs])
Parameters
----------
filename : str
Name of the output file.
format : str, optional, default = 'shtools'
'shtools' or 'npy'. See method from_file for more information.
**kwargs : keyword argument list, optional for format = 'npy'
Keyword arguments of numpy.save().
"""
if format is 'shtools':
with open(filename, mode='w') as file:
for l in range(self.lmax+1):
for m in range(l+1):
file.write('{:d}, {:d}, {:e}, {:e}\n'
.format(l, m, self.coeffs[0, l, m],
self.coeffs[1, l, m]))
elif format is 'npy':
_np.save(filename, self.coeffs, **kwargs)
else:
raise NotImplementedError(
'format={:s} not yet implemented'.format(repr(format)))
# ---- operators ----
def __add__(self, other):
"""
Add 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):
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 be of ' +
'the same kind and have the same ' +
'normalization and csphase.')
elif _np.isscalar(other) is True:
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 __radd__(self, other):
"""
Add two similar sets of coefficients or coefficients and a scalar:
other + self.
"""
return self.__add__(other)
def __sub__(self, other):
"""
Subtract 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):
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 be of ' +
'the same kind and have the same ' +
'normalization and csphase.')
elif _np.isscalar(other) is True:
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 __rsub__(self, other):
"""
Subtract two similar sets of coefficients or coefficients and a scalar:
other - self.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind):
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 be of ' +
'the same kind and have the same ' +
'normalization and csphase.')
elif _np.isscalar(other) is True:
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
coeffs[self.mask] = other - self.coeffs[self.mask]
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):
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 be of ' +
'the same kind and have the same ' +
'normalization and csphase.')
elif _np.isscalar(other) is True:
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 __div__(self, other):
"""
Divide two similar sets of coefficients or coefficients and a scalar
when __future__.division is not in effect: self / other.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind):
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 be of ' +
'the same kind and have the same ' +
'normalization and csphase.')
elif _np.isscalar(other) is True:
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 __truediv__(self, other):
"""
Divide two similar sets of coefficients or coefficients and a scalar
when __future__.division is in effect: self / other.
"""
if isinstance(other, SHCoeffs):
if (self.normalization == other.normalization and self.csphase ==
other.csphase and self.kind == other.kind):
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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 be of ' +
'the same kind and have the same ' +
'normalization and csphase.')
elif _np.isscalar(other) is True:
coeffs = _np.zeros([2, self.lmax+1, self.lmax+1])
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.')
# ---- 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)
def spectrum(self, convention='power', unit='per_l', base=10.):
"""
Return the spectrum as a function of spherical harmonic degree.
Usage
-----
power = x.spectrum([convention, unit, base])
Returns
-------
power : ndarray, shape (lmax+1)
1-D numpy ndarray of the spectrum, where lmax is the maximum
spherical harmonic degree.
Parameters
----------
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.
Description
-----------
This function returns either the power spectrum, energy spectrum, or
l2-norm spectrum. 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).
"""
return _spectrum(self.coeffs, normalization=self.normalization,
convention=convention, unit=unit, base=base)
# ---- Set individual coefficient
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([1.,2], [1,2], [0,-2]) # x.coeffs[0,1,0] = 1.
# x.coeffs[1,2,2] = 2.
"""
# make sure 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
# ---- Return coefficients with a different normalization convention ----
def to_array(self, normalization=None, csphase=None, lmax=None):
"""
Return spherical harmonics 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' or
'schmidt' for geodesy 4pi normalized, orthonormalized, or Schmidt
semi-normalized 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 normalization is None:
normalization = self.normalization
if csphase is None:
csphase = self.csphase
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'):
raise ValueError(
"normalization must be '4pi', 'ortho' " +
"or 'schmidt'. 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 lmax is not None:
if lmax > self.lmax:
raise ValueError('Output lmax is greater than the maximum ' +
'degree of the coefficients. ' +
'Output lmax = {:d}, lmax of coefficients ' +
'= {:d}'.format(lmax, self.lmax))
if lmax is None:
lmax = self.lmax
return self._to_array(
output_normalization=normalization.lower(),
output_csphase=csphase, lmax=lmax)
# ---- Rotate the coordinate system ----
def rotate(self, alpha, beta, gamma, degrees=True, dj_matrix=None):
"""
Rotate the coordinate system used to express the spherical harmonic
coefficients and return a new class instance.
Usage
-----
x_rotated = x.rotate(alpha, beta, gamma, [degrees, dj_matrix])
Returns
-------
x_rotated : SHCoeffs class instance
Parameters
----------
alpha, beta, gamma : float
The three Euler rotation angles in degrees.
degrees : bool, optional, default = True
True if the Euler angles are in degrees, False if they are in
radians.
dj_matrix : ndarray, optional, default = None
The djpi2 rotation matrix computed by a call to djpi2.
Description
-----------
This method will take the spherical harmonic coefficients of a
function, rotate the coordinate frame by the three Euler anlges, and
output the spherical harmonic coefficients of the rotated function.
The rotation of a coordinate system or body can be viewed in two
complementary ways involving three successive rotations. Both methods
have the same initial and final configurations, and the angles listed
in both schemes are the same.
Scheme A:
(I) Rotation about the z axis by alpha.
(II) Rotation about the new y axis by beta.
(III) Rotation about the new z axis by gamma.
Scheme B:
(I) Rotation about the z axis by gamma.
(II) Rotation about the initial y axis by beta.
(III) Rotation about the initial z axis by alpha.
The rotations can further be viewed either as a rotation of the
coordinate system or the physical body. For a rotation of the
coordinate system without rotation of the physical body, use
(alpha, beta, gamma).
For a rotation of the physical body without rotation of the coordinate
system, use
(-gamma, -beta, -alpha).
To perform the inverse transform of (alpha, beta, gamma), use
(-gamma, -beta, -alpha).
Note that this routine uses the "y convention", where the second
rotation is with respect to the new y axis. If alpha, beta, and gamma
were orginally defined in terms of the "x convention", where the second
rotation was with respect to the new x axis, the Euler angles according
to the y convention would be
alpha_y=alpha_x-pi/2, beta_x=beta_y, and gamma_y=gamma_x+pi/2.
"""
if degrees:
angles = _np.radians([alpha, beta, gamma])
else:
angles = _np.array([alpha, beta, gamma])
rot = self._rotate(angles, dj_matrix)
return rot
# ---- Convert spherical harmonic coefficients to a different normalization
def convert(self, normalization=None, csphase=None, lmax=None, kind=None,
check=True):
"""
Return a SHCoeff class instance with a different normalization
convention.
Usage
-----
clm = x.convert([normalization, csphase, lmax, kind, check])
Returns
-------
clm : SHCoeffs class instance
Parameters
----------
normalization : str, optional, default = x.normalization
Normalization of the output class: '4pi', 'ortho' or 'schmidt'
for geodesy 4pi normalized, orthonormalized, or Schmidt semi-
normalized coefficients, respectively.
csphase : int, optional, default = x.csphase
Condon-Shortley phase convention for the output class: 1 to exclude
the phase factor, or -1 to include it.
lmax : int, optional, default = x.lmax
Maximum spherical harmonic degree to output.
kind : str, optional, default = clm.kind
'real' or 'complex' spherical harmonic coefficients for the output
class.
check : bool, optional, default = True
When converting complex coefficients to real coefficients, if True,
check if function is entirely real.
"""
if normalization is None:
normalization = self.normalization
if csphase is None:
csphase = self.csphase
if lmax is None:
lmax = self.lmax
if kind is None:
kind = self.kind
# check argument consistency
if type(normalization) != str:
raise ValueError('normalization must be a string. ' +
'Input type was {: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 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 != self.kind):
if (kind == 'complex'):
temp = self._make_complex()
else:
temp = self._make_real(check=check)
coeffs = temp.to_array(normalization=normalization.lower(),
csphase=csphase, lmax=lmax)
else:
coeffs = self.to_array(normalization=normalization.lower(),
csphase=csphase, lmax=lmax)
# because to_array is already a copy, we can pass it as reference
# to save time
return SHCoeffs.from_array(coeffs,
normalization=normalization.lower(),
csphase=csphase, copy=False)
# ---- Expand the coefficients onto a grid ----
def expand(self, grid='DH', lat=None, lon=None, degrees=True, zeros=None,
lmax=None, lmax_calc=None):
"""
Evaluate the spherical harmonic coefficients either on a grid or for
a list of coordinates.
Usage
-----
f = x.expand(lat, lon, [lmax_calc, degrees])
g = x.expand([grid, lmax, lmax_calc, zeros])
Returns
-------
f : float, ndarray, or list
g : SHGrid class instance
Parameters
----------
lat, lon : int, float, ndarray, or list, optional, default = None
Latitude and longitude coordinates where the function is to be
evaluated.
degrees : bool, optional, default = True
True if lat and lon are in degrees, False if in radians.
grid : str, optional, default = 'DH'
'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.lmax
The maximum spherical harmonic degree, which determines the grid
spacing of the output grid.
lmax_calc : int, optional, default = x.lmax
The maximum spherical harmonic degree to use when evaluating the
function.
zeros : ndarray, optional, default = None
The cos(colatitude) nodes used in the Gauss-Legendre Quadrature
grids.
Description
-----------
For more information concerning the spherical harmonic expansions and
the properties of the output grids, see the documentation for
SHExpandDH, SHExpandDHC, SHExpandGLQ and SHExpandGLQC.
"""
if lat is not None and lon is not None:
if lmax_calc is None:
lmax_calc = self.lmax
values = self._expand_coord(lat=lat, lon=lon, degrees=degrees,
lmax_calc=lmax_calc)
return values
else: