forked from mjucker/aostools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclimate.py
3576 lines (3314 loc) · 125 KB
/
climate.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
#!/usr/bin/python
# Filename: climate.py
#
# Code by Martin Jucker, distributed under an GPLv3 License
#
# This file provides helper functions that can be useful as pre-viz-processing of files and data
############################################################################################
#
from __future__ import print_function
import numpy as np
# from numba import jit
## helper function: Get actual width and height of axes
def GetAxSize(fig,ax,dpi=False):
"""get width and height of a given axis.
output is in inches if dpi=False, in dpi if dpi=True
"""
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
if dpi:
width *= fig.dpi
height *= fig.dpi
return width, height
## helper function: check if string contained in list (set) of strings
def CheckAny(string,set):
for c in set:
if c in string: return True
return False
## helper function: return the day of the year instead of full date
def FindDayOfYear(dateStruc,dateUnits,calendar):
import netcdftime as nct
nDays = len(dateStruc)
t = nct.utime(dateUnits,calendar=calendar)
dateLoc = np.zeros_like(dateStruc)
for d in range(nDays):
dateLoc[d] = nct.datetime(1,dateStruc[d].month,dateStruc[d].day)
dayOfYear = t.date2num(dateLoc)
return dayOfYear
## compute climatologies
def ComputeClimate(file, climatType, wkdir='/', timeDim='time',cal=None):
"""Compute climatologies from netCDF files.
ComputeClimate(file,climatType,wkdir='/',timeDim='time')
Inputs:
file file name, relative path from wkdir
climatType 'daily', 'monthly', 'annual', 'DJF', 'JJA', or any
combination of months according to two-letter code
Ja Fe Ma Ap My Jn Jl Au Se Oc No De
wkdir working directory, in which 'file' must be, and to which the output
is written
timeDim name of the time dimension in the netcdf file
cal calendar, if other than within the netcdf file
Outputs:
outFile name of the output file created
writes outputfile with name depending on input file name and climatType
"""
# need to read netCDF and of course do some math
import netCDF4 as nc
import os
if climatType == 'DJF':
climType = 'DeJaFe'
elif climatType == 'JJA':
climType = 'JuJlAu'
elif climatType == 'annual':
climType = 'JaFeMaApMyJnJlAuSeOcNoDe'
else:
climType = climatType
monthList=['Ja','Fe','Ma','Ap','My','Jn','Jl','Au','Se','Oc','No','De']
calendar_types = ['standard', 'gregorian', 'proleptic_gregorian', 'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day']
if wkdir[-1] != '/': wkdir += '/'
if os.path.isfile(wkdir+file):
ncFile = nc.Dataset(wkdir+file,'r+')
else:
raise IOError(wkdir+file+' does not exist')
time = ncFile.variables[timeDim][:]
numTimeSteps = len(time)
timeVar = ncFile.variables[timeDim]
# check the time units
timeUnits = timeVar.units
chck = CheckAny(timeUnits,('seconds','days','months'))
if not chck:
print('Cannot understand units of time, which is: '+timeUnits)
newUnits = raw_input('Please provide units [seconds,days,months] ')
if newUnits not in ["seconds","days","months"]:
raise ValueError('units must be seconds, days, or months')
unitSplit = timeUnits.split()
unitSplit[0] = newUnits
timeUnits = ' '.join(unitSplit)
timeStep = np.diff(timeVar).mean()
print('The time dimension is in units of',timeUnits,', with a mean time step of',timeStep,'days')
# check the calendar type
getCal = False
if cal:
timeCal = cal
else:
try:
timeCal = str(timeVar.calendar)
if not CheckAny(timeCal,calendar_types):
print('Cannot understand the calendar type, which is: '+timeCal)
timeCal = raw_input('Please provide a calendar type from the list '+str(calendar_types)+' ')
timeVar.calendar = timeCal
except:
timeCal = raw_input('Please provide a calendar type from the list '+str(calendar_types)+' ')
if timeCal not in calendar_types:
raise ValueError('calender must be in '+str(calendar_types))
else:
print('Calendar type '+timeCal)
#
# split everything into years,months,days
date = nc.num2date(time,timeUnits,timeCal)
days = np.zeros(len(date),)
monthsI = np.zeros_like(days)
monthsS = []
years = np.zeros_like(days)
for d in range(len(date)):
days[d] = date[d].day
monthsI[d] = date[d].month
monthsS.append(monthList[date[d].month-1])
years[d] = date[d].year
# Now, need to know about the type of climatology we want.
#
if climType == 'daily':
dayOfYear = FindDayOfYear(date,timeUnits,timeCal)
climTimeDim = np.sort(np.unique(dayOfYear))
climTimeVar = dayOfYear
elif climType == 'monthly':
climTimeDim = np.sort(np.unique(monthsI)) - 1
climTimeVar = monthsI - 1
else:
climTimeVar = np.zeros_like(days)
for m in range(len(climType)/2):
thisMonth = climType[m*2:m*2+2]
indices = [i for i, x in enumerate(monthsS) if x == thisMonth]
climTimeVar[indices] = 1
# Create the output file, including dimensions.
#
# We exclude time for seasonal climatologies, but need time for daily and monthly.
outFileName = wkdir + file[0:-3] + '_' + climatType + '.nc'
try:
os.remove(outFileName)
except:
pass
outFile = nc.Dataset(outFileName,'w',format=ncFile.file_format)
for dim in ncFile.dimensions:
if dim != timeDim:
outDim = outFile.createDimension(dim,len(ncFile.dimensions[dim]))
inVar = ncFile.variables[dim]
outVar = outFile.createVariable(dim,str(ncFile.variables[dim].dtype),(dim,))
outVar[:] = inVar[:]
for att in inVar.ncattrs():
if not 'edges' in att:
outVar.setncattr(att,inVar.getncattr(att))
elif climType == 'daily' or climType == 'monthly':
nTime = len(climTimeDim)
if climType == 'daily':
units = 'days'
else:
units = 'months'
dTime = climTimeDim
outDim = outFile.createDimension(dim,nTime)
timeValue = dTime
outVar = outFile.createVariable(dim,str(ncFile.variables[dim].dtype),(dim,))
outVar[:] = timeValue
outVar.setncattr('long_name','climatological ' + units[:-1] + ' of year')
outVar.setncattr('units',units + ' since 0001-01-01 00:00:00')
outVar.setncattr('calendar',timeCal)
outVar.setncattr('cartesian_axis','T')
outVar.setncattr('bounds','time_bounds')
# Finally, perform the averaging and write into new file
#
# Here, we need to be very careful in the event of packaged data: netCDF4 knows about packaging when reading data, but we need to use scale_factor and add_offset to package the data back when writing the new file.
print('Averaging variables:')
for var in ncFile.variables:
varShape = np.shape(ncFile.variables[var])
if len(varShape) == 0: continue
if varShape[0] == numTimeSteps and len(varShape) >= 2:
print(' ',var)
tmpVar = ncFile.variables[var][:]
if climType != 'daily' and climType != 'monthly':
outVar = outFile.createVariable(var,str(ncFile.variables[var].dtype),ncFile.variables[var].dimensions[1:])
tmpAvg = tmpVar[climTimeVar>0,:].mean(axis=0)
else:
outVar = outFile.createVariable(var,str(ncFile.variables[var].dtype),ncFile.variables[var].dimensions )
avgShape = []
avgShape.append(nTime)
for t in range(len(np.shape(outVar))-1):
avgShape.append(np.shape(outVar)[t+1])
tmpAvg = np.zeros(avgShape)
for t in range(nTime):
includeSteps = climTimeVar == climTimeDim[t]
tmpAvg[t,:] = tmpVar[includeSteps,:].mean(axis=0)
#package average
if 'add_offset' in ncFile.variables[var].ncattrs():
tmpAvg = tmpAvg - ncFile.variables[var].getncattr('add_offset')
if 'scale_factor' in ncFile.variables[var].ncattrs():
tmpAvg = tmpAvg/ncFile.variables[var].getncattr('scale_factor')
#put the packaged average into the output variable
outVar[:] = tmpAvg.astype(np.int16)
else:
outVar[:] = tmpAvg
inVar = ncFile.variables[var]
for att in inVar.ncattrs():
outVar.setncattr(att,inVar.getncattr(att))
ncFile.close()
outFile.close()
print('DONE, wrote file',outFileName)
return outFileName
##############################################################################################
# get the saturation mixing ration according to Clausius-Clapeyron
# helper function: re-arrange array dimensions
def AxRoll(x,ax,invert=False):
"""Re-arrange array x so that axis 'ax' is first dimension.
Undo this if invert=True
"""
if ax < 0:
n = len(x.shape) + ax
else:
n = ax
#
if invert is False:
y = np.rollaxis(x,n,0)
else:
y = np.rollaxis(x,0,n+1)
return y
def ComputeSaturationMixingRatio(T, p, pDim):
"""Computes the saturation water vapor mixing ratio according to Clausius-Clapeyron
INPUTS:
T - temperature in Kelvin, any size
p - pressure in hPa/mbar, must be one dimension of T
pDim - index of dimension corresponding to p
OUTPUTS:
qsat - saturation water mixing ratio [kg/kg]
"""
#some constants we need
from .constants import Rd,Rv,ESO,HLV,Tfreeze
# make sure we are operating along the pressure axis
T = AxRoll(T,pDim)
# pressure is assumed in hPa: convert to Pa
p = p*100
# compute saturation pressure
esat = ES0*np.exp(HLV*(1./Tfreeze - 1./T)/Rv)
qsat = np.zeros_like(esat)
# finally, compute saturation mixing ratio from pressure
for k in range(len(p)):
qsat[k,:] = Rd/Rv*esat[k,:]/(p[k]-esat[k,:])
return AxRoll(qsat,pDim,invert=True)
##############################################################################################
def ComputeRelativeHumidity(inFile, pDim, outFile='none', temp='temp', sphum='sphum', pfull='pfull'):
"""Computes relative humidity from temperature and specific humidity.
File inFile is assumed to contain both temperature and specific humidity.
Relative humidity is either output of the function, or written to the file outFile.
Inputs:
inFile Name of the file (full path)
containing temperature and moisture
pDim Index of pressure dimension within temperature array
outFile Name of the output file containing specific humidity.
No output file is created if outFile='none'
temp Name of the temperature variable inside inFile
sphum Name of specific humidity variable inside inFile
pfull Name of full level pressure [hPa] inside inFile
"""
import netCDF4 as nc
# relative humidity is then q/qsat*100[->%]
# read input file
inFile = nc.Dataset(inFile, 'r')
t = inFile.variables[temp][:]
q = inFile.variables[sphum][:]
p = inFile.variables[pfull][:]
# compute saturation mixing ratio
qsat = ComputeSaturationMixingRatio(t, p, pDim)
#write output file
if outFile != 'none':
outFile = nc.Dataset(inFile[0:-3]+'_out.nc','w')
for dim in ncFile.dimensions:
outDim = outFile.createDimension(dim,len(ncFile.dimensions[dim]))
inVar = ncFile.variables[dim]
outVar = outFile.createVariable(dim, str(ncFile.variables[dim].dtype),(dim,))
for att in inVar.ncattrs():
outVar.setncattr(att,inVar.getncattr(att))
outVar[:] = inVar[:]
outVar = outFile.createVariable('rh', 'f4', ncFile.variables[temp].dimensions)
outVar[:] = q/qsat*1.e2
return q/qsat*1.e2
##############################################################################################
def ComputePsi(data, outFileName='none', temp='temp', vcomp='vcomp', lat='lat', pfull='pfull', time='time', p0=1e3):
"""Computes the residual stream function \Psi* (as a function of time).
INPUTS:
data - filename of input file or dictionary with temp,vcomp,lat,pfull
outFileName - filename of output file, 'none', or 'same'
temp - name of temperature field in inFile
vcomp - name of meridional velocity field in inFile
lat - name of latitude in inFile
pfull - name of pressure in inFile [hPa]
time - name of time field in inFile. Only needed if outFile used
p0 - pressure basis to compute potential temperature [hPa]
OUTPUTS:
psi - stream function, as a function of time
psis - residual stream function, as a function of time
"""
import netCDF4 as nc
from scipy.integrate import cumtrapz
import os
# some constants
from .constants import kappa,a0,g
if isinstance(data,str):
# check if file exists
if not os.path.isfile(data):
raise IOError('File '+data+' does not exist')
# read input file
print('Reading data')
update_progress(0)
if outFileName == 'same':
mode = 'a'
else:
mode = 'r'
inFile = nc.Dataset(data, mode)
t = inFile.variables[temp][:]
update_progress(.45)
v = inFile.variables[vcomp][:]
update_progress(.90)
l = inFile.variables[lat][:]
update_progress(.95)
p = inFile.variables[pfull][:]
update_progress(1)
else:
t = data[temp]
v = data[vcomp]
l = data[lat]
p = data[pfull]
data = []
p = p *100 # [Pa]
p0 = p0*100 # [Pa]
#
## compute psi
v_bar,t_bar = ComputeVertEddy(v,t,p,p0) # t_bar = bar(v'Th'/(dTh_bar/dp))
# Eulerian streamfunction
psi = cumtrapz(v_bar,x=p,axis=1,initial=0) # [m.Pa/s]
v_bar=v=t=[]
## compute psi* = psi - bar(v'Th'/(dTh_bar/dp))
psis = psi - t_bar
t_bar = []
psi = 2*np.pi*a0/g*psi *np.cos(l[np.newaxis,np.newaxis,:]*np.pi/180.) #[kg/s]
psis= 2*np.pi*a0/g*psis*np.cos(l[np.newaxis,np.newaxis,:]*np.pi/180.) #[kg/s]
## write outputfile
if outFileName != 'none':
print('Writing file '+outFileName)
if outFileName != 'same':
outFile = nc.Dataset(outFileName,'w')
for dim in inFile.dimensions:
if dim in [time,pfull,lat]:
outDim = outFile.createDimension(dim,len(inFile.dimensions[dim]))
inVar = inFile.variables[dim]
outVar = outFile.createVariable(dim, str(inFile.variables[dim].dtype),(dim,))
for att in inVar.ncattrs():
if att != '_FillValue': #no fill value in dimensions!
outVar.setncattr(att,inVar.getncattr(att))
outVar[:] = inVar[:]
else:
outFile = inFile
outVar = outFile.createVariable('psi', 'f4', (time,pfull,lat,))
outVar[:] = psi
outVar = outFile.createVariable('psi_star', 'f4', (time,pfull,lat,))
outVar[:] = psis
outFile.close()
print('Done writing file '+outFileName)
if outFileName != 'same':
inFile.close()
return psi,psis
##############################################################################################
def ComputePsiXr(v, t, lon='lon', lat='lat', pres='level', time='time', ref='mean', p0=1e3):
"""Computes the residual stream function \Psi* (as a function of time).
INPUTS:
v - meridional wind, xr.DataArray
t - temperature, xr.DataArray
lon - name of longitude in t
lat - name of latitude in t
pres - name of pressure in t [hPa]
time - name of time field in t
ref - how to treat dTheta/dp:
- 'rolling-X' : centered rolling mean over X days
- 'mean' : full time mean
p0 - pressure basis to compute potential temperature [hPa]
OUTPUTS:
psi - stream function, as a function of time
psis - residual stream function, as a function of time
"""
from scipy.integrate import cumtrapz
from numpy import cos,deg2rad
# some constants
from .constants import kappa,a0,g
#
## compute psi
v_bar,t_bar = ComputeVertEddyXr(v,t,pres,p0,lon,time,ref) # t_bar = bar(v'Th'/(dTh_bar/dp))
# Eulerian streamfunction
pdim = v_bar.get_axis_num(pres)
psi = v_bar.reduce(cumtrapz,x=v_bar[pres],axis=pdim,initial=0) # [m.hPa/s]
## compute psi* = psi - bar(v'Th'/(dTh_bar/dp))
psis = psi - t_bar
coslat = np.cos(np.deg2rad(t[lat]))
psi = 2*np.pi*a0/g*psi *coslat*100 #[kg/s]
psis= 2*np.pi*a0/g*psis*coslat*100 #[kg/s]
## give the DataArrays their names
psi.name = 'psi'
psis.name= 'psis'
return psi,psis
##############################################################################################
## helper functions
def update_progress(progress,barLength=10,info=None):
import sys
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "\r" #"\r\n"
#status = "Done...\r\n"
block = int(round(barLength*progress))
if info is not None:
text = '\r'+info+': '
else:
text = '\r'
if progress == 1:
if info is not None:
text = "\r{0} {1} {2}".format(" "*(len(info)+1)," "*barLength,status)
else:
text = "\r {0} {1}".format(" "*barLength,status)
else:
text += "[{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), int(progress*100), status)
sys.stdout.write(text)
sys.stdout.flush()
#
def ComputeVertEddy(v,t,p,p0=1e3,wave=0):
""" Computes the vertical eddy components of the residual circulation,
bar(v'Theta'/Theta_p). Either in real space, or a given wave number.
Dimensions must be time x pres x lat x lon.
Output dimensions are: time x pres x lat
Output units are [v_bar] = [v], [t_bar] = [v*p]
INPUTS:
v - meridional wind
t - temperature
p - pressure coordinate
p0 - reference pressure for potential temperature
wave - wave number (if >=0)
OUPUTS:
v_bar - zonal mean meridional wind [v]
t_bar - zonal mean vertical eddy component <v'Theta'/Theta_p> [v*p]
"""
#
# some constants
from .constants import kappa
#
# pressure quantitites
pp0 = (p0/p[np.newaxis,:,np.newaxis,np.newaxis])**kappa
dp = np.gradient(p)[np.newaxis,:,np.newaxis]
# convert to potential temperature
t = t*pp0 # t = theta
# zonal means
v_bar = np.nanmean(v,axis=-1)
t_bar = np.nanmean(t,axis=-1) # t_bar = theta_bar
# prepare pressure derivative
dthdp = np.gradient(t_bar,edge_order=2)[1]/dp # dthdp = d(theta_bar)/dp
dthdp[dthdp==0] = np.NaN
# time mean of d(theta_bar)/dp
dthdp = np.nanmean(dthdp,axis=0)[np.newaxis,:]
# now get wave component
#if isinstance(wave,list):
# t = np.sum(GetWaves(v,t,wave=-1,do_anomaly=True)[:,:,:,wave],axis=-1)
if wave == 0:
v = GetAnomaly(v) # v = v'
t = GetAnomaly(t) # t = t'
t = np.nanmean(v*t,axis=-1) # t = bar(v'Th')
else:
t = GetWaves(v,t,wave=wave,do_anomaly=True) # t = bar(v'Th'_{k=wave})
if wave < 0:
dthdp = np.expand_dims(dthdp,-1)
t_bar = t/dthdp # t_bar = bar(v'Th')/(dTh_bar/dp)
#
return v_bar,t_bar
def ComputeVertEddyXr(v,t,p='level',p0=1e3,lon='lon',time='time',ref='mean',wave=0):
""" Computes the vertical eddy components of the residual circulation,
bar(v'Theta'/Theta_p).
Output units are [v_bar] = [v], [t_bar] = [v*p]
INPUTS:
v - meridional wind, xr.DataArray
t - temperature, xr.DataArray
p - name of pressure
p0 - reference pressure for potential temperature
lon - name of longitude
time - name of time field in t
ref - how to treat dTheta/dp:
- 'rolling-X' : centered rolling mean over X days
- 'mean' : full time mean
- 'instant' : no time operation
wave - wave number: if == 0, return total. else passed to GetWavesXr()
OUPUTS:
v_bar - zonal mean meridional wind [v]
t_bar - zonal mean vertical eddy component <v'Theta'/Theta_p> [v*p]
"""
#
# some constants
from .constants import kappa
#
# pressure quantitites
pp0 = (p0/t[p])**kappa
# convert to potential temperature
t = t*pp0 # t = theta
# zonal means
v_bar = v.mean(lon)
t_bar = t.mean(lon) # t_bar = theta_bar
# prepare pressure derivative
dthdp = t_bar.differentiate(p,edge_order=2) # dthdp = d(theta_bar)/dp
dthdp = dthdp.where(dthdp != 0)
# time mean of d(theta_bar)/dp
if time in dthdp.dims:
if 'rolling' in ref:
r = int(ref.split('-')[-1])
dthdp = dthdp.rolling(dim={time:r},min_periods=1,center=True).mean()
elif ref == 'mean':
dthdp = dthdp.mean(time)
elif ref == 'instant':
dthdp = dthdp
# now get wave component
if isinstance(wave,list):
vpTp = GetWavesXr(v,t,dim=lon,wave=-1).sel(k=wave).sum('k')
elif wave == 0:
vpTp = (v - v_bar)*(t - t_bar)
vpTp = vpTp.mean(lon) # vpTp = bar(v'Th')
else:
vpTp = GetWavesXr(v,t,dim=lon,wave=wave) # vpTp = bar(v'Th'_{k=wave})
t_bar = vpTp/dthdp # t_bar = bar(v'Th')/(dTh_bar/dp)
#
return v_bar,t_bar
##############################################################################################
def eof(X,n=-1,detrend='constant',eof_in=None):
"""Principal Component Analysis / Empirical Orthogonal Functions / SVD
Uses Singular Value Decomposition to find the dominant modes of variability.
The field X can be reconstructed with Y = dot(EOF,PC) + X.mean(axis=time)
INPUTS:
X -- Field, shape (time x space).
n -- Number of modes to extract. All modes if n < 0
detrend -- detrend with global mean ('constant')
or linear trend ('linear')
eof_in -- If not None, compute PC by projecting eof onto X.
OUTPUTS:
EOF - Spatial modes of variability
PC - Temporal evolution of EOFs - only output if eof_in is not None
E - Explained value of variability
u - spatial modes
s - variances
v - temporal modes
"""
is_xr = False
try:
import xarray as xr
if isinstance(X,xr.DataArray):
is_xr = True
dims = []
for dim in X.dims[1:]:
dims.append(X[dim])
tdim = [X[X.dims[0]]]
X = X.values
except:
pass
import scipy.signal as sg
# make sure we have a matrix time x space
shpe = X.shape
if len(shpe) > 2:
X = X.reshape([shpe[0],np.prod(shpe[1:])])
if eof_in is not None:
if len(eof_in.shape) > 2:
eof_in = eof_in.reshape([np.prod(eof_in.shape[:-1]),eof_in.shape[-1]])
else:
eof_in = eof_in.reshape([np.prod(eof_in.shape),1])
# take out the time mean or trend
X = sg.detrend(X.transpose(),type=detrend)
if eof_in is not None:
if eof_in.shape[-1] == X.shape[0]:
PC = np.matmul(eof_in, X)
eof_norm = np.dot(eof_in.transpose(),eof_in)
return np.dot(PC,np.linalg.inv(eof_norm))
else:
PC = np.matmul(eof_in.transpose(), X)
eof_norm = np.dot(eof_in.transpose(),eof_in)
return np.dot(PC.transpose(),np.linalg.inv(eof_norm)).transpose()
# return sg.detrend(PC,type='constant')
# perform SVD - v is actually V.H in X = U*S*V.H
u,s,v = np.linalg.svd(X, full_matrices=False)
# now, u contains the spatial, and v the temporal structures
# s contains the variances, with the same units as the input X
# u.shape = (space, modes(space)), v.shape = (modes(space), time)
# get the first n modes, in physical units
# we can either project the data onto the principal component, X*V
# or multiply u*s. This is the same, as U*S*V.H*V = U*S
if n < 0:
n = s.shape[0]
EOF = np.dot(u[:,:n],np.diag(s)[:n,:n])
# time evolution is in v
PC = v[:n,:]
# EOF wants \lambda = the squares of the eigenvalues,
# but SVD yields \gamma = \sqrt{\lambda}
s2 = s*s
E = s2[:n]/sum(s2)
# now we need to make sure we get everything into the correct shape again
u = u[:,:n]
s = s[:n]
v = v.transpose()[:,:n]
if len(shpe) > 2:
# replace time dimension with modes at the end of the array
newshape = list(shpe[1:])+[n]
EOF = EOF.reshape(newshape)
u = u .reshape(newshape)
if is_xr: # return xarray dataarrays
mode = [('n',np.arange(1,n+1))]
EOF = xr.DataArray(EOF,coords=dims+mode,name='EOF')
PC = xr.DataArray(PC,coords=tdim+mode,name='PC')
E = xr.DataArray(E,coords=mode,name='E')
return EOF,PC,E,u,s,v
##############################################################################################
def ComputeAnnularMode(lat, pres, data, choice='z', hemi='infer', detrend='constant', eof_in=None, pc_in=None, eof_out=False, pc_out=False):
"""Compute annular mode as in Gerber et al, GRL 2008.
This is basically the first PC, but normalized to unit variance and zero mean.
To conform to Gerber et al (2008), `data` should be anomalous height or zonal wind
with respect to 30-day smoothed day of year climatology.
INPUTS:
lat - latitude
pres - pressure
data - variable to compute EOF from. This is typically
geopotential or zonal wind.
Size time x pres x lat (ie zonal mean)
choice - not essential, but used for sign convention.
If 'z', the sign is determined based on 70-80N/S.
Otherwise, 50-60N/S is used.
hemi - hemisphere to consider
'infer' - if mean(lat)>=0 -> NH, else SH
'SH' or 'NH'
detrend- detrend method for computing EOFs:
'linear' -> remove linear trend
'constant' -> remove total time mean
eof_in - if None, compute EOF1 as usual.
if the EOF1 is already known, use this instead of
computing it again.
pc_in - if None, standardize PC1 to its own mean and std deviation
else, use pc_in mean and std deviation to standardize.
eof_out- whether or not to pass the first EOF as output [False].
pc_out - whether or not to pass the first PC as output [False].
OUTPUT:
AM - The annular mode, size time x pres
EOF - The first EOF (if eof_out is True), size pres x lat
PC - The first PC (if pc_out is True). size time x pres
"""
#
AM = np.full((data.shape[0],data.shape[1]),np.nan)
if pc_out:
pco = np.full(AM.shape,np.nan)
# guess the hemisphere
if hemi == 'infer':
if np.mean(lat) >= 0:
sgn = 1.
else:
sgn = -1.
elif hemi == 'SH':
sgn = -1.
elif hemi == 'NH':
sgn = 1.
j_tmp = np.where(sgn*lat > 20)[0]
if eof_out:
eofo = np.full((data.shape[1],len(j_tmp)),np.nan)
coslat = np.cos(np.deg2rad(lat))
negCos = (coslat < 0.)
coslat[negCos] = 0.
# weighting as in Gerber et al GRL 2008
sqrtcoslat = np.sqrt(coslat[j_tmp])
# try to get the sign right
# first possibility
if choice == 'z':
minj = min(sgn*70,sgn*80)
maxj = max(sgn*80,sgn*70)
sig = -1
else:
minj = min(sgn*50,sgn*60)
maxj = max(sgn*60,sgn*50)
sig = 1
jj = (lat[j_tmp] > minj)*(lat[j_tmp] < maxj)
# second possibility
#jj = abs(lat[j_tmp]-80).argmin()
#sig = -1
if isinstance(pres,(int,float)):
data = np.reshape(data,(data.shape[0],1,data.shape[1]))
pres = [pres]
for k in range(len(pres)):
# remove global mean
globZ = GlobalAvg(lat,data[:,k,:],axis=-1,lim=lat[j_tmp[0]],mx=lat[j_tmp[-1]])
var = data[:,k,:] - globZ[:,np.newaxis]
# area weighting: EOFs are ~variance, thus take sqrt(cos)
var = var[:,j_tmp]*sqrtcoslat[np.newaxis,:]
varNan = np.isnan(var)
if np.sum(np.reshape(varNan,(np.size(varNan),)))==0:
if eof_in is None:
eof1,pc1,E,u,s,v = eof(var,n=1,detrend=detrend)
else:
pc1 = eof(var,n=1,detrend=detrend,eof_in=np.expand_dims(eof_in[k,:],-1))
eof1 = eof_in[k,:]
# force the sign of PC
pc1 = pc1*sig*np.sign(eof1[jj].mean())
if eof_out:
eofo[k,:] = np.squeeze(eof1)
if pc_out:
pco[:,k] = pc1
# force unit variance and zero mean
if pc_in is None:
AM[:,k] = (pc1-pc1.mean())/np.std(pc1)
else:
AM[:,k] = (pc1-pc_in.mean())/np.std(pc_in)
if eof_out and pc_out:
return AM,eofo,pco
elif eof_out:
return AM,eofo
elif pc_out:
return AM,pco
else:
return AM
##############################################################################################
def ComputeVstar(data, temp='temp', vcomp='vcomp', pfull='pfull', wave=-1, p0=1e3):
"""Computes the residual meridional wind v* (as a function of time).
INPUTS:
data - filename of input file, relative to wkdir, or dictionary with {T,v,pfull}
temp - name of temperature field in data
vcomp - name of meridional velocity field in data
pfull - name of pressure in inFile [hPa]
wave - decompose into given wave number contribution if wave>=0
p0 - pressure basis to compute potential temperature [hPa]
OUTPUTS:
vstar - residual meridional wind, as a function of time
"""
import netCDF4 as nc
a0 = 6371000
g = 9.81
# read input file
if isinstance(data,str):
print('Reading data')
update_progress(0)
#
inFile = nc.Dataset(data, 'r')
t = inFile.variables[temp][:]
update_progress(.45)
v = inFile.variables[vcomp][:]
update_progress(.90)
p = inFile.variables[pfull][:]
update_progress(1)
inFile.close()
#
v_bar,t_bar = ComputeVertEddy(v,t,p,p0,wave=wave)
else:
p = data[pfull]
v_bar,t_bar = ComputeVertEddy(data[vcomp],data[temp],p,p0,wave=wave)
# t_bar = bar(v'Th'/(dTh_bar/dp))
#
dp = np.gradient(p)[np.newaxis,:,np.newaxis]
vstar = v_bar - np.gradient(t_bar,edge_order=2)[1]/dp
return vstar
##############################################################################################
def ComputeWstar(data, slice='all', omega='omega', temp='temp', vcomp='vcomp', pfull='pfull', lat='lat', wave=[-1], p0=1e3):
"""Computes the residual upwelling w* as a function of time.
Input dimensions must be time x pres x lat x lon.
Output is either space-time (wave<0, dimensions time x pres x lat)
or space-time-wave (dimensions wave x time x pres x lat).
Output units are hPa/s, and the units of omega are expected to be hPa/s.
INPUTS:
data - filename of input file, or dictionary with (w,T,v,pfull,lat)
slice - time slice to work with (large memory requirements). Array [start,stop] or 'all'
omega - name of pressure velocity field in data [hPa/s]
temp - name of temperature field in data
vcomp - name of meridional velocity field in data
pfull - name of pressure in data [hPa]
lat - name of latitude in data [deg]
wave - decompose into given wave number contribution(s) if
len(wave)=1 and wave>=0, or len(wave)>1
p0 - pressure basis to compute potential temperature [hPa]
OUTPUTS:
residual pressure velocity, time x pfull x lat [and waves] [hPa/s]
"""
import netCDF4 as nc
a0 = 6371000.
# read input file
if isinstance(data,str):
inFile = nc.Dataset(data, 'r')
if slice == 'all':
slice=[0,inFile.variables[omega][:].shape[0]]
data = {}
data[omega] = inFile.variables[omega][slice[0]:slice[1],:]*0.01 # [hPa/s]
data[temp] = inFile.variables[temp][slice[0]:slice[1],:]
data[vcomp] = inFile.variables[vcomp][slice[0]:slice[1],:]
data[pfull] = inFile.variables[pfull][:] # [hPa]
data[lat] = inFile.variables[lat][:]
inFile.close()
# spherical geometry
pilat = data[lat]*np.pi/180.
coslat = np.cos(pilat)[np.newaxis,np.newaxis,:]
R = a0*coslat[np.newaxis,:]
R = 1./R
dphi = np.gradient(pilat)[np.newaxis,np.newaxis,:]
# compute thickness weighted meridional heat flux
shpe = data[omega].shape[:-1]
vt_bar = zeros((len(wave),)+shpe)
for w in range(len(wave)):
# w_bar is actually v_bar, but we don't need that
w_bar,vt_bar[w,:] = ComputeVertEddy(data[vcomp],data[temp],data[pfull],p0,wave=wave[w])
# weigh v'T' by cos\phi
vt_bar[w,:] = vt_bar[w,:]*coslat
# get the meridional derivative
vt_bar[w,:] = np.gradient(vt_bar[w,:],edge_order=2)[-1]/dphi
# compute zonal mean upwelling
w_bar = np.nanmean(data[omega],axis=-1)
# put it all together
if len(wave)==1:
return w_bar + np.squeeze(R*vt_bar)
else:
return w_bar + R*vt_bar
##############################################################################################
def ComputeWstarXr(omega, temp, vcomp, pres='level', lon='lon', lat='lat', time='time', ref='mean', p0=1e3, is_Pa='omega'):
"""Computes the residual upwelling w*. omega, temp, vcomp are xarray.DataArrays.
Output units are the same as the units of omega, and the pressure coordinate is expected in hPa, latitude in degrees.
INPUTS:
omega - pressure velocity. xarray.DataArray
temp - temperature. xarray.DataArray
vcomp - meridional velocity. xarray.DataArray
pfull - name of pressure coordinate.
lon - name of longitude coordinate
lat - name of latitude coordinate
time - name of time coordinate
ref - how to treat dTheta/dp:
- 'rolling-X' : centered rolling mean over X days
- 'mean' : full time mean
p0 - pressure basis to compute potential temperature [hPa]
is_Pa - correct for pressure units in variables:
- None: omega, p0 and pres are all in hPa or all in Pa
- 'omega': omega is in Pa/s but pres and p0 in hPa
- 'pres' : omega is in hPa/s, p0 in hPa, but pres in Pa
OUTPUTS:
residual pressure velocity, same units as omega
"""
import numpy as np
a0 = 6371000.
# spherical geometry
coslat = np.cos(np.deg2rad(omega[lat]))
R = a0*coslat
R = 1./R
# correct for units: hPa<->Pa
if is_Pa is not None:
if is_Pa.lower() == 'omega':
R = R*100
elif is_Pa.lower() == 'pres':
R = R*0.01
p0 = p0*100
# correct for units: degrees<->radians
R = R*180/np.pi
# compute thickness weighted meridional heat flux
_,vt_bar = ComputeVertEddyXr(vcomp, temp, pres, p0, lon, time, ref)
# get the meridional derivative
vt_bar = (coslat*vt_bar).differentiate(lat)
# compute zonal mean upwelling
w_bar = omega.mean(lon)
# put it all together
return w_bar + R*vt_bar
##############################################################################################
def ComputeEPfluxDiv(lat,pres,u,v,t,w=None,do_ubar=False,wave=0):
""" Compute the EP-flux vectors and divergence terms.
The vectors are normalized to be plotted in cartesian (linear)
coordinates, i.e. do not include the geometric factor a*cos\phi.
Thus, ep1 is in [m2/s2], and ep2 in [hPa*m/s2].
The divergence is in units of m/s/day, and therefore represents
the deceleration of the zonal wind. This is actually the quantity
1/(acos\phi)*div(F).
INPUTS:
lat - latitude [degrees]
pres - pressure [hPa]
u - zonal wind, shape(time,p,lat,lon) [m/s]
v - meridional wind, shape(time,p,lat,lon) [m/s]
t - temperature, shape(time,p,lat,lon) [K]
w - pressure velocity, optional, shape(time,p,lat,lon) [hPa/s]
do_ubar - compute shear and vorticity correction? optional
wave - only include this wave number. total if == 0, all waves if <0, single wave if >0, sum over waves if a list. optional
OUTPUTS:
ep1 - meridional EP-flux component, scaled to plot in cartesian [m2/s2]
ep2 - vertical EP-flux component, scaled to plot in cartesian [hPa*m/s2]
div1 - horizontal EP-flux divergence, divided by acos\phi [m/s/d]
div2 - horizontal EP-flux divergence , divided by acos\phi [m/s/d]
"""
# some constants
from .constants import Rd,cp,kappa,p0,Omega,a0
# geometry
pilat = lat*np.pi/180
dphi = np.gradient(pilat)[np.newaxis,np.newaxis,:]
coslat= np.cos(pilat)[np.newaxis,np.newaxis,:]
sinlat= np.sin(pilat)[np.newaxis,np.newaxis,:]
R = 1./(a0*coslat)
f = 2*Omega*sinlat
pp0 = (p0/pres[np.newaxis,:,np.newaxis])**kappa
dp = np.gradient(pres)[np.newaxis,:,np.newaxis]
if wave < 0:
dp = np.expand_dims(dp ,-1)
#
# absolute vorticity
if do_ubar:
ubar = np.nanmean(u,axis=-1)
fhat = R*np.gradient(ubar*coslat,edge_order=2)[-1]/dphi
else:
fhat = 0.
fhat = f - fhat # [1/s]
#
# add wavenumber dimension if needed
if wave < 0:
fhat = np.expand_dims(fhat,-1)
coslat = np.expand_dims(coslat,-1)
sinlat = np.expand_dims(sinlat,-1)
dphi = np.expand_dims(dphi,-1)