/
shgravcoeffs.py
2358 lines (2082 loc) · 102 KB
/
shgravcoeffs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Class for spherical harmonic coefficients of the gravitational potential.
"""
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
import warnings as _warnings
from scipy.special import factorial as _factorial
from .shcoeffsgrid import SHCoeffs as _SHCoeffs
from .shcoeffsgrid import SHRealCoeffs as _SHRealCoeffs
from .shcoeffsgrid import DHRealGrid as _DHRealGrid
from .shgravgrid import SHGravGrid as _SHGravGrid
from .shtensor import SHGravTensor as _SHGravTensor
from .shgeoid import SHGeoid as _SHGeoid
from ..constant import G as _G
from ..spectralanalysis import spectrum as _spectrum
from ..shio import convert as _convert
from ..shio import shread as _shread
from ..shtools import CilmPlusRhoHDH as _CilmPlusRhoHDH
from ..shtools import CilmPlusDH as _CilmPlusDH
from ..shtools import MakeGravGridDH as _MakeGravGridDH
from ..shtools import MakeGravGradGridDH as _MakeGravGradGridDH
from ..shtools import MakeGeoidGridDH as _MakeGeoidGridDH
# =============================================================================
# ========= SHGravCoeffs class =========================================
# =============================================================================
class SHGravCoeffs(object):
"""
Spherical harmonic coefficients class for the gravitational potential.
The coefficients of this class can be initialized using one of the four
constructor methods:
x = SHGravCoeffs.from_array(array, gm, r0)
x = SHGravCoeffs.from_random(powerspectrum, gm, r0)
x = SHGravCoeffs.from_zeros(lmax, gm, r0)
x = SHGravCoeffs.from_file('fname.dat')
x = SHGravCoeffs.from_shape(grid, rho, gm)
The normalization convention of the input coefficents is specified
by the optional 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.
errors : The uncertainties of the spherical harmonic coefficients.
gm : The gravitational constant times the mass times that is
associated with the gravitational potential coefficients.
r0 : The reference radius of the gravitational potential
coefficients.
omega : The angular rotation rate of the body.
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 (only 'real' is permissible).
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 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.
set_omega() : Set the angular rotation rate of the body.
set_coeffs() : Set coefficients in-place to specified values.
change_ref() : Return a new class instance referenced to a
different gm, or r0.
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() : Calculate the three vector components of the
gravity field, the total field, and the
gravitational potential, and return an SHGravGrid
class instance.
tensor() : Calculate the 9 components of the gravity tensor
and return an SHGravTensor class instance.
geoid() : Calculate the height of the geoid and return an
SHGeoid class instance.
plot_spectrum() : Plot the spectrum as a function of spherical
harmonic degree.
plot_spectrum2d() : Plot the 2D 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 the spherical harmonic coefficients as a file.
copy() : Return a copy of the class instance.
info() : Print a summary of the data stored in the
SHGravCoeffs instance.
"""
def __init__(self):
"""Unused constructor of the super class."""
print('Initialize the class using one of the class methods:\n'
'>>> pyshtools.SHGravCoeffs.from_array\n'
'>>> pyshtools.SHGravCoeffs.from_random\n'
'>>> pyshtools.SHGravCoeffs.from_zeros\n'
'>>> pyshtools.SHGravCoeffs.from_file\n'
'>>> pyshtools.SHGravCoeffs.from_shape\n')
# ---- Factory methods ----
@classmethod
def from_array(self, coeffs, gm, r0, omega=None, errors=None,
normalization='4pi', csphase=1, lmax=None, copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHGravCoeffs.from_array(array, gm, r0, [omega, errors,
normalization, csphase,
lmax, copy])
Returns
-------
x : SHGravCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmaxin+1, lmaxin+1).
The input spherical harmonic coefficients.
gm : float
The gravitational constant times the mass that is associated with
the gravitational potential coefficients.
mass : float
The mass of the planet in kg.
r0 : float
The reference radius of the spherical harmonic coefficients.
omega : float, optional, default = None
The angular rotation rate of the body.
errors : ndarray, optional, default = None
The uncertainties of the 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.
Notes
-----
If the degree-0 term of the input array is equal to zero, it will be
set to 1.
"""
if _np.iscomplexobj(coeffs):
raise TypeError('The input array must be 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))
)
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))
)
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
if coeffs[0, 0, 0] == 0:
_warnings.warn('The degree 0 term of the array was not set. This, '
'will be set to 1.', category=RuntimeWarning)
coeffs[0, 0, 0] = 1.0
if errors is not None:
clm = SHGravRealCoeffs(coeffs[:, 0:lmax+1, 0:lmax+1], gm=gm, r0=r0,
omega=omega, errors=errors[:, 0:lmax+1,
0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, copy=copy)
else:
clm = SHGravRealCoeffs(coeffs[:, 0:lmax+1, 0:lmax+1], gm=gm, r0=r0,
omega=omega,
normalization=normalization.lower(),
csphase=csphase, copy=copy)
return clm
@classmethod
def from_zeros(self, lmax, gm, r0, omega=None, errors=False,
normalization='4pi', csphase=1):
"""
Initialize the class with spherical harmonic coefficients set to zero
from degree 1 to lmax, and set the degree 0 term to 1.
Usage
-----
x = SHGravCoeffs.from_zeros(lmax, gm, r0, [omega, errors,
normalization, csphase])
Returns
-------
x : SHGravCoeffs class instance.
Parameters
----------
lmax : int
The maximum spherical harmonic degree l of the coefficients.
gm : float
The gravitational constant times the mass that is associated with
the gravitational potential coefficients.
r0 : float
The reference radius of the spherical harmonic coefficients.
omega : float, optional, default = None
The angular rotation rate of the body.
errors : bool, optional, default = False
If True, initialize the attribute errors with zeros.
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.
"""
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
coeffs = _np.zeros((2, lmax + 1, lmax + 1))
coeffs[0, 0, 0] = 1.0
if errors is False:
clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega,
normalization=normalization.lower(),
csphase=csphase)
else:
clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega,
errors=_np.zeros((2, lmax + 1, lmax + 1)),
normalization=normalization.lower(),
csphase=csphase)
return clm
@classmethod
def from_file(self, fname, format='shtools', gm=None, r0=None,
omega=None, lmax=None, normalization='4pi', skip=0,
header=True, errors=False, csphase=1, r0_index=0, gm_index=1,
omega_index=None, header_units='m', set_degree0=True,
**kwargs):
"""
Initialize the class with spherical harmonic coefficients from a file.
Usage
-----
x = SHGravCoeffs.from_file(filename, [format='shtools', gm, r0, omega,
lmax, normalization, csphase,
skip, header, errors, gm_index,
r0_index, omega_index,
header_units, set_degree0])
x = SHGravCoeffs.from_file(filename, format='npy', gm, r0,
[omega, normalization, csphase, **kwargs])
Returns
-------
x : SHGravCoeffs class instance.
Parameters
----------
filename : str
Name of the file, including path.
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.
header : bool, optional, default = True
If True, read a list of values from the header line of an 'shtools'
formatted file.
errors : bool, optional, default = False
If True, read errors from the file (for 'shtools' formatted files
only).
r0_index : int, optional, default = 0
For shtools formatted files, if header is True, r0 will be set
using the value from the header line with this index.
gm_index : int, optional, default = 1
For shtools formatted files, if header is True, gm will be set
using the value from the header line with this index.
omega_index : int, optional, default = None
For shtools formatted files, if header is True, omega will be set
using the value from the header line with this index.
gm : float, optional, default = None
The gravitational constant time the mass that is associated with
the gravitational potential coefficients.
r0 : float, optional, default = None
The reference radius of the spherical harmonic coefficients.
omega : float, optional, default = None
The angular rotation rate of the body.
header_units : str, optional, default = 'm'
The units used for r0 and gm in the header line of an shtools
formatted file: 'm' or 'km'. If 'km', the values of r0 and gm will
be converted to meters.
set_degree0 : bool, optional, default = True
If the degree-0 coefficient is zero, set this to 1.
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'.
**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
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. If a header line is read, r0_index,
gm_index, and omega_index, are used as the indices to set r0, gm, and
omega. If header_unit is specified as 'km', the values of r0 and gm
that are read from the header will be converted to meters.
For shtools formatted files, 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 errors are read,
each line must contain:
l, m, coeffs[0, l, m], coeffs[1, l, m], error[0, l, m], error[1, l, m]
If format='npy', a binary numpy 'npy' file will be read using
numpy.load().
If the degree 0 term of the file is zero (or not specified), this will
be set to 1.
"""
error = None
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 header_units.lower() not in ('m', 'km'):
raise ValueError("header_units can be only 'm', or 'km'. Input "
"value is {:s}.".format(repr(header_units)))
if format == 'shtools':
if r0_index is not None and r0 is not None:
raise ValueError('Can not specify both r0_index and r0')
if gm_index is not None and gm is not None:
raise ValueError('Can not specify both gm_index and gm')
if omega_index is not None and omega is not None:
raise ValueError('Can not specify both omega_index and omega')
if header is False and (r0 is None or gm is None):
raise ValueError('If header is False, r0 and gm must be '
'specified.')
header_list = None
if format.lower() == 'shtools':
if header is True:
if errors is True:
coeffs, error, lmaxout, header_list = _shread(
fname, lmax=lmax, skip=skip, header=True, error=True)
else:
coeffs, lmaxout, header_list = _shread(
fname, lmax=lmax, skip=skip, header=True)
else:
if errors is True:
coeffs, error, lmaxout = _shread(
fname, lmax=lmax, error=True, skip=skip)
else:
coeffs, lmaxout = _shread(fname, lmax=lmax, skip=skip)
elif format.lower() == 'npy':
if gm is None or r0 is None:
raise ValueError('For binary npy files, gm and r0 must be '
'specified.')
coeffs = _np.load(fname, **kwargs)
lmaxout = coeffs.shape[1] - 1
else:
raise NotImplementedError(
'format={:s} not implemented'.format(repr(format)))
if _np.iscomplexobj(coeffs):
raise TypeError('The input coefficients must be real.')
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 coeffs[0, 0, 0] == 0 and set_degree0:
coeffs[0, 0, 0] = 1.0
if format.lower() == 'shtools' and header is True:
if r0_index is not None:
r0 = float(header_list[r0_index])
if gm_index is not None:
gm = float(header_list[gm_index])
if omega_index is not None:
omega = float(header_list[omega_index])
if header_units.lower() == 'km':
r0 *= 1.e3
gm *= 1.e9
clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega,
errors=error,
normalization=normalization.lower(),
csphase=csphase, header=header_list)
return clm
@classmethod
def from_random(self, power, gm, r0, omega=None, function='geoid',
lmax=None, normalization='4pi', csphase=1,
exact_power=False):
"""
Initialize the class of gravitational potential spherical harmonic
coefficients as random variables with a given spectrum.
Usage
-----
x = SHGravCoeffs.from_random(power, gm, r0, [omega, function, lmax,
normalization,
csphase, exact_power])
Returns
-------
x : SHGravCoeffs class instance.
Parameters
----------
power : ndarray, shape (L+1)
numpy array of shape (L+1) that specifies the expected power per
degree l, where L is the maximum spherical harmonic bandwidth.
gm : float
The gravitational constant times the mass that is associated with
the gravitational potential coefficients.
r0 : float
The reference radius of the spherical harmonic coefficients.
omega : float, optional, default = None
The angular rotation rate of the body.
function : str, optional, default = 'geoid'
The type of input power spectrum: 'potential' for the gravitational
potential, 'geoid' for the geoid, 'radial' for the radial gravity,
or 'total' for the total gravity field.
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.
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.
Description
-----------
This routine returns a random realization of spherical harmonic
gravitational potential 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 (2l+1). These coefficients are then divided by a prefactor
that depends upon the function being used to calculate the spectrum:
gm/r0 for the gravitiational potential, r0 for the geoid, and
(l+1)*gm/(r**2) for the radial gravity. The power spectrum of the
random realization can be fixed exactly to the input spectrum by
setting exact_power to True.
Note that the degree 0 term is set to 1, and the degree-1 terms are
set to 0.
"""
if type(normalization) != str:
raise ValueError('normalization must be a string. '
'Input type was {:s}'
.format(str(type(normalization))))
if function.lower() not in ('potential', 'geoid', 'radial', 'total'):
raise ValueError(
"function must be of type 'potential', "
"'geoid', 'radial', or 'total'. Provided value was {:s}"
.format(repr(function))
)
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 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.
coeffs = _np.empty((2, nl, nl))
for l in degrees:
coeffs[:2, l, :l+1] = _np.random.normal(size=(2, l+1))
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 function.lower() == 'potential':
coeffs /= (gm / r0)
elif function.lower() == 'geoid':
coeffs /= r0
elif function.lower() == 'radial':
for l in degrees:
coeffs[:, l, :l+1] /= (gm * (l + 1) / r0**2)
elif function.lower() == 'total':
for l in degrees:
coeffs[:, l, :l+1] /= (gm / r0**2) * _np.sqrt((l + 1) *
(2 * l + 1))
if lmax > nl - 1:
coeffs = _np.pad(coeffs, ((0, 0), (0, lmax - nl + 1),
(0, lmax - nl + 1)), 'constant')
coeffs[0, 0, 0] = 1.0
coeffs[:, 1, :] = 0.0
clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega,
normalization=normalization.lower(),
csphase=csphase)
return clm
@classmethod
def from_shape(self, shape, rho, gm, nmax=7, lmax=None, lmax_grid=None,
lmax_calc=None, omega=None):
"""
Initialize a class of gravitational potential spherical harmonic
coefficients by calculuting the gravitational potential associatiated
with relief along an interface.
Usage
-----
x = SHGravCoeffs.from_shape(shape, rho, gm, [nmax, lmax, lmax_grid,
lmax_calc, omega])
Returns
-------
x : SHGravCoeffs class instance.
Parameters
----------
shape : SHGrid or SHCoeffs class instance
The shape of the interface, either as an SHGrid or SHCoeffs class
instance. If the input is an SHCoeffs class instance, this will be
expaned on a grid using the optional parameters lmax_grid and
lmax_calc.
rho : int, float, or ndarray, or an SHGrid or SHCoeffs class instance
The density contrast associated with the interface in kg / m3. If
the input is a scalar, the density contrast is constant. If
the input is an SHCoeffs or SHGrid class instance, the density
contrast will vary laterally.
gm : float
The gravitational constant times the mass that is associated with
the gravitational potential coefficients.
nmax : integer, optional, default = 7
The maximum order used in the Taylor-series expansion when
calculating the potential coefficients.
lmax : int, optional, shape.lmax
The maximum spherical harmonic degree of the output spherical
harmonic coefficients.
lmax_grid : int, optional, default = lmax
If shape or rho is of type SHCoeffs, this parameter determines the
maximum spherical harmonic degree that is resolvable when expanded
onto a grid.
lmax_calc : optional, integer, default = lmax
If shape or rho is of type SHCoeffs, this parameter determines the
maximum spherical harmonic degree that will be used when expanded
onto a grid.
omega : float, optional, default = None
The angular rotation rate of the body.
Description
-----------
Initialize an SHGravCoeffs class instance by calculating the spherical
harmonic coefficients of the gravitational potential associated with
the shape of a density interface. The potential is calculated using the
finite-amplitude technique of Wieczorek and Phillips (1998) for a
constant density contrast and Wieczorek (2007) for a density contrast
that varies laterally. The output coefficients are referenced to the
mean radius of shape, and the potential is strictly valid only when it
is evaluated at a radius greater than the maximum radius of shape.
The input shape (and density contrast rho for variable density) can be
either an SHGrid or SHCoeffs class instance. The routine makes direct
use of gridded versions of these quantities, so if the input is of type
SHCoeffs, it will first be expanded onto a grid. This exansion will be
performed on a grid that can resolve degrees up to lmax_grid, with only
the first lmax_calc coefficients being used. The input shape must
correspond to absolute radii as the degree 0 term determines the
reference radius of the coefficients.
As an intermediate step, this routine calculates the spherical harmonic
coefficients of the interface raised to the nth power, i.e.,
(shape-r0)**n, where r0 is the mean radius of shape. If the input shape
is bandlimited to degree L, the resulting function will thus be
bandlimited to degree L*nmax. This subroutine assumes implicitly that
the maximum spherical harmonic degree of the input shape (when
SHCoeffs) or maximum resolvable spherical harmonic degree of shape
(when SHGrid) is greater or equal to this value. If this is not the
case, aliasing will occur. In practice, for accurate results, the
effective bandwidth needs only to be about three times the size of L,
though this should be verified for each application. The effective
bandwidth of shape (when SHCoeffs) can be increased by preprocessing
with the method pad(), or by increaesing the value of lmax_grid (when
SHGrid).
"""
mass = gm / _G.value
if type(shape) is not _SHRealCoeffs and type(shape) is not _DHRealGrid:
raise ValueError('shape must be of type SHRealCoeffs '
'or DHRealGrid. Input type is {:s}'
.format(repr(type(shape))))
if (not issubclass(type(rho), float) and type(rho) is not int
and type(rho) is not _np.ndarray and
type(rho) is not _SHRealCoeffs and
type(rho is not _DHRealGrid)):
raise ValueError('rho must be of type float, int, ndarray, '
'SHRealCoeffs or DHRealGrid. Input type is {:s}'
.format(repr(type(rho))))
if type(shape) is _SHRealCoeffs:
shape = shape.expand(lmax=lmax_grid, lmax_calc=lmax_calc)
if type(rho) is _SHRealCoeffs:
rho = rho.expand(lmax=lmax_grid, lmax_calc=lmax_calc)
if type(rho) is _DHRealGrid:
if shape.lmax != rho.lmax:
raise ValueError('The grids for shape and rho must have the '
'same size. '
'lmax of shape = {:d}, lmax of rho = {:d}'
.format(shape.lmax, rho.lmax))
cilm, d = _CilmPlusRhoHDH(shape.data, nmax, mass, rho.data,
lmax=lmax)
else:
cilm, d = _CilmPlusDH(shape.data, nmax, mass, rho, lmax=lmax)
clm = SHGravRealCoeffs(cilm, gm=gm, r0=d, omega=omega,
normalization='4pi', csphase=1)
return clm
@property
def mass(self):
"""Return the mass of the planet in kg.
"""
return self.gm / _G.value
# ---- Define methods that modify internal variables ----
def set_omega(self, omega):
"""
Set the angular rotation rate of the class instance.
Usage
-----
x.set_omega(omega)
Parameters
----------
omega : float
The angular rotation rate of the body.
"""
self.omega = omega
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 (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, errors=False,
**kwargs):
"""
Save spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format='shtools', header, errors])
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.
errors : bool, optional, default = False
If True, save the errors in the file (for 'shtools' formatted
files only).
**kwargs : keyword argument list, optional for format = 'npy'
Keyword arguments of numpy.save().
Description
-----------
If format='shtools', the coefficients and meta-data will be written to
an ascii formatted file. The first line is an optional user provided
header line, and the following line provides the attributes r0, gm,
omega, and lmax. 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 the errors are to be saved, the format of each line
will be
l, m, coeffs[0, l, m], coeffs[1, l, m], error[0, l, m], error[1, l, m]
If format='npy', the spherical harmonic coefficients (but not the
meta-data nor errors) will be saved to a binary numpy 'npy' file using
numpy.save().
"""
if format is 'shtools':
if errors is True and self.errors is None:
raise ValueError('Can not save errors when then have not been '
'initialized.')
if self.omega is None:
omega = 0.
else:
omega = self.omega
with open(filename, mode='w') as file:
if header is not None:
file.write(header + '\n')
file.write('{:.16e}, {:.16e}, {:.16e}, {:d}\n'.format(
self.r0, self.gm, omega, self.lmax))
for l in range(self.lmax+1):
for m in range(l+1):
if errors is True:
file.write('{:d}, {:d}, {:.16e}, {:.16e}, '
'{:.16e}, {:.16e}\n'
.format(l, m, self.coeffs[0, l, m],
self.coeffs[1, l, m],
self.errors[0, l, m],
self.errors[1, l, m]))
else:
file.write('{:d}, {:d}, {:.16e}, {:.16e}\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 implemented'.format(repr(format)))
def to_array(self, normalization=None, csphase=None, lmax=None):
"""
Return spherical harmonic coefficients (and errors) as a numpy array.
Usage
-----
coeffs, [errors] = x.to_array([normalization, csphase, lmax])
Returns
-------
coeffs : ndarry, shape (2, lmax+1, lmax+1)
numpy ndarray of the spherical harmonic coefficients.
errors : ndarry, shape (2, lmax+1, lmax+1)
numpy ndarray of the errors of the spherical harmonic
coefficients if they are not None.
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.
Description
-----------
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 the errors of the coefficients are set, they will be
output as a separate array.
"""
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)
if self.errors is not None:
errors = _convert(self.errors, normalization_in=self.normalization,
normalization_out=normalization,
csphase_in=self.csphase, csphase_out=csphase,
lmax=lmax)
return coeffs, errors
else:
return coeffs
def copy(self):
"""
Return a deep copy of the class instance.
Usage
-----
copy = x.copy()