-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpsd_functions.py
1419 lines (1131 loc) · 42.4 KB
/
psd_functions.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
import numpy as np
from netCDF4 import Dataset
import os,sys,time
from scipy.fftpack import fft, ifft, fftn, ifftn
from scipy.signal import periodogram, hamming, tukey
import scipy.stats as stats
import matplotlib.pyplot as plt
import multiprocessing as mp
def find_time(starttime,endtime,nd):
startday = int(starttime[6:8])
startmon = int(starttime[4:6])
startyear = int(starttime[0:4])
endday = int(endtime[6:8])
endmon = int(endtime[4:6])
endyear = int(endtime[0:4])
ii = 1
iday = startday
imon = startmon
iyear = startyear
itime = iyear * 10000 + imon * 100 + iday
idaymax = [31,28,31,30,31,30,31,31,30,31,30,31]
idays = np.array([iday])
imons = np.array([imon])
iyears = np.array([iyear])
if (int(endtime) - int(starttime) >0 ):
while( itime < endyear * 10000 + endmon * 100 + endday ):
iday = iday + nd
if (iday > idaymax[imon-1]):
iday = iday - idaymax[imon-1]
imon = imon + 1
if (imon > 12):
imon = 1
iyear = iyear + 1
itime = iyear * 10000 + imon * 100 + iday
idays = np.append(idays,iday)
imons = np.append(imons,imon)
iyears = np.append(iyears,iyear)
return iyears,imons,idays
def find_kindex(depth,deptht,depthw):
"""
Find the k index of a given depth
"""
kdiff = (deptht - depth)
kt = np.where( np.abs(kdiff) == np.min(np.abs(kdiff)) )[0]
kdiff = (depthw - depth)
kw = np.where( np.abs(kdiff) == np.min(np.abs(kdiff)) )[0]
return kt.max(),kw.max()
def calculate_rhines_scale(urms,mean_lat):
"""
"""
b = 2. * 7.2921150 * 1e-5 * np.cos( np.pi/180. * mean_lat ) / (6371.0*1000)
r = 2 * np.pi * np.sqrt( urms / b )
return r
def set_region(region,tlon,tlat):
info = {}
info['region'] = region
## Jet in double-gyre run
if (region == 'gyre-jet'):
lon0 = 0
lon1 = 16
lat0 = 19
lat1 = 31
elif (region == 'gyre-ext'):
lon0 = 15
lon1 = 40
lat0 = 19
lat1 = 31
elif (region == 'gyre-global'):
lon0 = 0
lon1 = 43
lat0 = 5
lat1 = 48
## Jet in Rob's MITgcm run
elif (region == 'MITgcm-jet'):
lon0 = 1.5e5
lon1 = 1.125e6
lat0 = 1.5e6
lat1 = 2.25e6
elif (region == 'MITgcm-down'):
lon0 = 200*7500
lon1 = 350*7500
lat0 = 1.5e6
lat1 = 2.25e6
## Regions on in the real world
## ACC
elif (region == 'acc-full'):
lon0 = 30.
lon1 = 70.
lat0 = -45
lat1 = -35
## same region as Scott & Wang JPO,2005
elif (region == 'acc-scott'):
lon0 = -128
lon1 = -112
lat0 = -65
lat1 = -49
elif (region == 'south-pacific1'):
lon0 = -160
lon1 = -100
lat0 = -65
lat1 = -47
elif (region == 'south-pacific2'):
lon0 = -175
lon1 = -80
lat0 = -68
lat1 = -47
## Agulhas retroflection
elif (region == 'agulhas-retro'):
lon0 = 25
lon1 = 68
lat0 = -45.5
lat1 = -37
elif (region == 'agulhas-rings-big'):
lon0 = -10
lon1 = 60
lat0 = -50
lat1 = 10
rot = -20
elif (region == 'agulhas-current-big'):
lon0 = -5
lon1 = 67
lat0 = -50
lat1 = -10
elif (region == 'agulhas-retro-2'):
lon0 = 14
lon1 = 68
lat0 = -54
lat1 = -45.5
## Gulf Stream
elif (region[0:10] == 'gulfstream'):
lat0 = 36.3
lat1 = 42.
if (region == 'gulfstream-full'):
lon0 = -63.5
lon1 = -34.
elif (region == 'gulfstream-up'):
lon0 = -68.5
lon1 = -40.
elif (region == 'gulfstream-down'):
lon0 = -68.5
lon1 = -50.
else:
print ' region ',region,' is not a recognised part of the Gulf Stream!'
sys.exit()
## Kuroshio
elif (region[0:8] == 'kuroshio'):
lat0 = 30.0
lat1 = 40.0
if (region == 'kuroshio-full'):
lon0 = 141.5
lon1 = -176.
## downstream
elif (region == 'kuroshio-down'):
lon0 = 163.
lon1 = -176 #-165.
## upstream
elif (region == 'kuroshio-up'):
lon0 = 141.5
lon1 = 163.
elif (region == 'kuroshio-full2'):
lon0 = 149.
lon1 = -176.
lat0 = 28.0
lat1 = 43.0
elif (region == 'kuroshio-full3'):
lon0 = 145.
lon1 = 180.
lat0 = 28.0
lat1 = 43.0
elif (region == 'north-pacific-1'):
lon0 = 141.5
lon1 = -176.
lat0 = 20.0
lat1 = 32.5
elif (region == 'argentine'):
lon0 = -52.75
lon1 = -30.
lat0 = -53.
lat1 = -40.
elif (region == 'east-pacific-1'):
lon0 = -121.5
lon1 = -82.5
lat0 = -46.4
lat1 = -25.
else:
print ' Region: ',region,' is not a region I recognise! '
print ' If you have not typed anything stupid (which the esteemed Dr Kjellsson often does) '
print ' you should add the lon,lats for the region to the function set_region '
sys.exit()
info['lon0'] = lon0
info['lon1'] = lon1
info['lat0'] = lat0
info['lat1'] = lat1
##
## We have the lon0, lon1, lat0, lat1 of the region
##
## Find i,j indices for the region
##
#if (grid_type == 'll'):
if 1:
## e.g. if lon1 = 160E and lon0 = 160W
## then we convert lon to [0,360] to make lon monotonic
if (lon1 < lon0):
tmp_lon1 = lon1+360
tlon = np.where(tlon<0,tlon+360,tlon)
else:
tmp_lon1 = lon1
## find all indices in [lon0,lon1],[lat0,lat1]
ind = np.where( (tlon>=lon0) & (tlon<=tmp_lon1) & (tlat>=lat0) & (tlat<=lat1) )
## if we converted to [0,360] before, we convert back now
if (lon1 < lon0):
tlon = np.where(tlon>180,tlon-360,tlon)
## we should be able to select a subdomain if the grid is x-y rather than lon-lat
## I think this is common for idealised MITgcm runs?
## In that case, maybe the user can set the x0, x1, y0, y1 variables here?
#elif (grid_type == 'xy'):
# ind = np.where( (tlon >= lon0) & (tlon <=lon1) & (tlat >= lat0) & (tlat <=lat1) )
## ind[1] has i indices, and ind[0] has j indices
i_ind = ind[1]
j_ind = ind[0]
## pick i0,i1,j0,j1 as min/max of i and j arrays
## On a wonky grid like e.g. NEMO tripolar grid,
## this may mean that we include places where lon < lon0
i0 = i_ind.min()
i1 = i_ind.max()
j0 = j_ind.min()
j1 = j_ind.max()
info['i0'] = i0
info['i1'] = i1
info['j0'] = j0
info['j1'] = j1
return info
def set_mitgcm_rob_grid(ufile):
"""
"""
print ufile
ncu = Dataset(ufile,'r')
xx = ncu.variables['X'][:]
yy = ncu.variables['Y'][:]
lon = xx
lat = yy
ulon, ulat = np.meshgrid(lon,lat)
vlon, vlat = np.meshgrid(lon,lat)
tlon, tlat = np.meshgrid(lon,lat)
ncu.close()
return ulon,ulat
def read_mitgcm_rob(ufile,tfile,i0,i1,j0,j1,step0=0,step1=1,lw=False):
"""
"""
print ufile
ncu = Dataset(ufile,'r')
print tfile
nct = Dataset(tfile,'r')
xx = ncu.variables['X'][i0:i1]
yy = ncu.variables['Y'][j0:j1]
ulon, ulat = np.meshgrid(xx,yy)
vlon, vlat = np.meshgrid(xx,yy)
tlon, tlat = np.meshgrid(xx,yy)
utmp = ncu.variables['UVEL'][step0:step1,:,j0:j1,i0:i1+1]
uvel_full = 0.5 * (utmp[:,:,:,1:] + utmp[:,:,:,0:-1])
vtmp = ncu.variables['VVEL'][step0:step1,:,j0:j1+1,i0:i1]
vvel_full = 0.5 * (vtmp[:,:,1:,:] + vtmp[:,:,0:-1,:])
etan_full = ncu.variables['ETAN'][step0:step1,:,j0:j1,i0:i1]
dzt = np.ones(uvel_full[0,:,:,:].shape) * 3000.
for s in range(step0,step1):
if (s == step0):
taux_full = nct.variables['taux'][:,j0:j1,i0:i1]
tauy_full = taux_full * 0.
else:
taux_full = np.concatenate( (taux_full, nct.variables['taux'][:,j0:j1,i0:i1]), axis=0 )
tauy_full = np.concatenate( (tauy_full, taux_full*0), axis=0 )
## sometimes uvel, vvel are undefined
## mask all values larger than 20m/s
umax = max( np.abs(uvel_full.min()), uvel_full.max() )
vmax = max( np.abs(vvel_full.min()), vvel_full.max() )
if (umax > 10 or vmax > 10):
print ' WARNING!!! uvel > 10 or vmax > 10'
umask = np.where( np.abs(uvel_full) > 20, 1, 0)
vmask = np.where( np.abs(vvel_full) > 20, 1, 0)
uvel_full = np.ma.array( uvel_full, mask=umask )
vvel_full = np.ma.array( vvel_full, mask=vmask )
etan_full = np.ma.array( etan_full, mask=vmask )
print taux_full.shape,umask.shape
taux_full = np.ma.array( taux_full, mask=umask[0,0,:,:] )
tauy_full = np.ma.array( tauy_full, mask=vmask[0,0,:,:] )
umax = max( np.abs(uvel_full.min()), uvel_full.max() )
vmax = max( np.abs(vvel_full.min()), vvel_full.max() )
if (umax > 10 or vmax > 10):
print ' uvel > 10 or vmax > 10 or wmax > 10'
sys.exit()
ncu.close()
nct.close()
data = {}
data['ulon'] = ulon
data['ulat'] = ulat
data['vlon'] = vlon
data['vlat'] = vlat
data['uvel'] = uvel_full
data['vvel'] = vvel_full
data['etan'] = etan_full
data['tlon'] = tlon
data['tlat'] = tlat
data['taux'] = taux_full
data['tauy'] = tauy_full
data['dzt'] = dzt
return data
def calculate_uv_gradients_xy(uvel,vvel,dxu,dyu,dxv,dyv,dxt,dyt,dxf,dyf):
"""
Calculates du/dx, du/dy, dv/dx, dv/dy
and nabla^2 u, nabla^2 v,
and nabla^4 u, nabla^4 v
at T points if u,v are given at U,V points
"""
dudx_xy = np.zeros(uvel.shape)
dvdx_xy = np.zeros(uvel.shape)
dudy_xy = np.zeros(uvel.shape)
dvdy_xy = np.zeros(uvel.shape)
lapu = np.zeros(uvel.shape)
lapv = np.zeros(uvel.shape)
blpu = np.zeros(uvel.shape)
blpv = np.zeros(uvel.shape)
for jk in range(0,uvel.shape[0]):
dudx_xy[jk,1:-1,1:-1] = (uvel[jk,1:-1,1:-1] - uvel[jk,1:-1,0:-2]) / dxu[1:-1,1:-1]
dudy_xy[jk,1:-1,1:-1] = 0.5 * ( (uvel[jk,2:,1:-1] - uvel[jk,0:-2,1:-1]) / (2*dyu[1:-1,1:-1]) + \
(uvel[jk,2:,0:-2] - uvel[jk,0:-2,0:-2]) / (2*dyu[1:-1,1:-1]) )
dvdx_xy[jk,1:-1,1:-1] = 0.5 * ( (vvel[jk,1:-1,2:] - vvel[jk,1:-1,0:-2]) / (2*dxv[1:-1,1:-1]) + \
(vvel[jk,0:-2,2:] - vvel[jk,0:-2,0:-2]) / (2*dxv[1:-1,1:-1]) )
dvdy_xy[jk,1:-1,1:-1] = (vvel[jk,1:-1,1:-1] - vvel[jk,0:-2,1:-1]) / dyv[1:-1,1:-1]
rot = np.zeros((uvel.shape[1],uvel.shape[2]))
div = np.zeros((uvel.shape[1],uvel.shape[2]))
zuf = np.zeros((uvel.shape[1],uvel.shape[2]))
zut = np.zeros((uvel.shape[1],uvel.shape[2]))
# rot = dv/dx - du/dy at F point
rot[1:-1,1:-1] = (vvel[jk,1:-1,2: ] - vvel[jk,1:-1,1:-1])/dxf[1:-1,1:-1] - (uvel[jk,2: ,1:-1] - uvel[jk,1:-1,1:-1])/dyf[1:-1,1:-1]
# div = du/dx + dv/dy at T point
div[1:-1,1:-1] = (uvel[jk,1:-1,1:-1] - uvel[jk,1:-1,0:-2])/dxt[1:-1,1:-1] + (vvel[jk,1:-1,1:-1] - vvel[jk,0:-2,1:-1])/dyt[1:-1,1:-1]
# lap(u) = ddiv/dx - drot/dy at U point
lapu[jk,1:-1,1:-1] = (div[1:-1,2: ] - div[1:-1,1:-1])/dxu[1:-1,1:-1] - (rot[1:-1,1:-1] - rot[0:-2,1:-1])/dyu[1:-1,1:-1]
# lap(v) = drot/dx + ddiv/dy at V point
lapv[jk,1:-1,1:-1] = (rot[1:-1,1:-1] - rot[1:-1,0:-2])/dxv[1:-1,1:-1] + (div[2: ,1:-1] - div[1:-1,1:-1])/dyv[1:-1,1:-1]
# zuf = dlapv/dx - dlapu/dy at F point
zuf[1:-1,1:-1] = (lapv[jk,1:-1,2: ] - lapv[jk,1:-1,1:-1])/dxf[1:-1,1:-1] - (lapu[jk,2: ,1:-1] - lapu[jk,1:-1,1:-1])/dyf[1:-1,1:-1]
# zut = dlapu/dx + dlapv/dy at T point
zut[1:-1,1:-1] = (lapu[jk,1:-1,1:-1] - lapu[jk,1:-1,0:-2])/dxt[1:-1,1:-1] + (lapv[jk,1:-1,1:-1] - lapv[jk,0:-2,1:-1])/dyt[1:-1,1:-1]
# blpu = dzut/dx - dzuf/dy at U point
blpu[jk,1:-1,1:-1] = (zut[1:-1,2: ] - zut[1:-1,1:-1])/dxu[1:-1,1:-1] - (zuf[1:-1,1:-1] - zuf[0:-2,1:-1])/dyu[1:-1,1:-1]
# blpv = dzuf/dx + dzut/dy at V point
blpv[jk,1:-1,1:-1] = (zuf[1:-1,1:-1] - zuf[1:-1,0:-2])/dxv[1:-1,1:-1] + (zut[2: ,1:-1] - zut[1:-1,1:-1])/dyv[1:-1,1:-1]
data = {}
data['dudx_xy'] = dudx_xy
data['dvdx_xy'] = dvdx_xy
data['dudy_xy'] = dudy_xy
data['dvdy_xy'] = dvdy_xy
data['lapu_xy'] = lapu
data['lapv_xy'] = lapv
data['blpu_xy'] = blpu
data['blpv_xy'] = blpv
return data
def calculate_bottom_friction_xy(uvel,vvel,dzt,kbot,Cd=-1e-3,bg_tke=2.5e-3,mode='quadratic'):
"""
"""
## calculate bottom friction
## kbot is the bottom level
if (0):
vu = np.zeros(uvel[:,-1,:,:].shape)
uv = np.zeros(vvel[:,-1,:,:].shape)
vu[:,1:-1,1:-1] = 0.25 * (vvel[:,kbot,1:-1,1:-1] + vvel[:,kbot,0:-2,1:-1] + vvel[:,kbot,1:-1,2:] + vvel[:,kbot,0:-2,2:])
uv[:,1:-1,1:-1] = 0.25 * (uvel[:,kbot,1:-1,1:-1] + uvel[:,kbot,1:-1,0:-2] + uvel[:,kbot,2:,1:-1] + uvel[:,kbot,2:,0:-2])
utrd_bfr2 = -1e-3 * np.sqrt( uvel[:,kbot,:,:]**2 + vu**2 + 2.5 * 1e-3 ) * uvel[:,kbot,:,:] / dzt.sum(axis=1)
vtrd_bfr2 = -1e-3 * np.sqrt( uv**2 + vvel[:,kbot,:,:]**2 + 2.5 * 1e-3 ) * vvel[:,kbot,:,:] / dzt.sum(axis=1)
Hdep = dzt.sum(axis=0)
if (mode == 'quadratic'):
bfru = Cd * np.sqrt( uvel[kbot,:,:]**2 + vvel[kbot,:,:]**2 + bg_tke ) * uvel[kbot,:,:] / Hdep
bfrv = Cd * np.sqrt( uvel[kbot,:,:]**2 + vvel[kbot,:,:]**2 + bg_tke ) * vvel[kbot,:,:] / Hdep
data = {}
data['bfru'] = bfru
data['bfrv'] = bfrv
return data
def calculate_pressure_gradient_xy(ssh,rhd,dxt,dyt,dzt,grav=9.81):
"""
"""
spgu = np.zeros(rhd.shape)
spgv = np.zeros(rhd.shape)
hpgu = np.zeros(rhd.shape)
hpgv = np.zeros(rhd.shape)
for jk in range(0,rhd.shape[0]):
spgu[jk,1:-1,1:-1] = -grav * (ssh[1:-1,2:] - ssh[1:-1,0:-2])/(2*dxt[1:-1,1:-1])
spgv[jk,1:-1,1:-1] = -grav * (ssh[2:,1:-1] - ssh[0:-2,1:-1])/(2*dyt[1:-1,1:-1])
if (jk == 0):
coeff = -grav * 0.5 * dzt[jk,1:-1,1:-1]
hpgu[jk,1:-1,1:-1] = coeff * (rhd[jk,1:-1,2:] - rhd[jk,1:-1,0:-2])/(2*dxt[1:-1,1:-1])
hpgv[jk,1:-1,1:-1] = coeff * (rhd[jk,2:,1:-1] - rhd[jk,0:-2,1:-1])/(2*dyt[1:-1,1:-1])
else:
coeff = -grav * dzt[jk,1:-1,1:-1]
hpgu[jk,1:-1,1:-1] = hpgu[jk-1,1:-1,1:-1] + coeff * (rhd[jk,1:-1,2:] - rhd[jk,1:-1,0:-2])/(2*dxt[1:-1,1:-1])
hpgv[jk,1:-1,1:-1] = hpgv[jk-1,1:-1,1:-1] + coeff * (rhd[jk,2:,1:-1] - rhd[jk,0:-2,1:-1])/(2*dyt[1:-1,1:-1])
## force to zero on boundaries
spgu[:,0,:] = 0. ; spgu[:,-1,:] = 0. ; spgu[:,:,0] = 0. ; spgu[:,:,-1] = 0.
spgv[:,0,:] = 0. ; spgv[:,-1,:] = 0. ; spgv[:,:,0] = 0. ; spgv[:,:,-1] = 0.
hpgu[:,0,:] = 0. ; hpgu[:,-1,:] = 0. ; hpgu[:,:,0] = 0. ; hpgu[:,:,-1] = 0.
hpgv[:,0,:] = 0. ; hpgv[:,-1,:] = 0. ; hpgv[:,:,0] = 0. ; hpgv[:,:,-1] = 0.
preu = spgu + hpgu
prev = spgv + hpgv
data = {}
data['spgu'] = spgu
data['spgv'] = spgv
data['hpgu'] = hpgu
data['hpgv'] = hpgv
data['preu'] = preu
data['prev'] = prev
return data
def rotate_box(xlist,ylist,alpha):
"""
"""
a = alpha*np.pi/180.
Lx = xlist[1]-xlist[0]
Ly = ylist[2]-ylist[1]
x1p = xlist[0]
y1p = ylist[0]
x2p = xlist[0] + np.cos(a) * Lx
y2p = ylist[0] + np.sin(a) * Lx
x3p = x2p - np.sin(a) * Ly
y3p = y2p + np.cos(a) * Ly
x4p = xlist[0] - np.sin(a) * Lx
y4p = ylist[0] + np.cos(a) * Lx
return [x1p,x2p,x3p,x4p],[y1p,y2p,y3p,y4p]
def calculate_vorticity(uvel,vvel,xx,yy):
"""
"""
rot = np.zeros(uvel.shape)
dvdx = (vvel[1:-1,2:]-vvel[1:-1,0:-2]) / (xx[1:-1,2:]-xx[1:-1,0:-2])
dudy = (uvel[2:,1:-1]-uvel[0:-2,1:-1]) / (yy[2:,1:-1]-yy[0:-2,1:-1])
rot[1:-1,1:-1] = dvdx[:,:] - dudy[:,:]
return rot
def calculate_ke(k2D,l2D,uvel,vvel,laverage=True):
"""
"""
uhat = fftn(uvel)
vhat = fftn(vvel)
z = 0.5 * np.real(uhat * np.conj(uhat) + vhat * np.conj(vhat))
if (laverage):
nn = (uvel.shape[1]**2 * uvel.shape[0]**2)
z = z/float(nn)
return z
def calculate_cke(k2D,l2D,uvel,vvel,dz,laverage=True):
"""
Calculate kinetic energy for each layer
"""
dtot = np.sum(dz,axis=0)
for jk in range(0,uvel.shape[0]):
## weight is sqrt(dz/H)
## since we multiply u*u, this ends up being
## u*u*dz/H
## which is what we want to sum
weight = dz[jk] / dtot
uhat = fftn(uvel[jk,:,:])
vhat = fftn(vvel[jk,:,:])
z = 0.5 * np.real(uhat * np.conj(uhat) + vhat * np.conj(vhat)) * weight
if (jk == 0):
cke = z
else:
cke += z
if (laverage):
nn = (uvel.shape[1]**2 * uvel.shape[2]**2)
cke = cke / float(nn)
return cke
def calculate_ens(k2D,l2D,rot):
"""
"""
rhat = fftn(rot)
z = 0.5 * np.real(rhat * np.conj(rhat))
return z
def calculate_spectral_flux(kx,ky,uvel,vvel):
"""
Calculate spectral flux
We assume du/dt = -u du/dx - v du/dy
dv/dt = -u dv/dx - v dv/dy
"""
uhat = fftn(uvel)
vhat = fftn(vvel)
i = np.complex(0,1)
# du/dx in x,y
ddx_u = np.real( ifftn(i*kx*uhat) )
# du/dy in x,y
ddy_u = np.real( ifftn(i*ky*uhat) )
# dv/dx in x,y
ddx_v = np.real( ifftn(i*kx*vhat) )
# dv/dy in x,y
ddy_v = np.real( ifftn(i*ky*vhat) )
# adv_u = u * du/dx + v * du/dy
adv_u = -uvel * ddx_u - vvel * ddy_u
# adv_v = u * dv/dx + v * dv/dy
adv_v = -uvel * ddx_v - vvel * ddy_v
# KE trend from advection:
# - u * adv_u - v * adv_v
# in spectral space
# The minus sign arises as advection
# is on the RHS of the momentum eqs.
Tkxky = np.real( np.conj(uhat)*fftn(adv_u) + \
np.conj(vhat)*fftn(adv_v) ) #[m2/s3]
return Tkxky
def calculate_spectral_flux_baroclinic_barotropic(kx,ky,u_bt,v_bt,u_bc,v_bc):
"""
Calculate spectral flux for a triad
i.e. u_bt * u_bc * du_bc/dx + u_bt * v_bc * du_bc/dy +
v_bt * u_bc * dv_bc/dx + v_bt * v_bc * dv_bc/dy
"""
print ' WARNING: Gradients for barotropic/baroclinic velocities '
print ' are calculated in spectral space. '
print ' You should do the calculations in physical space to agree '
print ' with a grid-point model '
i = np.complex(0,1)
uhat_bt = fftn(u_bt)
vhat_bt = fftn(v_bt)
nx = u_bc.shape[2]
ny = u_bc.shape[1]
nz = u_bc.shape[0]
ddx_u_bt = np.real( ifftn(i*kx*uhat_bt) ) # du_bt/dx
ddy_u_bt = np.real( ifftn(i*ky*uhat_bt) ) # du_bt/dy
ddx_v_bt = np.real( ifftn(i*kx*vhat_bt) ) # dv_bt/dx
ddy_v_bt = np.real( ifftn(i*ky*vhat_bt) ) # dv_bt/dy
for jk in range(0,nz):
uhat_bc = fftn(u_bc[jk,:,:])
vhat_bc = fftn(v_bc[jk,:,:])
ddx_u_bc = np.real( ifftn(i*kx*uhat_bc) ) # du_bc/dx
ddy_u_bc = np.real( ifftn(i*ky*uhat_bc) ) # du_bc/dy
ddx_v_bc = np.real( ifftn(i*kx*vhat_bc) ) # dv_bc/dx
ddy_v_bc = np.real( ifftn(i*ky*vhat_bc) ) # dv_bc/dy
if (jk == 0):
# adv_u = u * du/dx + v * du/dy
adv_u_bc_bc = u_bc[jk,:,:] * ddx_u_bc + v_bc[jk,:,:] * ddy_u_bc
adv_u_bt_bt = u_bt[:,:] * ddx_u_bt + v_bt[:,:] * ddy_u_bt
# adv_v = u * dv/dx + v * dv/dy
adv_v_bc_bc = u_bc[jk,:,:] * ddx_v_bc + v_bc[jk,:,:] * ddy_v_bc
adv_v_bt_bt = u_bt[:,:] * ddx_v_bt + v_bt[:,:] * ddy_v_bt
else:
# adv_u = u * du/dx + v * du/dy
adv_u_bc_bc = adv_u_bc_bc + u_bc[jk,:,:] * ddx_u_bc + v_bc[jk,:,:] * ddy_u_bc
adv_u_bt_bt = adv_u_bt_bt + u_bt[:,:] * ddx_u_bt + v_bt[:,:] * ddy_u_bt
# adv_v = u * dv/dx + v * dv/dy
adv_v_bc_bc = adv_v_bc_bc + u_bc[jk,:,:] * ddx_v_bc + v_bc[jk,:,:] * ddy_v_bc
adv_v_bt_bt = adv_v_bt_bt + u_bt[:,:] * ddx_v_bt + v_bt[:,:] * ddy_v_bt
adv_u_bc_bc = adv_u_bc_bc / float(nz)
adv_v_bc_bc = adv_v_bc_bc / float(nz)
adv_u_bt_bt = adv_u_bt_bt / float(nz)
adv_v_bt_bt = adv_v_bt_bt / float(nz)
# KE trend from advection:
# - u * adv_u - v * adv_v
# in spectral space
# The minus sign arises as advection
# is on the RHS of the momentum eqs.
Tk_bt_bc_bc = np.real( -np.conj(uhat_bt)*fftn(adv_u_bc_bc) - \
np.conj(vhat_bt)*fftn(adv_v_bc_bc) ) #[m2/s3]
Tk_bt_bt_bt = np.real( -np.conj(uhat_bt)*fftn(adv_u_bt_bt) - \
np.conj(vhat_bt)*fftn(adv_v_bt_bt) ) #[m2/s3]
Tk_bc_bc_bc = np.real( -np.conj(uhat_bc)*fftn(adv_u_bc_bc) - \
np.conj(vhat_bc)*fftn(adv_v_bc_bc) )
nn = (nx**2 * ny**2)
data = {}
data['Tk_bt_bc_bc'] = Tk_bt_bc_bc / float(nn)
data['Tk_bt_bt_bt'] = Tk_bt_bt_bt / float(nn)
data['Tk_bc_bc_bc'] = Tk_bc_bc_bc / float(nn)
return data
def calculate_spectral_flux_baroclinic_barotropic5(kx,ky,u_bt,v_bt,u_bc,v_bc,dzt):
"""
Calculate spectral flux for a triad
i.e. u_bt * u_bc * du_bc/dx + u_bt * v_bc * du_bc/dy +
v_bt * u_bc * dv_bc/dx + v_bt * v_bc * dv_bc/dy
Used in Kjellsson & Zanna (Fluids, 2017)
A good reference for the terms is Scott & Arbic (JPO, 2007)
Note: Triads that only include one baroclinic component,
e.g. (bt,bt,bc) should be zero.
Check that they are!
Barotropic velocity, (u_bt, v_bt), is 2D
and baroclinic velocity (u_bc,v_bc) is 3D
Input:
kx, ky - 2D arrays with zonal and meridional wavenumbers
u_bt, v_bt - 2D arrays with barotropic velocity components
u_bc, v_bc - 3D arrays with baroclinic velocity components
Output:
data - Dictionary containing 8 different triad interactions
"""
i = np.complex(0,1)
uhat_bt = fftn(u_bt)
vhat_bt = fftn(v_bt)
nx = u_bc.shape[2]
ny = u_bc.shape[1]
nz = u_bc.shape[0]
# derivatives for barotropic velocities
ddx_u_bt = np.real( ifftn(i*kx*uhat_bt) ) # du_bt/dx
ddy_u_bt = np.real( ifftn(i*ky*uhat_bt) ) # du_bt/dy
ddx_v_bt = np.real( ifftn(i*kx*vhat_bt) ) # dv_bt/dx
ddy_v_bt = np.real( ifftn(i*ky*vhat_bt) ) # dv_bt/dy
# Barotropic self-interactions
# adv_u = u * du/dx + v * du/dy
adv_u_bt_bt = u_bt[:,:] * ddx_u_bt + v_bt[:,:] * ddy_u_bt
# adv_v = u * dv/dx + v * dv/dy
adv_v_bt_bt = u_bt[:,:] * ddx_v_bt + v_bt[:,:] * ddy_v_bt
adv_u_bc_bc_tot = np.zeros((ny,nx))
adv_u_bt_bc_tot = np.zeros((ny,nx))
adv_u_bc_bt_tot = np.zeros((ny,nx))
adv_v_bc_bc_tot = np.zeros((ny,nx))
adv_v_bt_bc_tot = np.zeros((ny,nx))
adv_v_bc_bt_tot = np.zeros((ny,nx))
Tk_bc_bc_bc = np.zeros(uhat_bt.shape)
Tk_bc_bt_bt = np.zeros(uhat_bt.shape)
Tk_bc_bc_bt = np.zeros(uhat_bt.shape)
Tk_bc_bt_bc = np.zeros(uhat_bt.shape)
Hsum = np.sum(dzt,axis=0)
for jk in range(0,nz):
uhat_bc = fftn(u_bc[jk,:,:])
vhat_bc = fftn(v_bc[jk,:,:])
ddx_u_bc = np.real( ifftn(i*kx*uhat_bc) ) # du_bc/dx
ddy_u_bc = np.real( ifftn(i*ky*uhat_bc) ) # du_bc/dy
ddx_v_bc = np.real( ifftn(i*kx*vhat_bc) ) # dv_bc/dx
ddy_v_bc = np.real( ifftn(i*ky*vhat_bc) ) # dv_bc/dy
# weight baroclinic advection by layer thickness
# adv_u = u * du/dx + v * du/dy
adv_u_bc_bc = (u_bc[jk,:,:] * ddx_u_bc + v_bc[jk,:,:] * ddy_u_bc) * dzt[jk,:,:]/Hsum
adv_u_bc_bt = (u_bc[jk,:,:] * ddx_u_bt + v_bc[jk,:,:] * ddy_u_bt) * dzt[jk,:,:]/Hsum
adv_u_bt_bc = (u_bt[:,:] * ddx_u_bc + v_bt[:,:] * ddy_u_bc) * dzt[jk,:,:]/Hsum
# adv_v = u * dv/dx + v * dv/dy
adv_v_bc_bc = (u_bc[jk,:,:] * ddx_v_bc + v_bc[jk,:,:] * ddy_v_bc) * dzt[jk,:,:]/Hsum
adv_v_bc_bt = (u_bc[jk,:,:] * ddx_v_bt + v_bc[jk,:,:] * ddy_v_bt) * dzt[jk,:,:]/Hsum
adv_v_bt_bc = (u_bt[:,:] * ddx_v_bc + v_bt[:,:] * ddy_v_bc) * dzt[jk,:,:]/Hsum
# vertical sum of advection terms
adv_u_bc_bc_tot = adv_u_bc_bc_tot + adv_u_bc_bc
adv_u_bt_bc_tot = adv_u_bt_bc_tot + adv_u_bt_bc
adv_u_bc_bt_tot = adv_u_bc_bt_tot + adv_u_bc_bt
adv_v_bc_bc_tot = adv_v_bc_bc_tot + adv_v_bc_bc
adv_v_bt_bc_tot = adv_v_bt_bc_tot + adv_v_bt_bc
adv_v_bc_bt_tot = adv_v_bc_bt_tot + adv_v_bc_bt
# baroclinic budget
Tk_bc_bc_bc = Tk_bc_bc_bc + np.real( -np.conj(uhat_bc)*fftn(adv_u_bc_bc) - \
np.conj(vhat_bc)*fftn(adv_v_bc_bc) )
Tk_bc_bc_bt = Tk_bc_bc_bt + np.real( -np.conj(uhat_bc)*fftn(adv_u_bc_bt) - \
np.conj(vhat_bc)*fftn(adv_v_bc_bt) ) #[m2/s3]
Tk_bc_bt_bc = Tk_bc_bt_bc + np.real( -np.conj(uhat_bc)*fftn(adv_u_bt_bc) - \
np.conj(vhat_bc)*fftn(adv_v_bt_bc) ) #[m2/s3]
# weight barotropic advection by layer thickness
adv_u_bt_bt_new = adv_u_bt_bt * dzt[jk,:,:]/Hsum
adv_v_bt_bt_new = adv_v_bt_bt * dzt[jk,:,:]/Hsum
Tk_bc_bt_bt = Tk_bc_bt_bt + np.real( -np.conj(uhat_bc)*fftn(adv_u_bt_bt_new) - \
np.conj(vhat_bc)*fftn(adv_v_bt_bt_new) ) #[m2/s3]
# KE trend from advection:
# - u * adv_u - v * adv_v
# The minus sign arises as advection
# is on the RHS of the momentum eqs.
# barotropic budget
Tk_bt_bc_bc = np.real( -np.conj(uhat_bt)*fftn(adv_u_bc_bc_tot) - \
np.conj(vhat_bt)*fftn(adv_v_bc_bc_tot) ) #[m2/s3]
Tk_bt_bt_bt = np.real( -np.conj(uhat_bt)*fftn(adv_u_bt_bt) - \
np.conj(vhat_bt)*fftn(adv_v_bt_bt) ) #[m2/s3]
Tk_bt_bc_bt = np.real( -np.conj(uhat_bt)*fftn(adv_u_bc_bt_tot) - \
np.conj(vhat_bt)*fftn(adv_v_bc_bt_tot) ) #[m2/s3]
Tk_bt_bt_bc = np.real( -np.conj(uhat_bt)*fftn(adv_u_bt_bc_tot) - \
np.conj(vhat_bt)*fftn(adv_v_bt_bc_tot) ) #[m2/s3]
## The FFT routine in scipy returns
## y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()
## where j is wavenumber, x is array in gridpoint space, and n is number of grid points
## To normalise, we must divide by n
## if its a 2D FFT, we must divide by nx*ny
## and since we take the square of the transformed variables
## we must divide by (nx*ny)^2
nn2 = (nx**2 * ny**2)
data = {}
data['Tk_bt_bc_bc'] = Tk_bt_bc_bc / float(nn2) #[m2/s3] (energy per second)
data['Tk_bt_bt_bt'] = Tk_bt_bt_bt / float(nn2)
data['Tk_bt_bc_bt'] = Tk_bt_bc_bt / float(nn2)
data['Tk_bt_bt_bc'] = Tk_bt_bt_bc / float(nn2)
data['Tk_bc_bc_bc'] = Tk_bc_bc_bc / float(nn2)
data['Tk_bc_bc_bt'] = Tk_bc_bc_bt / float(nn2)
data['Tk_bc_bt_bt'] = Tk_bc_bt_bt / float(nn2)
data['Tk_bc_bt_bc'] = Tk_bc_bt_bc / float(nn2)
return data
def calculate_spectral_ke_tendency(uvel,vvel,du,dv,win=1.):
"""
Calculate KE tendency using momentum and momentum tendencies
"""
npoints_sq = uvel.shape[0]**2 * uvel.shape[1]**2
d_ke = np.real( np.conj( fftn(uvel[:,:]*win) ) * fftn(du[:,:]*win) + \
np.conj( fftn(vvel[:,:]*win) ) * fftn(dv[:,:]*win) ) / float(npoints_sq)
return d_ke
def calculate_spectral_ape_flux(kx,ky,uvel,vvel,ape):
"""
"""
i = np.complex(0,1)
nx = uvel.shape[2]
ny = uvel.shape[1]
nz = uvel.shape[0]
## FFT of the square root of APE
## We will multiply by conj of APE later, so
## we must take square root so that the final
## product is APE
ahat = fftn(np.sqrt(ape))
for jk in range(0,nz):
uhat = fftn(uvel[jk,:,:])
vhat = fftn(vvel[jk,:,:])
# dAPE/dx in x,y
ddx_ape = np.real( ifftn(i*kx*ahat) )
# dAPE/dy in x,y
ddy_ape = np.real( ifftn(i*ky*ahat) )
# u * dAPE/dx + v * dAPE/dy
tmp = uvel[jk,:,:] * ddx_ape + vvel[jk,:,:] * ddy_ape
adv_tmp = np.real( -np.conj(ahat)*fftn(tmp) ) #[m2/s3]
if (jk == 0):
adv_ape = tmp
else:
adv_ape += tmp
adv_ape = adv_ape / float(nz)
nn = (ahat.shape[1]**2 * ahat.shape[0]**2)
adv_ape = adv_ape / float(nn)
data = {}
data['adv_ape'] = adv_ape
return data
def calculate_spectral_ape_flux_baroclinic_barotropic(kx,ky,u_bt,v_bt,u_bc,v_bc,ape):
"""
"""
i = np.complex(0,1)
uhat_bt = fftn(u_bt)
vhat_bt = fftn(v_bt)
nx = u_bt.shape[1]
ny = u_bt.shape[0]
nz = u_bc.shape[0]
## FFT of the square root of APE
## We will multiply by conj of APE later, so
## we must take square root so that the final
## product is APE
ahat = fftn(np.sqrt(ape))
# dAPE/dx in x,y
ddx_ape = np.real( ifftn(i*kx*ahat) )
# dAPE/dy in x,y
ddy_ape = np.real( ifftn(i*ky*ahat) )
# u_bt * dAPE/dx + v_bt * dAPE/dy
adv_bt_ape = u_bt * ddx_ape + v_bt * ddy_ape
for jk in range(0,nz):
uhat_bc = fftn(u_bc[jk,:,:])
vhat_bc = fftn(v_bc[jk,:,:])
# u_bc * dAPE/dx + v_bc * dAPE/dy
if (jk == 0):
adv_bc_ape = u_bc[jk,:,:] * ddx_ape + v_bc[jk,:,:] * ddy_ape
else:
adv_bc_ape += u_bc[jk,:,:] * ddx_ape + v_bc[jk,:,:] * ddy_ape
adv_ape_bt_ape = np.real( -np.conj(ahat)*fftn(adv_bt_ape) ) #[m2/s3]
adv_ape_bc_ape = np.real( -np.conj(ahat)*fftn(adv_bc_ape) ) #[m2/s3]
nn = (ahat.shape[1]**2 * ahat.shape[0]**2)
adv_ape_bt_ape = adv_ape_bt_ape / float(nn)
adv_ape_bc_ape = adv_ape_bc_ape / float(nn)
data = {}
data['adv_ape_bt_ape'] = adv_ape_bt_ape
data['adv_ape_bc_ape'] = adv_ape_bc_ape
return data
def calculate_spectral_ens_flux(kx,ky,uvel,vvel,rot):
"""
"""
rhat = fftn(rot)
uhat = fftn(uvel)
vhat = fftn(vvel)
i = np.complex(0,1)
# drot/dx in x,y
ddx_rot = np.real( ifftn(i*kx*rhat) )
# drot/dy in x,y
ddy_rot = np.real( ifftn(i*ky*rhat) )
# adv_rot = u * drot/dx + v * drot/dy
adv_rot = uvel * ddx_rot + vvel * ddy_rot
# Enstrophy trend from advection:
# rot * adv_rot
# in spectral space
Tkxky = np.real( -np.conj(rhat)*fftn(adv_rot) )
return Tkxky
def calculate_spectral_viscosity(kx,ky,uvel,Ahm,order='4'):
"""
Calculate spectral flux
We assume du/dt = (d4/dx4+d4/dy4) u (order 4) or
du/dt = (d2/dx2+d2/dy2) u (order 2) or
"""
uhat = fftn(uvel)
i = np.complex(0,1)
if (order == '4'):
# d4u/dx4 in x,y
ddx_u = Ahm * np.real( ifftn(kx**4 * uhat) )
# d4u/dy4 in x,y
ddy_u = Ahm * np.real( ifftn(ky**4 * uhat) )
# 2 d4/dx2dy2 in x,y
ddxy_u = Ahm * np.real( ifftn(2 * kx**2 * ky**2 * uhat) )
##
Tkxky = np.real( np.conj(uhat) * fftn(ddx_u) + \
np.conj(uhat) * fftn(ddxy_u)+ \
np.conj(uhat) * fftn(ddy_u) )
elif (order == '2'):
# d2u/dx2 in x,y
ddx_u = -Ahm * np.real( ifftn(kx**2 * uhat) )
# d2u/dy2 in x,y
ddy_u = -Ahm * np.real( ifftn(ky**2 * uhat) )
# KE trend from viscosity:
# ddx_u + ddy_u
# in spectral space
Tkxky = np.real( np.conj(uhat) * fftn(ddx_u) + \
np.conj(uhat) * fftn(ddy_u) )
return Tkxky
def calculate_spectral_forcing(kx,ky,uvel,vvel,taux,tauy,rho=1023.,laverage=True):
"""
Calculate spectral flux from wind forcing