-
Notifications
You must be signed in to change notification settings - Fork 237
/
check_mom_budget.py
374 lines (322 loc) · 11.7 KB
/
check_mom_budget.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
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
######################## -*- coding: utf-8 -*-
"""Usage: python ./check_mom_budget.py
"""
import sys, os
import matplotlib.pyplot as plt
import numpy as np
try:
from MITgcmutils import rdmds
except:
# this hack to make sure that MITgcmutils.rdmds is available assumes
# that we are somewhere within the MITgcm/verification directory
import re
cwdstr = os.getcwd()
dirpath = cwdstr[:re.search("verification",cwdstr).start()]
sys.path.append(os.path.join(dirpath,'utils/python/MITgcmutils') )
from MITgcmutils import rdmds
rDir, nit, deltaT = "../tr_run.thsice/", 36010, 86400
#rDir, nit, deltaT = "../tr_run.viscA4/", 86405, 3600
namF, namFs = 'momDiag', 'srfDiag'
class gridLoader:
"""a hack to mimic a matlab struct"""
def __init__(self, gDir):
self.xC = rdmds(os.path.join(gDir,'XC'))
self.yC = rdmds(os.path.join(gDir,'YC'))
self.xG = rdmds(os.path.join(gDir,'XG'))
self.yG = rdmds(os.path.join(gDir,'YG'))
self.dXc=rdmds(os.path.join(gDir,'DXC'))
self.dYc=rdmds(os.path.join(gDir,'DYC'))
self.dXg=rdmds(os.path.join(gDir,'DXG'))
self.dYg=rdmds(os.path.join(gDir,'DYG'))
self.dRf=np.squeeze(rdmds(os.path.join(gDir,'DRF')))
self.rAc=rdmds(os.path.join(gDir,'RAC'))
self.rAw=rdmds(os.path.join(gDir,'RAW'))
self.rAs=rdmds(os.path.join(gDir,'RAS'))
self.rAz=rdmds(os.path.join(gDir,'RAZ'))
self.hFacC=rdmds(os.path.join(gDir,'hFacC'))
self.hFacW=rdmds(os.path.join(gDir,'hFacW'))
self.hFacS=rdmds(os.path.join(gDir,'hFacS'))
self.depth=rdmds(os.path.join(gDir,'Depth'))
def readdiags(fname,nit):
v,iter,M=rdmds(os.path.join(rDir,fname), nit, returnmeta = True);
fList=M['fldlist']
n=len(fList)
return v, n, fList
def split_C_cub(v3d):
""" v6t = split_C_cub(v3d)
--------------------------------------------
split 2d/3d arrays V, center, to 2d/3d x 6 faces
and add 1 column + 1 row <== at the begining !!!
=> output is v6t[nr,ny+1,ny+1,6]
"""
kad=1
dims = v3d.shape
nx,ny = dims[-1],dims[-2]
if len(dims) == 2: nr = 1
else: nr = np.prod(dims[:-2])
nyp=ny+1; n2p=ny+2; nye=ny+kad
v = v3d.reshape((nr,ny,nx))
v6t = np.zeros((nr,nye,nye,6))
for n in range(6):
v6t[:,1:,1:,n]=v[:,:,n*ny:(n+1)*ny]
v6t[:,1:,0, 0]=v6t[:,-1,:0:-1,4]
v6t[:,1:,0, 2]=v6t[:,-1,:0:-1,0]
v6t[:,1:,0, 4]=v6t[:,-1,:0:-1,2]
v6t[:,1:,0, 1]=v6t[:,1:,-1,0]
v6t[:,1:,0, 3]=v6t[:,1:,-1,2]
v6t[:,1:,0, 5]=v6t[:,1:,-1,4]
v6t[:,0, :, 0]=v6t[:,-1,:,5]
v6t[:,0, :, 2]=v6t[:,-1,:,1]
v6t[:,0, :, 4]=v6t[:,-1,:,3]
v6t[:,0,1:, 1]=v6t[:,:0:-1,-1,5]
v6t[:,0,1:, 3]=v6t[:,:0:-1,-1,1]
v6t[:,0,1:, 5]=v6t[:,:0:-1,-1,3]
v6t[:,0,0,1]=v6t[:,1,-1,0]
v6t[:,0,0,3]=v6t[:,1,-1,2]
v6t[:,0,0,5]=v6t[:,1,-1,4]
return v6t
def calc_grad(fld,dx,dy):
"""calculate gradient of 6-tiled fields fld[nr,ny+1,ny+1,6]
and return as (dfx[nr,ny,ncx], dfy[nr,ny,ncx])
"""
nnr, np1 = fld.shape[:2]
nc = np1-1
myshape = (1,G.dXc.shape[0],G.dXc.shape[1])
dfx = (fld[:,:,1:,:]-fld[:,:,:-1,:])[:,1:,:,:] \
.reshape((nnr,nc,nc*6),order='F') \
/np.tile(dx.reshape(myshape),(nnr,1,1))
dfy = (fld[:,1:,:,:]-fld[:,:-1,:,:])[:,:,1:,:] \
.reshape((nnr,nc,nc*6),order='F') \
/np.tile(dy.reshape(myshape),(nnr,1,1))
return dfx, dfy
def getListIndex(diagName,fldLst):
"""Return index of diagName in fldlst (list of diagnostics names);
if diagName is not in fldlist, return -1
"""
if diagName in str(fldLst):
j = fldLst.index(diagName)
else:
j = -1
return j
def printstats(var,varName):
fmt='Var = %8s : Min,Max,Avr,StD= %12.5e %12.5e %12.5e %12.5e'
print(fmt % (varName, var.min(), var.max(), var.mean(), var.std()))
return
def printsum(var,res):
fmt = ' Sum Tend: Avr,StD= %12.5e %12.5e ; Residual= %12.5e %12.5e +';
print(fmt % (var.mean(), var.std(), res.mean(), res.std()))
return
def printStatsAndSum(fldLst,dtot,gtot):
"""For each of the terms in fldLst
a) print some stats of this term
b) add to other tendency and print stats of the sum
c) substract the sum from total tendency (-> residual) and print stats
"""
for fldName in fldLst:
j = getListIndex(fldName,fldList)
if j > -1:
var = np.copy(np.squeeze(v4d[j,:,:,:]))
elif "m_ImplD" in fldName:
# U/Vm_ImpD was not found. Now we have to do something different
print(fldName+" was not found, trying alternative",end = " ")
if 'Um' in fldName:
if juNz>-1: j, var = juNz, gUnuZ
elif 'Vm' in fldName:
if jvNz>-1: j, var = jvNz, gVnuZ
if j==-1: print("... unsuccessfull")
if j>-1:
printstats(var,fldList[j])
gtot=gtot+var
printsum(gtot,dtot-gtot)
else:
print('... cannot use '+fldName)
return
# let's go
# first establish the grid parameters that we are going to need
G = gridLoader(rDir)
nr, nc = G.hFacC.shape[:2]
nPxy = G.hFacC.shape[2]*nc
nPp2 = nPxy+2;
ncx = 6*nc
np1 = nc+1;
mskW=np.minimum(np.ceil(G.hFacW),1); mskS=np.minimum(np.ceil(G.hFacS),1);
# set constants
rhoConst=1035.
gravity =9.81
# Read in 2-D diagnostics file "namFs" and 3-D diagnostics file "namF":
v3d,nV2d,f2dList = readdiags(namFs,nit)
v4d,nV, fldList = readdiags(namF,nit)
if nV2d == 0: f2dList=fldList
# compute the horizontal pressure gradient terms in case we need them
if 'PHI_SURF' in str(f2dList):
jdps = f2dList.index('PHI_SURF')
var = v3d[jdps,:,:]
elif 'ETAN' in str(f2dList):
jdps = f2dList.index('ETAN')
var = gravity*np.copy(v3d[jdps,:,:])
else:
jdps = -1
if jdps > -1:
dpx, dpy = calc_grad(- split_C_cub(var),G.dXc,G.dYc)
# horizontal non-hydrostatic pressure gradients terms
jnh = -1
fileName='%s.%10.10i.%s' % (os.path.join(rDir,'pnhDiag'),nit+1,'data')
if os.path.isfile(fileName):
print(' -- loading file: %s ...' % fileName)
var=rdmds(os.path.join(rDir,'pnhDiag'),nit+1)
print(' done')
elif 'PHI_NH' in str(fldList):
jnh = fldList.index('PHI_NH')
var=np.copy(v4d[jnh,:,:,:])
if jnh > -1:
dpNHx, dpNHy = calc_grad(- split_C_cub(var),G.dXc,G.dYc)
dpNHx=dpNHx*mskW
dpNHy=dpNHy*mskS
# when using z* with older output, need to account for
# column vertical streaching in computation of vertical
# viscosity tendency form vertical viscous flux 'VISrI_Um'
if 'ETAN' in str(f2dList):
jeta = f2dList.index('ETAN')
v6t = split_C_cub(v3d[jeta,:,:]*G.rAc)
vbx = 0.5*(v6t[:,:,1:,:]+v6t[:,:,:-1,:])[:,1:,:,:] \
.reshape((1,nc,nc*6),order='F')/G.rAw
vby = 0.5*(v6t[:,1:,:,:]+v6t[:,:-1,:,:])[:,:,1:,:] \
.reshape((1,nc,nc*6),order='F')/G.rAs
d6t = split_C_cub(G.depth)
hhx = np.minimum(d6t[:,:,1:,:],d6t[:,:,:-1,:])[:,1:,:,:] \
.reshape((1,nc,nc*6),order='F')
hhy = np.minimum(d6t[:,1:,:,:],d6t[:,:-1,:,:])[:,:,1:,:] \
.reshape((1,nc,nc*6),order='F')
hhx[hhx==0.]=np.Inf
rFacW=vbx/hhx + np.ones((nc,ncx))
hhy[hhy==0.]=np.Inf
rFacS=vby/hhy + np.ones((nc,ncx))
else:
jdps = -1
#-------------------------------------------------------------------------------
# horizontal gradients of the potential Phi, this can be derived from
# different diagnostics depending on their availability
gUdp, gVdp = np.zeros((nr,nc,ncx)), np.zeros((nr,nc,ncx))
titUdp, titVdp = ' ? ', ' ? '
jdph=-1
j1=getListIndex('Um_dPhiX',fldList)
j2=getListIndex('Vm_dPhiY',fldList)
if j1==-1 & j2==-1:
jdph=-1;
j1=getListIndex('Um_dPHdx',fldList)
j2=getListIndex('Vm_dPHdy',fldList)
if j1>-1: jdph=j1
elif j2>-1: jdph=j2
if jdph > -1 & jdps > -1:
gUdp=dpx.repmat((nr,1,1))*mskW;
gVdp=dpy.repmat((nr,1,1))*mskS;
if jnh > -1: gUdp=gUdp+dpNHx; gVdp=gVdp+dpNHy
else:
if j1==-1: jdph=j2
else: jdph=j1
if jdph > -1:
if j1 > -1:
gUdp=gUdp+np.squeeze(v4d[j1,:,:,:])
titUdp=fldList[j1]
if j2 > -1:
gVdp=gVdp+np.squeeze(v4d[j2,:,:,:])
titVdp=fldList[j2]
if jdps > -1:
titUdp=titUdp[:-1]+titUdp[-1].upper()
titVdp=titVdp[:-1]+titVdp[-1].upper()
#print(' titUdp: >%s< ; titVdp: >%s<\n' %(titUdp,titVdp))
#-- Tendencies from implicit vertical viscous fluxes
# Note: will be used to close momentum budget
# a) if using older output (since 'Um_ImplD' was not there);
# b) and using implicit viscosity but without implicit bottom friction
# In the latest case (selectImplicitDrag=2,) cannot close the budget
# using older output
juNz = getListIndex('VISrI_Um',fldList)
jvNz = getListIndex('VISrI_Vm',fldList)
if juNz>-1 or jvNz>-1:
print(' -- Tendencies from vertically visc. fluxes --')
if juNz>-1:
var=np.copy(np.squeeze(v4d[juNz,:,:,:]))
# compute tendency from minus div of vert. fluxes:
div=np.copy(var); div[:-1,:,:]=div[:-1,:,:]-var[1:,:,:]
ddz=G.hFacW*np.tile(G.dRf.reshape((nr,1,1)),(1,nc,ncx))
rdz=np.copy(ddz); rdz[ddz!=0]=1./rdz[ddz!=0]
gUnuZ= - div*rdz/np.tile(G.rAw*rFacW,(nr,1,1))
printstats(gUnuZ,fldList[juNz])
#--
jj = getListIndex('Um_ImplD',fldList)
if jj > -1:
var=np.copy(np.squeeze(v4d[jj,:,:,:]))
printstats(var,fldList[jj])
var = var - gUnuZ
printstats(var,'Diff:2-1')
print()
if jvNz>-1:
var=np.copy(np.squeeze(v4d[jvNz,:,:,:]))
# compute tendency from minus div of vert. fluxes:
div=np.copy(var); div[:-1,:,:]=div[:-1,:,:]-var[1:,:,:]
ddz=G.hFacS*np.tile(G.dRf.reshape((nr,1,1)),(1,nc,ncx))
rdz=np.copy(ddz); rdz[ddz!=0]=1./rdz[ddz!=0]
gVnuZ= - div*rdz/np.tile(G.rAs*rFacS,(nr,1,1))
printstats(gVnuZ,fldList[jvNz])
#--
jj = getListIndex('Vm_ImplD',fldList)
if jj > -1:
var=np.copy(np.squeeze(v4d[jj,:,:,:]))
printstats(var,fldList[jj])
var = var - gVnuZ
printstats(var,'Diff:2-1')
print()
# Here we check that vertical integral of implicit vertical viscous tendency
# match either bottom drag (if using implicit bottom drag) or simply zero.
j1 = getListIndex('Um_ImplD',fldList)
j2 = getListIndex('botTauX' ,f2dList)
if j1>-1 & j2>-1:
print(' -- Vertically integrated tendencies --');
bTauX = np.copy(v3d[j2,:,:])
printstats(bTauX,f2dList[j2])
var=np.copy(np.squeeze(v4d[j1,:,:,:]))
# vertical integration:
ddz=G.hFacW*np.tile(G.dRf.reshape((nr,1,1)),(1,nc,ncx))
var=rhoConst*((var*ddz).sum(axis=0))*rFacW
printstats(var,fldList[j1])
printstats(var-bTauX,'Diff:2-1')
print()
j1 = getListIndex('Vm_ImplD',fldList)
j2 = getListIndex('botTauY' ,f2dList)
if j1>-1 & j2>-1:
bTauY = np.copy(v3d[j2,:,:])
printstats(bTauY,f2dList[j2])
var=np.copy(np.squeeze(v4d[j1,:,:,:]))
# vertical integration:
ddz=G.hFacS*np.tile(G.dRf.reshape((nr,1,1)),(1,nc,ncx))
var=rhoConst*((var*ddz).sum(axis=0))*rFacS
printstats(var,fldList[j1])
printstats(var-bTauY,'Diff:2-1')
print()
# this is where the actual momentum budget check starts
print(' -- Check Mom budget, exp: %s, files: %s & %s, it= %i'
% (rDir,namF,namFs,nit))
j = getListIndex('TOTUTEND',fldList)
if j > -1:
dUtot=np.copy(np.squeeze(v4d[j,:,:,:]))/86400.
printstats(dUtot,fldList[j])
j = getListIndex('Um_dPhiX',fldList)
if j == -1: j = getListIndex('Um_dPHdx',fldList)
if j >-1:
printstats(gUdp,titUdp)
gUtot=gUdp
printStatsAndSum(['Um_Advec','Um_Ext','Um_Diss','Um_ImplD','AB_gU'],dUtot,gUtot)
print()
j = getListIndex('TOTVTEND',fldList)
if j > -1:
dVtot=np.copy(np.squeeze(v4d[j,:,:,:]))/86400.
printstats(dVtot,fldList[j])
j = getListIndex('Vm_dPhiY',fldList)
if j == -1: j = getListIndex('Vm_dPHdy',fldList)
if j > -1:
printstats(gVdp,titVdp)
gVtot=gVdp
printStatsAndSum(['Vm_Advec','Vm_Ext','Vm_Diss','Vm_ImplD','AB_gV'],dVtot,gVtot)