-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathspectral_utils.py
2720 lines (2250 loc) · 97.1 KB
/
spectral_utils.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
"""
Interface to the Rayleigh grid and spectral transforms, including:
+ Fourier grid/transforms/derivatives
+ Legendre grid/transforms/derivatives
+ Chebyshev grid/transforms/derivatives
R. Orvedahl May 24, 2021
"""
from __future__ import print_function
import numpy as np
from scipy.linalg.blas import dgemm as DGEMM
from scipy.linalg.blas import zgemm as ZGEMM
import warnings
def ddx_repeated_gridpoints(data, grid, indices, axis=0):
"""
6th order centered finite difference on a non-uniform mesh that contains
repeated grid points. For example, a grid that looks like this
|---x---x---x
x---x---x---x---x
x---x---x---|
where there are repeated grid points at internal boundaries. This appears
when using multiple chebyshev domains; the grid points at the internal
boundaries are repeated.
Args
----
data : ndarray
The data values on the grid.
grid : 1D ndarray of shape (N,)
The grid point values. Each subdomain must contain more than 7 grid points.
indices : 1D array_like
Each element gives the index to the second instance of a repeated grid point, e.g.,
the first repeated grid point occurs at grid[indices[0]] and grid[indices[0]-1].
axis : int, optional
The axis over which to take the derivative.
Returns
-------
dfdx : ndarray
Derivative evaluated on the grid, same shape as input.
"""
grid = np.asarray(grid); data = np.asarray(data)
# swap axis order
data = swap_axis(data, axis, -1)
dfdx = np.zeros_like(data)
# compute derivative in each subdomain
slc = [slice(None)]*len(dfdx.shape)
start = 0
for i in indices:
stop = i
slc[-1] = slice(start,stop)
Ncheck = len(grid[start:stop])
if (Ncheck < 9):
e = "Subdomains must have 9 or more grid points, only found N = {}"
raise ValueError(e.format(Ncheck))
dfdx[tuple(slc)] = ddx(data[tuple(slc)], grid[start:stop], axis=-1)
start = i
slc[-1] = slice(start, None)
dfdx[tuple(slc)] = ddx(data[tuple(slc)], grid[start:], axis=-1)
# restore axis order
dfdx = swap_axis(dfdx, -1, axis)
return dfdx
def ddx(data, grid, axis=0):
"""
6th order centered finite difference on a non-uniform mesh, one-sided
differences on the boundary points. The grid points must be unique.
Args
----
data : ndarray
The data values on the grid.
grid : 1D ndarray of shape (N,)
The grid point values.
axis : int, optional
The axis over which to take the derivative.
Returns
-------
dfdx : ndarray
Derivative evaluated on the grid, same shape as input.
"""
x = np.asarray(grid); f = np.asarray(data)
# swap axis order
f = swap_axis(f, axis, -1)
if (grid[0] < grid[1]):
data_reversed = False
else:
data_reversed = True
x = x[::-1]
f = f[...,::-1]
nx = np.shape(f)[-1]
dfdx = np.zeros_like(f)
# solve the following system for f' using determinants
# f(-3) = f0 + dxm30*f'+dxm30**2*f''/2+dxm30**3*f'''/6+dxm30**4*f''''/24
# f(-2) = f0 + dxm20*f'+dxm20**2*f''/2+dxm20**3*f'''/6+dxm20**4*f''''/24
# f(-1) = f0 + dxm10*f'+dxm10**2*f''/2+dxm10**3*f'''/6+dxm10**4*f''''/24
# f(1) = f0 + dxp10*f'+dxp10**2*f''/2+dxp10**3*f'''/6+dxp10**4*f''''/24
# f(2) = f0 + dxp20*f'+dxp20**2*f''/2+dxp20**3*f'''/6+dxp20**4*f''''/24
# f(3) = f0 + dxp30*f'+dxp30**2*f''/2+dxp30**3*f'''/6+dxp30**4*f''''/24
# dxpj0 = x(j) - x(0); dxmj0 = x(-j) - x(0)
sh2 = np.shape(f)[:-1] + (7,7)
sh = tuple([1]*len(np.shape(f)[:-1])) + (7,)
N = np.zeros(sh2)
for i in range(3,nx-3):
dxm30 = x[i-3] - x[i]; dxm20 = x[i-2] - x[i]; dxm10 = x[i-1] - x[i]
dxp10 = x[i+1] - x[i]; dxp20 = x[i+2] - x[i]; dxp30 = x[i+3] - x[i]
delta = (abs(dxm30)+abs(dxm20)+abs(dxm10)+abs(dxp10)+abs(dxp20)+abs(dxp30))/6.
dxm30 /= delta; dxm20 /= delta; dxm10 /= delta
dxp10 /= delta; dxp20 /= delta; dxp30 /= delta
a = [1., dxm30, dxm30**2, dxm30**3, dxm30**4, dxm30**5, dxm30**6]
N[...,0,:] = np.array(a).reshape(sh)
a = [1., dxm20, dxm20**2, dxm20**3, dxm20**4, dxm20**5, dxm20**6]
N[...,1,:] = np.array(a).reshape(sh)
a = [1., dxm10, dxm10**2, dxm10**3, dxm10**4, dxm10**5, dxm10**6]
N[...,2,:] = np.array(a).reshape(sh)
a = [1., 0, 0 , 0 , 0 , 0 , 0 ]
N[...,3,:] = np.array(a).reshape(sh)
a = [1., dxp10, dxp10**2, dxp10**3, dxp10**4, dxp10**5, dxp10**6]
N[...,4,:] = np.array(a).reshape(sh)
a = [1., dxp20, dxp20**2, dxp20**3, dxp20**4, dxp20**5, dxp20**6]
N[...,5,:] = np.array(a).reshape(sh)
a = [1., dxp30, dxp30**2, dxp30**3, dxp30**4, dxp30**5, dxp30**6]
N[...,6,:] = np.array(a).reshape(sh)
# construct 1st derivative, multiply (num/den) by n!/delta**n for nth derivative
dfdx[...,i] = np.linalg.solve(N, f[...,i-3:i+4])[...,1]/delta
# left/right boundary point
dfdx[...,0] = _one_sided_6th(x[:7], f[...,:7])
dfdx[...,nx-1] = _one_sided_6th(x[-7:], f[...,-7:], right_edge=True)
# first/last interior point
dfdx[...,1] = _one_sided_6th(x[1:8], f[...,1:8])
dfdx[...,nx-2] = _one_sided_6th(x[-8:-1], f[...,-8:-1], right_edge=True)
# second/second to last interior point
dfdx[...,2] = _one_sided_6th(x[2:9], f[...,2:9])
dfdx[...,nx-3] = _one_sided_6th(x[-9:-2], f[...,-9:-2], right_edge=True)
if (data_reversed):
dfdx = dfdx[...,::-1]
# restore axis order
dfdx = swap_axis(dfdx, -1, axis)
return dfdx
def _one_sided_6th(xx, ff, right_edge=False):
"""
One sided 6th order finite difference on a non-uniform mesh over the last axis.
Args
----
xx : (7,) ndarray
The three grid points, the left edge is assumed to be the boundary.
ff : (...,7) ndarray
The data values on the grid.
right_edge : bool, optional
Calculate the one sided difference on the right boundary.
Returns
-------
dfdx : (...,1) ndarray
Derivative evaluated on the left/right boundary, if f is shape tuple + (7,)
then dfdx will have shape tuple.
"""
xx = np.asarray(xx); ff = np.asarray(ff)
if (right_edge):
xx = xx[::-1]; ff = ff[...,::-1]
# generate matrix such that A*f' = f
# where the rows of A are taylor expansions:
# f0 = f0
# f1 = f0 + dx10*f' + dx10**2*f''/2 + dx10**3*f'''/6 + dx10**4*f''''/24 + ...
# f2 = f0 + dx20*f' + dx20**2*f''/2 + dx20**3*f'''/6 + dx20**4*f''''/24 + ...
# f3 = f0 + dx30*f' + dx30**2*f''/2 + dx30**3*f'''/6 + dx30**4*f''''/24 + ...
# f4 = f0 + dx40*f' + dx40**2*f''/2 + dx40**3*f'''/6 + dx40**4*f''''/24 + ...
# f5 = f0 + dx50*f' + dx50**2*f''/2 + dx50**3*f'''/6 + dx50**4*f''''/24 + ...
# f6 = f0 + dx60*f' + dx60**2*f''/2 + dx60**3*f'''/6 + dx60**4*f''''/24 + ...
# rewrite it so dx --> dx/delta for matrix conditioning
# this makes the unknown vector f^(n)*delta**n/n!
dx10 = xx[1] - xx[0]; dx20 = xx[2] - xx[0]; dx30 = xx[3] - xx[0]
dx40 = xx[4] - xx[0]; dx50 = xx[5] - xx[0]; dx60 = xx[6] - xx[0]
delta = (abs(dx10) + abs(dx20) + abs(dx30) + abs(dx40) + abs(dx50) + abs(dx60))/6.
dx10 /= delta; dx20 /= delta; dx30 /= delta; dx40 /= delta; dx50 /= delta; dx60 /= delta
sh2 = np.shape(ff)[:-1] + (7,7)
N = np.zeros(sh2)
sh = tuple([1]*len(np.shape(ff)[:-1])) + (7,)
N[...,0,:] = np.array([1., 0., 0., 0., 0., 0., 0. ]).reshape(sh)
N[...,1,:] = np.array([1., dx10, dx10**2, dx10**3, dx10**4, dx10**5, dx10**6]).reshape(sh)
N[...,2,:] = np.array([1., dx20, dx20**2, dx20**3, dx20**4, dx20**5, dx20**6]).reshape(sh)
N[...,3,:] = np.array([1., dx30, dx30**2, dx30**3, dx30**4, dx30**5, dx30**6]).reshape(sh)
N[...,4,:] = np.array([1., dx40, dx40**2, dx40**3, dx40**4, dx40**5, dx40**6]).reshape(sh)
N[...,5,:] = np.array([1., dx50, dx50**2, dx50**3, dx50**4, dx50**5, dx50**6]).reshape(sh)
N[...,6,:] = np.array([1., dx60, dx60**2, dx60**3, dx60**4, dx60**5, dx60**6]).reshape(sh)
# fNprime = dn_f_dxn[N] * N! / delta**N where N specifies what derivative
f1prime = np.linalg.solve(N, ff)[...,1]/delta
return f1prime
def _choose_gemm(data, tol=1e-15):
"""
Determine correct BLAS GEMM routine to use: real vs complex.
Args
----
data : array_like
The input data.
tol : float, optional
Choose tolerance below which the imaginary part is considered zero.
Returns
-------
gemm : scipy function
Reference to either dgemm or zgemm from scipy.linalg.blas
is_complex : bool
Describes the chosen scipy routine as either real or complex.
"""
data = np.asarray(data)
# choose based on imaginary part of all data
if (np.any(np.abs(np.imag(data)) > tol)):
is_complex = True
gemm = ZGEMM
else:
is_complex = False
gemm = DGEMM
return gemm, is_complex
def swap_axis(array, axis0, axis1):
"""
Swap axes of array, other axes remain untouched.
Args
----
array : ndarray
The input array.
axis0 : int
The original axis that will be swapped.
axis1 : int
The final destination axis.
Returns
-------
array : ndarray
The input array with the swapped axes.
Examples
--------
>>> B.shape
(2,3,4,5,6)
>>> A = swap_axis(B, -1, 1) # swap the 2nd axis with the last axis
>>> A.shape
(2,6,4,5,3)
>>> A = swap_axis(A, 1, -1) # undo the previous swap
>>> A.shape
(2,3,4,5,6)
"""
array = np.asarray(array)
dim = len(np.shape(array))
axis0 = pos_axis(axis0, dim)
axis1 = pos_axis(axis1, dim)
if (axis0 == axis1): return array
if (dim > 1): # swap only needed if larger than 1D
return np.swapaxes(array, axis0, axis1)
else:
return array
def pos_axis(axis, dim):
"""
Convert axis to a positive integer into array of size dim.
Args
----
axis : int
The axis to verify.
dim : int
Number of dimensions where axis is valid.
Returns
-------
axis : int
The positive integer reference to the given axis.
Example
-------
>>> x.shape
(128,64,8)
>>> dim = len(x.shape)
>>> axis = -2
>>>
>>> Axis = pos_axis(axis, dim)
>>> Axis
1
"""
try:
paxis = np.arange(dim)[axis]
except:
if (axis > 0):
raise ValueError("axis must be < dim, axis={}, dim={}".format(axis, dim))
else:
raise ValueError("|axis| must be <= dim, axis={}, dim={}".format(axis, dim))
return paxis
def grid_size(N, spectral, dealias=1.0):
"""
Find size of physical and spectral grids with dealiasing.
Args
----
N : int
Number of grid points or coefficients.
spectral : bool
Does the incoming N refer to physical space (Ngrid) or spectral (Npoly_max).
dealias : float, optional
Amount to dealias: N_grid = dealias*(N_poly_max + 1).
Returns
-------
Ngrid : int
Number of physical space grid points.
Npoly_max : int
Maximum degree in polynomial expansion.
"""
if (spectral):
Npoly_max = N
Ngrid = int(np.floor(dealias*(Npoly_max+1)))
else:
Ngrid = N
Npoly_max = int(np.ceil(Ngrid/dealias - 1))
return Ngrid, Npoly_max
class Fourier:
"""
Handle real data on a Fourier grid, i.e., longitude/phi grid.
This is a stand alone class meant to be used for data where only operations
in the longitude direction are required, e.q., phi derivative or FFT with no
Legendre transform. For data that requires a transform in both longitude and
latitude, the SHT class is more appropriate.
This Fourier class can do transforms and derivatives along
any axis of the real data, but keeps all modes up to the Nyquist frequency.
This behavior is different compared to a full spherical harmonic transform,
which applies a triangular truncation of the azimuthal wavenumbers (see SHT).
Attributes
----------
nphi : integer
Physical space grid resolution. This can also be accessed as n_phi.
phi : ndarray (nphi,)
The longitude grid points.
dphi : float
The grid spacing.
mvals : ndarray (nphi/2 + 1,)
The angular frequencies, also accessed as angular_freq.
Methods
-------
to_spectral(data, axis=0, window=None)
Transform to spectral space along the given axis. A window function can be
applied in physical space before doing the transform by setting the window
to a ndarray of shape (nphi,).
to_physical(data, axis=0)
Transform to physical space along the given axis.
d_dphi(data, axis=0, physical=True)
Compute a derivative with respect to phi along the given axis. Data is assumed
to be in physical space (physical=True).
"""
def __init__(self, N):
"""
Initialize the Fourier grid and FFT (assumes real data).
Args
----
N : int
Number of physical space grid points.
"""
self.N = N
self.x = self._grid()
self.dx = np.mean(self.x[1:]-self.x[:-1])
# alias
self.dphi = self.dx
self.phi = self.x
self.nphi = self.n_phi = self.N
# compute frequencies
self.freq = self._frequencies()
self.low_freq = self.freq.min()
self.high_freq = self.freq.max()
self.angular_freq = 2*np.pi*self.freq
self.mvals = self.angular_freq
def _frequencies(self):
"""
Calculate frequencies on the Fourier grid.
Returns
-------
freq : 1D array
Array of positive frequencies.
"""
freq = np.fft.fftfreq(self.N, d=self.dx) # all frequencies: positive & negative
freq = np.abs(freq[0:int(self.N/2)+1]) # only keep positive frequencies
return freq
def _grid(self):
"""
Calculate Fourier grid points in [0,2pi).
Returns
-------
x : 1D array
Physical space grid points.
"""
self.period = 2.*np.pi
dphi = self.period/self.N
xgrid = dphi*np.arange(self.N)
return xgrid
def to_spectral(self, data_in, axis=0, window=None):
"""
FFT from physical space to spectral space.
Args
----
data_in : ndarray
Input data array of real values in physical space.
axis : int, optional
The axis along which the FFT will be taken.
window : 1D array, optional
Apply a window defined in physical space before doing the FFT.
Returns
-------
data_out : ndarray
Complex Fourier coefficients.
"""
data_in = np.asarray(data_in)
shp = np.shape(data_in); dim = len(shp)
axis = pos_axis(axis, dim)
if (shp[axis] != self.N):
e = "FFT expected length={} along axis={}, found N={}"
raise ValueError(e.format(self.N, axis, shp[axis]))
if (window is None): # build window of 1.0 if not supplied
window = np.ones((self.N))
elif (np.shape(window)[0] != self.N):
e = "FFT window length={}, expected={}"
raise ValueError(e.format(np.shape(window)[0], self.N))
if (len(np.shape(window)) > 1): raise ValueError("FFT window must be 1D")
# reshape window for compatibility with incoming data
nshp = [1]*dim; nshp[axis] = -1; nshp = tuple(nshp)
window = np.reshape(window, nshp)
norm = 2./self.N # two because we neglect negative freqs
data_out = norm*np.fft.rfft(data_in*window, axis=axis)
return data_out
def to_physical(self, data_in, axis=0):
"""
FFT from spectral space to physical space.
Args
----
data_in : ndarray
Input data array of complex values in spectral space.
axis : int, optional
The axis along which the FFT will be taken.
Returns
-------
data_out : ndarray
Array of physical space values, all real.
"""
data_in = np.asarray(data_in)
shp = np.shape(data_in); dim = len(shp)
axis = pos_axis(axis, dim)
# determine size of physical space for normalization
Nm = shp[axis]
if (Nm % 2 == 0):
npts = 2*Nm - 1
else:
npts = 2*Nm - 2
if (shp[axis] != self.freq.shape[0]):
e = "FFT expected length={} along axis={}, found N={}"
raise ValueError(e.format(self.freq.shape[0], axis, shp[axis]))
norm = 2./npts
data_out = np.fft.irfft(data_in/norm, axis=axis)
# throw out the imaginary part, since data is assumed real
data_out = data_out.real
return data_out
def d_dphi(self, data_in, axis=0, physical=True):
"""
Compute a derivative with respect to phi/longitude.
Args
----
data_in : ndarray
Input data array in either physical or spectral space.
axis : int, optional
Axis along which the derivative will be computed.
physical : bool, optional
Specify the incoming data as being in physical space or spectral. The
data will be transformed to spectral space (if necessary) to compute
the derivative.
Returns
-------
data_out : ndarray
Output data containing d/dphi, in the same space as incoming data. If
incoming data was in physical space, the derivative will also be in
physical space.
"""
data_in = np.asarray(data_in)
shp = np.shape(data_in); dim = len(shp)
axis = pos_axis(axis, dim)
if (physical):
if (self.N != shp[axis]):
e = "d_dphi shape error: expected N={}, found={}"
raise ValueError(e.format(np.shape(self.freq)[0], shp[axis]))
else:
if (np.shape(self.freq)[0] != shp[axis]):
e = "d_dphi shape error: expected N={}, found={}"
raise ValueError(e.format(np.shape(self.freq)[0], shp[axis]))
if (physical): # transform to spectral space first, if necessary
data_in = self.to_spectral(data_in, axis=axis)
nshp = [1]*dim; nshp[axis] = -1; nshp = tuple(nshp)
freq = np.reshape(self.freq, nshp)
# multiply by 2*pi*i to compute derivative
data_out = 2*np.pi*1j*freq*data_in
if (physical): # transform back to incoming space
data_out = self.to_physical(data_out, axis=axis)
return data_out
def legendre_grid(Npts, quad=False):
"""
Calculate the Legendre grid points ordered as x[i] < x[i+1] with x in (-1,1).
Args
----
Npts : int
Number of grid points.
quad : bool, optional
Return arrays using quad precision, default is double.
Returns
-------
x : (Npts,) ndarray
The Legendre grid points.
w : (Npts,) ndarray
The Legendre integration weights.
"""
x = np.zeros((Npts), dtype=np.float128); w = np.zeros((Npts), dtype=np.float128)
midpoint = np.asarray(0.0, dtype=np.float128)
scaling = np.asarray(1.0, dtype=np.float128)
n_roots = int((Npts + 1)/2)
eps = np.asarray(3.e-15, dtype=np.float128)
# this is a Newton-Rhapson find for the roots
for i in range(n_roots):
ith_root = np.asarray(np.cos(np.pi*(i+0.75)/(Npts+0.5)), dtype=np.float128)
converged = False; iters = 0
while (not converged):
pn, deriv_pn = _evaluate_Pl(ith_root, Npts)
new_guess = ith_root - pn/deriv_pn
delta = np.abs(ith_root - new_guess)
ith_root = new_guess
if (delta <= eps):
converged = True
x[i] = midpoint - scaling*ith_root
x[Npts-1-i] = midpoint + scaling*ith_root
w[i] = 2.*scaling/((1.-ith_root*ith_root)*deriv_pn*deriv_pn)
w[Npts-1-i] = w[i]
iters += 1
if (not quad): # return in double precision
x = np.asarray(x, dtype=np.float64)
w = np.asarray(w, dtype=np.float64)
return x, w
def _evaluate_Pl(x, n):
"""
Evaluate n-th Legendre polynomial at the given grid point:
P_{n+1} = (2*n+1)*x/(n+1)*P_n - n/(n+1)*P_n-1
P_{m} = ( (2*m-1)*x*P_{m-1} - (m-1)*P_{m-2} ) /m
Args
----
x : float or (N,) ndarray
The evaluation points.
n : int
The order of the Legendre function.
Returns
-------
pn : float or (N,) ndarray
Legendre function evaluated at x.
deriv_pn : float or (N,) ndarray
Derivative of the Legendre function evaluated at x.
"""
x = np.asarray(x, dtype=np.float128)
if (len(np.shape(x)) > 0): # x is array
length = len(x)
else:
length = 1 # x is scalar
pn_minus1 = np.asarray(0.0, dtype=np.float128)
pn = np.asarray(1.0, dtype=np.float128)
# use recursion relation
for j in range(n):
pn_minus2 = pn_minus1
pn_minus1 = pn
pn = ((2.*j + 1.)*x*pn_minus1 - j*pn_minus2)/(j+1.)
# get derivative
deriv_pn = n*(x*pn-pn_minus1)/(x*x - 1.)
return pn, deriv_pn
def _compute_Pl(x, lmax):
"""
Compute array of modified associated Legendre functions for m=0. The computed
values include the spherical harmonic normalization:
Y_l^m = A_l^m * P_l^m(x) * exp(i*m*phi)
This routine computes A_l^m*P_l^m(x) for all available values of x and l, but only m=0.
Args
----
x : (Nth,) ndarray
The Legendre grid points.
lmax : int
The maximum order of the Legendre polynomials that will be included.
Returns
-------
Pl : (Nth, lmax+1) ndarray
The l-th Legendre polynomial evaluated at x[i].
"""
x = np.asarray(x, dtype=np.float128)
n = np.shape(x)[0]
# compute in "quad" precision...it will actually be closer to 80 bit
Pl = np.zeros((n,lmax+1), dtype=np.float128)
mv = 0 # azimuthal wavenumber
# start with the l=m & l=m+1 pieces
# compute factorial ratio = sqrt[ (2m)! / 4**m / m! / m!] for m=0
ratio = np.asarray(1.0, dtype=np.float128)
amp = np.sqrt((mv+0.5)/(2.*np.pi))
amp *= ratio
tmp = 1. - x[:]*x[:]
if (mv%2 == 1):
Pl[:,mv] = -amp*tmp**(mv/2+0.5) # odd m
else:
Pl[:,mv] = amp*tmp**(mv/2) # even m
# l=m+1 part
if (mv < lmax):
Pl[:,mv+1] = Pl[:,mv]*x[:]*np.sqrt(2.*mv+3)
# l>m+1 part
for l in range(mv+2,lmax+1):
amp = np.sqrt( ((l-1)**2 - mv*mv) / (4.*(l-1)**2 - 1.) )
amp2 = np.sqrt( (4.*l*l-1.) / (l*l-mv*mv) )
tmp = Pl[:,l-1]*x[:] - amp*Pl[:,l-2]
Pl[:,l] = tmp*amp2
# store in double precision
Pl = np.asarray(Pl, dtype=np.float64)
return Pl
class Legendre:
"""
Handle data on a Legendre grid, i.e., latitude/theta grid.
This is a stand alone class meant to be used for data where only operations
in the latitude direction are required, e.q., theta derivative or Legendre
transform with no FFT. For data that requires a transform in both longitude
and latitude, the SHT class is more appropriate.
This Legendre class can do transforms and derivatives along
any axis of the real/complex data. The data is decomposed as
.. math::
F(x) = \\sum C_l A_l^{m=0} P_l^{m=0}(x)
where :math:`P_l^m` are the associated Legendre functions for :math:`m=0` and
:math:`A_l^m` are the Spherical harmonic normalization coefficients.
This is a different expansion than what is used for a full spherical harmonic
expansion, which includes nonzero values of m and applies a triangular truncation
to the azimuthal modes (see SHT).
Attributes
----------
nth : integer
Physical space grid resolution. This can also be accessed as ntheta or n_theta.
lmax : integer
Maximum polynomial degree in spectral space. This can also be accessed as l_max.
nl : integer
Number of polynomials in spectral space. This can also be accessed as nell or n_l.
theta : ndarray (nth,)
The co-latitude grid points.
costh : ndarray (nth,)
The cosine of the co-latitude points. This can also be accessed as costheta.
sinth : ndarray (nth,)
The sine of the co-latitude points. This can also be accessed as sintheta.
Methods
-------
to_spectral(data, axis=0)
Transform to spectral space along the given axis.
to_physical(data, axis=0)
Transform to physical space along the given axis.
d_dtheta(data, axis=0, physical=True)
Compute a derivative with respect to theta along the given axis. Data is assumed
to be in physical space (physical=True).
"""
def __init__(self, N, spectral=False, dealias=1.5, dgemm_tol=1e-14):
"""
Initialize the Legendre grid and transform.
Args
----
N : int
Resolution of the theta grid.
spectral : bool, optional
Does N refer to physical space or spectral space. If spectral=True,
N would be the maximum polynomial degree (l_max). The default
is that N refers to the physical space resolution (N_theta).
dealias : float, optional
Amount to dealias: N_theta = dealias*(l_max + 1).
dgemm_tol : float, optional
If the data has any imaginary part with magnitude above this tolerance, then
the complex BLAS routine will be used.
"""
self.nth, self.lmax = grid_size(N, spectral, dealias)
self.nell = self.lmax + 1
self.dealias = dealias
self.parity = False
self.dgemm_tol = dgemm_tol
if (self.nth % 2 == 1):
e = "Theta grid must have even number of grid points, found = {}"
raise ValueError(e.format(self.nth))
# generate grid, weights, and Pl array
_x, _w = legendre_grid(self.nth, quad=True)
self.x = np.zeros((self.nth), dtype=np.float64)
self.w = np.zeros((self.nth), dtype=np.float64)
self.x[:] = _x[:]
self.w[:] = _w[:]
# build array of P_l(x)
self.Pl = _compute_Pl(_x, self.lmax) # (nth,nl)
# array for transforming to spectral
self.iPl = np.transpose(2*np.pi*np.reshape(self.w, (self.nth,1))*self.Pl) # (nl,nth)
# alias
self.ntheta = self.nth
self.n_theta = self.ntheta
self.l_max = self.lmax
self.nl = self.n_l = self.nell
self.sinth = np.sqrt(1.- self.x*self.x)
self.costh = self.x
self.theta = np.arccos(self.costh)
self.costheta = self.costh
self.sintheta = self.sinth
def to_spectral(self, data_in, axis=0):
"""
Legendre transform from physical space to spectral space.
Args
----
data_in : ndarray
Input data to be transformed.
axis : int, optional
The axis over which the transform will take place.
Returns
-------
data_out : ndarray
Transformed data, same shape as input, except along the transformed axis.
"""
data_in = np.asarray(data_in)
shp = np.shape(data_in); dim = len(shp)
axis = pos_axis(axis, dim)
if (shp[axis] != self.nth):
e = "Legendre transform expected length={} along axis={}, found N={}"
raise ValueError(e.format(self.nth, axis, shp[axis]))
# make the transform axis first
transform_axis = 0
data_in = swap_axis(data_in, axis, transform_axis)
# perform the transform with calls to BLAS
alpha = 1.0; beta = 0.0
shape = list(data_in.shape); shape[transform_axis] = self.lmax+1
GEMM, is_complex = _choose_gemm(data_in, tol=self.dgemm_tol)
# (nl,nth) * (nth,...)
data_out = GEMM(alpha=alpha, beta=beta,
trans_a=0, trans_b=0,
a=self.iPl, b=data_in[...])
data_out = np.reshape(data_out, tuple(shape), order='A')
# restore axis order
data_out = swap_axis(data_out, transform_axis, axis)
return data_out
def to_physical(self, data_in, axis=0):
"""
Legendre transform from spectral space to physical space.
Args
----
data_in : ndarray
Input data to be transformed.
axis : int, optional
The axis over which the transform will take place.
Returns
-------
data_out : ndarray
Transformed data, same shape as input, except along the transformed axis.
"""
data_in = np.asarray(data_in)
shp = np.shape(data_in); dim = len(shp)
axis = pos_axis(axis, dim)
if (shp[axis] != self.lmax+1):
e = "Legendre transform expected length={} along axis={}, found N={}"
raise ValueError(e.format(self.nth, axis, shp[axis]))
# make the transform axis first
transform_axis = 0
data_in = swap_axis(data_in, axis, transform_axis)
# perform the transform with calls to BLAS
alpha = 1.0; beta = 0.0
shape = list(data_in.shape); shape[transform_axis] = self.nth
GEMM, is_complex = _choose_gemm(data_in, tol=self.dgemm_tol)
# (nth,nl) * (nl,...)
data_out = GEMM(alpha=alpha, beta=beta,
trans_a=0, trans_b=0,
a=self.Pl, b=data_in[...])
data_out = np.reshape(data_out, tuple(shape), order='A')
# restore axis order
data_out = swap_axis(data_out, transform_axis, axis)
return data_out
def d_dtheta(self, data_in, axis=0, physical=True):
"""
Compute derivative with respect to theta.
Args
----
data_in : ndarray
Input data array.
axis : int, optional
The axis over which the derivative will take place.
physical : bool, optional
Specify the incoming data as being in physical space or spectral. The
data will be transformed to spectral space (if necessary) to compute
the derivative.
Returns
-------
data_out : ndarray
Output data containing d/dtheta, in the same space as incoming data. If
incoming data was in physical space, the derivative will also be in
physical space.
"""
data_in = np.asarray(data_in)
shp = np.shape(data_in); dim = len(shp)
axis = pos_axis(axis, dim)
if (physical):
if (shp[axis] != (self.nth)):
e = "d_dtheta expected length={} along axis={}, found N={}"
raise ValueError(e.format(self.nth, axis, shp[axis]))
else:
if (shp[axis] != (self.lmax+1)):
e = "d_dtheta expected length={} along axis={}, found N={}"
raise ValueError(e.format(self.lmax+1, axis, shp[axis]))
# make the d/dx axis first
transform_axis = 0
data_in = swap_axis(data_in, axis, transform_axis)
if (physical): # go to spectral space if necessary
data_in = self.to_spectral(data_in, axis=transform_axis)
# compute the derivative: sin(th)*dF/dth with m=0
# sin(th)*dP_l^m/dth = l*D_{l+1}^m*P_{l+1}^m - (l+1)*D_l^m*P_{l-1}^m
# where P_l^m includes the A_l^m normalization of the spherical harmonics
# and D_l^m = sqrt[ ((l-m)*(l+m)) / ((2l-1)*(2l+1)) ]
Dl0 = np.zeros((self.lmax+1))
for l in range(1,self.lmax+1):
den = 4.*l*l-1.
Dl0[l] = l/np.sqrt(den)
shape = list(data_in.shape); shape[transform_axis] = self.lmax+1
data_out = np.zeros(tuple(shape), dtype=data_in.dtype)
# l=0 component
data_out[0,...] = -data_in[1,...]*2*Dl0[1]
for l in range(1,self.lmax): # interior l values
data_out[l,...] = -(l+2)*Dl0[l+1]*data_in[l+1,...] + (l-1)*Dl0[l]*data_in[l-1,...]
# l=lmax component
data_out[self.lmax,...] = (self.lmax-1)*Dl0[self.lmax]*data_in[self.lmax-1,...]
# convert back to physical space
data_out = self.to_physical(data_out, axis=transform_axis)
# undo the sin(th) part in physical space
nshp = [1]*len(data_out.shape); nshp[transform_axis] = -1; nshp = tuple(nshp)
sinth = np.reshape(self.sinth, nshp)
data_out /= sinth
if (not physical): # go back to spectral space if necessary
data_out = self.to_spectral(data_out, axis=transform_axis)
# restore axis order
data_out = swap_axis(data_out, transform_axis, axis)
return data_out
def chebyshev_zeros(Npts, reverse=False, quad=False):