/
shmagcoeffs.py
1989 lines (1745 loc) · 83.8 KB
/
shmagcoeffs.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 magnetic 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 .shmaggrid import SHMagGrid as _SHMagGrid
from .shtensor import SHMagTensor as _SHMagTensor
from ..spectralanalysis import spectrum as _spectrum
from ..shio import convert as _convert
from ..shio import shread as _shread
from ..shtools import MakeMagGridDH as _MakeMagGridDH
from ..shtools import MakeMagGradGridDH as _MakeMagGradGridDH
# =============================================================================
# ========= SHMagCoeffs class =========================================
# =============================================================================
class SHMagCoeffs(object):
"""
Spherical harmonic coefficients class for the magnetic potential.
The coefficients of this class (in units of nT) can be initialized using
one of the four constructor methods:
x = SHMagCoeffs.from_array(array, r0)
x = SHMagCoeffs.from_random(powerspectrum, r0)
x = SHMagCoeffs.from_zeros(lmax, r0)
x = SHMagCoeffs.from_file('fname.dat')
The normalization convention of the input coefficents is specified
by the optional normalization and csphase parameters, which take the
following values:
normalization : '4pi', geodesy 4-pi normalized.
: 'ortho', orthonormalized.
: 'schmidt' (default), 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.
r0 : The reference radius of the magnetic potential
coefficients.
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_coeffs() : Set coefficients in-place to specified values.
change_ref() : Return a new class instance referenced to a
different reference radius.
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
magnetic field, the total field, and the magnetic
potential, and return an SHMagGrid class instance.
tensor() : Calculate the 9 components of the magnetic field
tensor and return an SHMagTensor 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 to a file.
copy() : Return a copy of the class instance.
info() : Print a summary of the data stored in the
SHMagCoeffs instance.
"""
def __init__(self):
"""Unused constructor of the super class."""
print('Initialize the class using one of the class methods:\n'
'>>> pyshtools.SHMagCoeffs.from_array\n'
'>>> pyshtools.SHMagCoeffs.from_random\n'
'>>> pyshtools.SHMagCoeffs.from_zeros\n'
'>>> pyshtools.SHMagCoeffs.from_file\n')
# ---- Factory methods ----
@classmethod
def from_array(self, coeffs, r0, errors=None, normalization='schmidt',
csphase=1, lmax=None, copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHMagCoeffs.from_array(array, r0, [errors, normalization, csphase,
lmax, copy])
Returns
-------
x : SHMagCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmaxin+1, lmaxin+1).
The input spherical harmonic coefficients.
r0 : float
The reference radius of the spherical harmonic coefficients.
errors : ndarray, optional, default = None
The uncertainties of the spherical harmonic coefficients.
normalization : str, optional, default = 'schmidt'
'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
-----
The coefficients in the input array are assumed to have units of nT.
"""
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 errors is not None:
clm = SHMagRealCoeffs(coeffs[:, 0:lmax+1, 0:lmax+1], r0=r0,
errors=errors[:, 0:lmax+1, 0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, copy=copy)
else:
clm = SHMagRealCoeffs(coeffs[:, 0:lmax+1, 0:lmax+1], r0=r0,
normalization=normalization.lower(),
csphase=csphase, copy=copy)
return clm
@classmethod
def from_zeros(self, lmax, r0, errors=False, normalization='schmidt',
csphase=1):
"""
Initialize the class with spherical harmonic coefficients set to zero.
Usage
-----
x = SHMagCoeffs.from_zeros(lmax, r0, [errors, normalization, csphase])
Returns
-------
x : SHMagCoeffs class instance.
Parameters
----------
lmax : int
The maximum spherical harmonic degree l of the coefficients.
r0 : float
The reference radius of the spherical harmonic coefficients.
errors : bool, optional, default = False
If True, initialize the attribute errors with zeros.
normalization : str, optional, default = 'schmidt'
'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))
if errors is False:
clm = SHMagRealCoeffs(coeffs, r0=r0,
normalization=normalization.lower(),
csphase=csphase)
else:
clm = SHMagRealCoeffs(coeffs, r0=r0,
errors=_np.zeros((2, lmax + 1, lmax + 1)),
normalization=normalization.lower(),
csphase=csphase)
return clm
@classmethod
def from_file(self, fname, format='shtools', r0=None, lmax=None,
normalization='schmidt', skip=0, header=True, errors=False,
csphase=1, r0_index=0, header_units='m', coeffs_units='nT',
**kwargs):
"""
Initialize the class with spherical harmonic coefficients from a file.
Usage
-----
x = SHMagCoeffs.from_file(filename, [format='shtools', r0, lmax,
normalization, csphase, skip,
header, errors, r0_index,
header_units, coeffs_units])
x = SHMagCoeffs.from_file(filename, format='npy', r0,
[normalization, csphase, **kwargs])
Returns
-------
x : SHMagCoeffs 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.
r0 : float, optional, default = None
The reference radius of the spherical harmonic coefficients.
header_units : str, optional, default = 'm'
The units of r0 in the header line of an shtools formatted file:
'm' or 'km'. If 'km', the value of r0 will be converted to meters.
coeffs_units : str, optional, default = 'nT'
The units of the coefficients read from the file: 'nT or 'T''. If
'T', the coefficients will be converted to nT.
normalization : str, optional, default = 'schmidt'
'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 is
used as the indice to set r0. If header_unit is specified as 'km', the
value of r0 read from the header will be converted to meters. The
coefficients read from the file are assumed to have units of nT. If
coeffs_units is specified as 'T', the coefficients will be converted
to nT.
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().
Notes
-----
The coefficients read from the file are assumed to have units of nT.
"""
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 format == 'shtools':
if r0_index is not None and r0 is not None:
raise ValueError('Can not specify both r0_index and r0')
if header is False and r0 is None:
raise ValueError('If header is False, r0 must be specified.')
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 coeffs_units.lower() not in ('nt', 't'):
raise ValueError("coeffs_units can be only 'T' or 'nT'. Input "
"value is {:s}.".format(repr(coeffs_units)))
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 r0 is None:
raise ValueError('For binary npy files, 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 format.lower() == 'shtools' and header is True:
if r0_index is not None:
r0 = float(header_list[r0_index])
if header_units.lower() == 'km':
r0 *= 1.e3
if coeffs_units.lower() == 't':
coeffs *= 1.e9
if errors is True:
error *= 1.e9
clm = SHMagRealCoeffs(coeffs, r0=r0, errors=error,
normalization=normalization.lower(),
csphase=csphase, header=header_list)
return clm
@classmethod
def from_random(self, power, r0, function='total', lmax=None,
normalization='schmidt', csphase=1, exact_power=False):
"""
Initialize the class of magnetic potential spherical harmonic
coefficients as random variables with a given spectrum.
Usage
-----
x = SHMagCoeffs.from_random(power, r0, [function, lmax, normalization,
csphase, exact_power])
Returns
-------
x : SHMagCoeffs 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.
r0 : float
The reference radius of the spherical harmonic coefficients.
function : str, optional, default = 'potential'
The type of input power spectrum: 'potential' for the magnetic
potential in nT m, 'radial' for the radial magnetic field in nT,
or 'total' for the total magnetic field (Lowes-Mauersberger) in nT.
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 = 'schmidt'
'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
magnetic 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:
r0 for the magnetic potential, (l+1) for the radial magnetic field,
or sqrt((l+1)*(2l+1)). The power spectrum of the random realization can
be fixed exactly to the input spectrum by setting exact_power to True.
Notes
-----
The coefficients stored in the class instance have units of nT.
"""
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', 'radial', 'total'):
raise ValueError(
"function must be of type 'potential', "
"'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 /= r0
elif function.lower() == 'radial':
for l in degrees:
coeffs[:, l, :l+1] /= (l + 1)
elif function.lower() == 'total':
for l in degrees:
coeffs[:, l, :l+1] /= _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] = 0.0
clm = SHMagRealCoeffs(coeffs, r0=r0,
normalization=normalization.lower(),
csphase=csphase)
return clm
# ---- 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 (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 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.')
with open(filename, mode='w') as file:
if header is not None:
file.write(header + '\n')
file.write('{:.16e}, {:d}\n'.format(self.r0, 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()
"""
return _copy.deepcopy(self)
def info(self):
"""
Print a summary of the data stored in the SHMagCoeffs class instance.
Usage
-----
x.info()
"""
print(repr(self))
# -------------------------------------------------------------------------
# Mathematical operators
#
# Operations that involve a change of units are not permitted, such as
# SHMagCoeffs*SHMagCoeffs, SHMagCoeffs/SHMagCoeffs, and
# SHMagCoeffs+SHCoeffs. All operations ignore the errors of the
# coefficients.
# -------------------------------------------------------------------------
def __add__(self, other):
"""
Add two similar sets of magnetic potential coefficients:
self + other.
"""
if isinstance(other, SHMagCoeffs):
if (self.r0 == other.r0 and
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 SHMagCoeffs.from_array(
coeffs, r0=self.r0, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('Addition is permitted only when the two '
'SHMagCoeffs instances have the same kind, '
'normalization, csphase, r0 and lmax.')
else:
raise TypeError('Addition is permitted only for two SHMagCoeffs '
'instances. Type of other is {:s}'
.format(repr(type(other))))
def __radd__(self, other):
"""
Add two similar sets of magnetic potential coefficients:
other + self.
"""
return self.__add__(other)
def __sub__(self, other):
"""
Subtract two similar sets of magnetic potential coefficients:
self - other.
"""
if isinstance(other, SHMagCoeffs):
if (self.r0 == other.r0 and
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 SHMagCoeffs.from_array(
coeffs, r0=self.r0, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('Subtraction is permitted only when the two '
'SHMagCoeffs instances have the same kind, '
'normalization, csphase, r0 and lmax.')
else:
raise TypeError('Subtraction is permitted only for two '
'SHMagCoeffs instances. Type of other is {:s}'
.format(repr(type(other))))
def __rsub__(self, other):
"""
Subtract two similar sets of magnetic potential coefficients:
other - self.
"""
if isinstance(other, SHMagCoeffs):
if (self.r0 == other.r0 and
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 SHMagCoeffs.from_array(
coeffs, r0=self.r0, csphase=self.csphase,
normalization=self.normalization)
else:
raise ValueError('Subtraction is permitted only when the two '
'SHMagCoeffs instances have the same kind, '
'normalization, csphase, r0 and lmax.')
else:
raise TypeError('Subtraction is permitted only for two '
'SHMagCoeffs instances. Type of other is {:s}'
.format(repr(type(other))))
def __mul__(self, other):
"""
Multiply an SHMagCoeffs instance by an SHCoeffs instance or 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 SHMagCoeffs.from_array(
coeffs, r0=self.r0, 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 multiply real magnetic '
'potential coefficients by a complex '
'constant.')
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = self.coeffs[self.mask] * other
return SHMagCoeffs.from_array(
coeffs, r0=self.r0, csphase=self.csphase,
normalization=self.normalization)
else:
raise TypeError('Multiplication of an SHMagCoeffs instance is '
'permitted only with either an SHCoeffs instance '
'or a scalar. '
'Type of other is {:s}'.format(repr(type(other))))
def __rmul__(self, other):
"""
Multiply an SHMagCoeffs instance by an SHCoeffs instance or scalar:
other * self.
"""
return self.__mul__(other)
def __div__(self, other):
"""
Divide an SHMagCoeffs instance by an SHCoeffs instance or 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
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 SHMagCoeffs.from_array(
coeffs, r0=self.r0, 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 divide real magnetic '
'potential coefficients by a complex '
'constant.')
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],
dtype=self.coeffs.dtype)
coeffs[self.mask] = self.coeffs[self.mask] / other
return SHMagCoeffs.from_array(
coeffs, r0=self.r0, csphase=self.csphase,
normalization=self.normalization)
else:
raise TypeError('Division of an SHMagCoeffs instance is '
'permitted only with either an SHCoeffs instance '
'or a scalar. '
'Type of other is {:s}'.format(repr(type(other))))
def __truediv__(self, other):
"""
Divide an SHMagCoeffs instance by an SHCoeffs instance or 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
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 SHMagCoeffs.from_array(
coeffs, r0=self.r0, 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 divide real magnetic '
'potential coefficients by a complex '
'constant.')
coeffs = _np.empty([2, self.lmax+1, self.lmax+1],