def plot_cb_pym6(initializer,perc=99): budgetlist = extract_cb_terms_pym6(initializer) with mfdset(initializer.fil) as fh, mfdset(initializer.fil2) as fh2: e = gv('e',budgetlist[0].dom,'hi',fh2).read_array() plot_kwargs = dict(cmap='RdBu_r') plotter_kwargs = dict(zcoord=True,z=initializer.z,e=e,isop_mean=True) fig = Plotter.budget_plot(budgetlist,initializer.meanax, plot_kwargs=plot_kwargs,ncols=3, plotter_kwargs=plotter_kwargs, perc=perc,individual_cbars=False) return fig
def plotzetaanimation(geofil, fil, savfil=None, fig=None, wlon=-25, elon=0, slat=10, nlat=60, zs=0, ze=1, fps=5, bitrate=1000, **plotkwargs): fhgeo = dset(geofil) fh = mfdset(fil) ani = animatezeta(fhgeo, fh, fig=fig, wlon=wlon, elon=elon, slat=slat, nlat=nlat, zs=zs, ze=ze, **plotkwargs) if savfil: mywriter = animation.FFMpegWriter(fps=fps, bitrate=bitrate) ani.save(savfil + '.mp4', writer=mywriter) else: plt.show() fh.close() fhgeo.close()
def extract_cb_terms_pym6(initializer): domain = Domain.Domain(initializer) with mfdset(initializer.fil) as fh, mfdset(initializer.fil2) as fh2: vhy = gv('vh',domain,'vl',fh2,fh,plot_loc='hl').ysm().read_array(filled=0).ddx(2,div_by_area=True) uhx = gv('uh',domain,'ul',fh2,fh,plot_loc='hl').xsm().read_array(filled=0).ddx(3,div_by_area=True) wd = gv('wd',domain,'hi',fh2).read_array().o1diff(1) # budgetlist = [-uhx*(1/domain.dyT[uhx._slice[2:]]),-vhy*(1/domain.dxT[vhy._slice[2:]]),-wd] budgetlist = [-uhx,-vhy,-wd] lab = [ r'$-(\bar{h}\hat{u})_{\tilde{x}}$', r'$-(\bar{h}\hat{v})_{\tilde{y}}$', r'$-(\bar{h}\hat{\varpi})_{\tilde{b}}$'] for i,var in enumerate(budgetlist): var.name = lab[i] return budgetlist
def __init__(self, expt, **kwargs): fh = mfdset(expt.fil0) self.file_ = expt.fil0 self.filemean_ = expt.fil2 self.x = fh.variables['xh'][:] self.y = fh.variables['yh'][:] self.zi = fh.variables['zi'][:] self.zl = fh.variables['zl'][:] self.z = kwargs.get('z', np.linspace(-3000, -1)) self.e = fh.variables['e'] self.u = fh.variables['u'] self.v = fh.variables['v'] self.geometry = expt.geometry #self.toffset = expt.toffset fhmean = mfdset(expt.fil2) self.emean = np.mean(fhmean.variables['e'][:], axis=0, keepdims=True) fhmean.close()
def getuvhe(filename,i): fh = mfdset(filename) h = fh.variables['h'][i,:,:,:] e = fh.variables['e'][i,:,:,:] el = (e[0:-1,:,:] + e[1:,:,:])/2; u = fh.variables['u'][i,:,:,:] v = fh.variables['v'][i,:,:,:] fh.close() return (u,v,h,e,el)
def getcontterms(filename,i): fh = mfdset(filename) dhdt = fh.variables['dhdt'][i,:,:,:] uh = fh.variables['uh'][i,:,:,:] vh = fh.variables['vh'][i,:,:,:] wd = fh.variables['wd'][i,:,:,:] uhgm = fh.variables['uhGM'][i,:,:,:] vhgm = fh.variables['vhGM'][i,:,:,:] fh.close() return (dhdt,uh,vh,wd,uhgm,vhgm)
def getoceanstats(filename): fh = mfdset(filename) layer = fh.variables['Layer'][:] interface = fh.variables['Interface'][:] time = fh.variables['Time'][:] en = fh.variables['En'][:] ape = fh.variables['APE'][:] ke = fh.variables['KE'][:] maxcfltrans = fh.variables['max_CFL_trans'][:] maxcfllin = fh.variables['max_CFL_lin'][:] return (layer,interface,time), (en,ape,ke), (maxcfltrans,maxcfllin)
def plot_wf_spectrum_vort(initializer, perc=99): domain = Domain.Domain(initializer) with mfdset(initializer.fil) as fh: e = gv('e', domain, 'hi', fh, plot_loc='qi').xsm().ysm().read_array( tmean=False, extend_kwargs=dict(method='mirror')).move_to('ui').move_to('qi') uy = gv('u', domain, 'ul', fh, plot_loc='ql').yep().read_array( tmean=False, filled=0, extend_kwargs=dict(method='vorticity')).ddx(2) vx = gv('v', domain, 'vl', fh, plot_loc='ql').xep().read_array( tmean=False, filled=0, extend_kwargs=dict(method='vorticity')).ddx(3) vort = (vx - uy).toz([-1], e=e) vort.name = '' fig, ax = plt.subplots(1, 2) vort.plot('nanmean', initializer.meanax, perc=98, contour=False, cbar=True, plot_kwargs=dict(cmap='RdBu_r'), ax=ax[0]) initializer.ls = 0 initializer.le = None domain1 = Domain.Domain(initializer) h = gv('e', domain1, 'hi', fh).read_array().o1diff(1).values omega = 2 * np.pi * (1 / 24 / 3600 + 1 / 365 / 24 / 3600) lr = np.sum( np.sqrt(h * domain.db) / np.pi / (2 * omega * np.sin(np.radians(0.5 * (initializer.slat + initializer.nlat)))), axis=1, keepdims=True) lr = np.mean(lr, axis=(0, 1, 2, 3)).squeeze() sig = vort.mean(axis=2).values.squeeze() fx, fx1, ft, Rsq = cross_spectrum(sig, 5 * 24 * 3600, 4000) vmax = np.percentile(Rsq, 99.9) im = ax[1].pcolormesh(fx1, ft, Rsq, cmap='Reds', vmin=0, vmax=vmax) fig.colorbar(im, ax=ax[1]) beta = 2 * omega * np.cos( np.radians(0.5 * (initializer.slat + initializer.nlat))) / domain.R_earth w = -beta * fx / (fx**2 + lr**-2) ax[1].plot(-fx, -w, 'k') return fig, ax
def getdims(filename): fh = mfdset(filename) xq = fh.variables['xq'][:] yq = fh.variables['yq'][:] time = fh.variables['Time'][:] xh = fh.variables['xh'][:] yh = fh.variables['yh'][:] zi = fh.variables['zi'][:] zl = fh.variables['zl'][:] fh.close() return (xh,yh), (xq,yq), (zi,zl), time
def getmomxterms(filename,i): fh = mfdset(filename) dudt = fh.variables['dudt'][i,:,:,:] cau = fh.variables['CAu'][i,:,:,:] pfu = fh.variables['PFu'][i,:,:,:] dudtvisc = fh.variables['du_dt_visc'][i,:,:,:] diffu = fh.variables['diffu'][i,:,:,:] dudtdia = fh.variables['dudt_dia'][i,:,:,:] gkeu = fh.variables['gKEu'][i,:,:,:] rvxv = fh.variables['rvxv'][i,:,:,:] fh.close() return (dudt,cau,pfu,dudtvisc,diffu,dudtdia,gkeu,rvxv)
def getmomyterms(filename,i): fh = mfdset(filename) dvdt = fh.variables['dvdt'][i,:,:,:] cav = fh.variables['CAv'][i,:,:,:] pfv = fh.variables['PFv'][i,:,:,:] dvdtvisc = fh.variables['dv_dt_visc'][i,:,:,:] diffv = fh.variables['diffv'][i,:,:,:] dvdtdia = fh.variables['dvdt_dia'][i,:,:,:] gkev = fh.variables['gKEv'][i,:,:,:] rvxu = fh.variables['rvxu'][i,:,:,:] fh.close() return (dvdt,cav,pfv,dvdtvisc,diffv,dvdtdia,gkev,rvxu)
def plotsshanim(geofil, fil, desfps, savfil=None): D, (ah, aq), (dxcu, dycu, dxcv, dycv, dxbu, dybu, dxt, dyt), f = rdp.getgeom(geofil) (xh, yh), (xq, yq), (zi, zl), time = rdp.getdims(fil) print(len(time)) nx = len(xh) ny = len(yh) nz = len(zl) nzp1 = len(zi) nt = len(time) fh = mfdset(fil) e1 = fh.variables['e'][:, 0, :, :] emax = np.ceil(np.amax(np.abs(e1))) e = fh.variables['e'][0, :, :, :] fh.close() xlim = [-25, 0] # actual values of x in degrees ylim = [10, 50] # actual values of y in degrees zlim = [0, 1] # indices of zl or zi (X, Y, P, Pmn, Pmx), (xs, xe), (ys, ye) = sliceDomain(e, e, xlim[0], xlim[-1], ylim[0], ylim[-1], zlim[0], zlim[-1], xq, yh, zi, 0) # X,Y,P,Pmn,Pmx = plotrange(e,xlim[0],xlim[-1], # ylim[0],ylim[-1], # zlim[0],zlim[-1],xh,yh,zi,e,0) fig = plt.figure() ax = plt.axes() Vctr = np.linspace(-emax, emax, num=12, endpoint=True) Vcbar = (Vctr[1:] + Vctr[:-1]) / 2 im = ax.contourf(X, Y, P, Vctr, cmap=plt.cm.RdBu_r) cbar = plt.colorbar(im, ticks=Vcbar) ani = animation.FuncAnimation(fig, update_contour_plot, frames=range(nt), fargs=(fil, ax, fig, xlim, ylim, zlim, xh, yh, zi, 0, emax)) if savfil: ani.save(savfil + '.mp4', writer="ffmpeg", fps=desfps, extra_args=['-vcodec', 'libx264']) else: plt.show() #plt.close(fig) plt.close('all')
def update_contour_plot(i,fil,ax,fig,xlim,ylim,zlim,x,y,z,meanax): fh = mfdset(fil) var = fh.variables['e'][i,:,:,:] fh.close() X,Y,P,Pmn,Pmx = plotrange(var,xlim[0],xlim[-1], ylim[0],ylim[-1], zlim[0],zlim[-1],x,y,z,var,meanax) ax.cla() Vctr = np.linspace(-0.6,0.6,num=12,endpoint=True) im = ax.contourf(X, Y, P, Vctr, cmap=plt.cm.RdBu_r) plt.title(str(i)) print(i) return im,
def extract_northward_transport(geofil,vgeofil,fil,fil2,xstart,xend,ystart,yend,zs,ze,meanax): keepax = () for i in range(4): if i not in meanax: keepax += (i,) fhgeo = dset(geofil) fh = mfdset(fil) zi = rdp1.getdims(fh)[2][0] dbl = -np.diff(zi)*9.8/1031 (xs,xe),(ys,ye),dimv = rdp1.getlatlonindx(fh,wlon=xstart,elon=xend, slat=ystart, nlat=yend,zs=zs,ze=ze,yhyq='yq') dxcv = rdp1.getgeombyindx(fhgeo,xs,xe,ys,ye)[2][2] f = rdp1.getgeombyindx(fhgeo,xs,xe,ys,ye)[-1] nt_const = dimv[0].size fhgeo.close() vh = fh.variables['vh'][0:,zs:ze,ys:ye,xs:xe]/dxcv fh2 = mfdset(fil2) h = fh2.variables['h_Cv'][0:,zs:ze,ys:ye,xs:xe] fh2.close() fh.close() vh = vh.filled(0) vhplus = np.where(vh>0,vh,0) vhminus = np.where(vh<0,vh,0) R = 6378 #lr = np.sum(np.sqrt(-h*dbl[:,np.newaxis,np.newaxis])/np.pi/f/1e3,axis=1,keepdims=True)/np.radians(R) lr = np.sum(np.sqrt(-h*dbl[:,np.newaxis,np.newaxis])/np.pi/f/1e3,axis=1,keepdims=True)/np.radians(R*np.cos(np.radians(dimv[2][:,np.newaxis]))) lr = np.mean(lr,axis=0).squeeze() terms = np.ma.concatenate(( vhplus[:,:,:,:,np.newaxis], vhminus[:,:,:,:,np.newaxis]),axis=4) termsm = np.ma.apply_over_axes(np.mean, terms, meanax) termsm = termsm.squeeze() X = dimv[keepax[1]] Y = dimv[keepax[0]] return X,Y, termsm, lr
def update_contour_plot(i, fil, ax, fig, xlim, ylim, zlim, x, y, z, meanax, emax): fh = mfdset(fil) var = fh.variables['e'][i, :, :, :] fh.close() (X, Y, P, Pmn, Pmx), (xs, xe), (ys, ye) = sliceDomain(var, var, xlim[0], xlim[-1], ylim[0], ylim[-1], zlim[0], zlim[-1], x, y, z, 0) # X,Y,P,Pmn,Pmx = plotrange(var,xlim[0],xlim[-1], # ylim[0],ylim[-1], # zlim[0],zlim[-1],x,y,z,var,meanax) ax.cla() Vctr = np.linspace(-emax, emax, num=12, endpoint=True) im = ax.contourf(X, Y, P, Vctr, cmap=plt.cm.RdBu_r) plt.title(str(i)) #print(i) sys.stdout.write('\r' + str(i)) sys.stdout.flush() return im,
def plotsshanim(geofil,fil,desfps,savfil=None): D, (ah,aq), (dxcu,dycu,dxcv,dycv,dxbu,dybu,dxt,dyt) = rdp.getgeom(geofil) (xh,yh), (xq,yq), (zi,zl), time = rdp.getdims(fil) print(len(time)) nx = len(xh) ny = len(yh) nz = len(zl) nzp1 = len(zi) nt = len(time) fh = mfdset(fil) e1 = fh.variables['e'][:,0,:,:] emax = np.ceil(np.amax(np.abs(e1))) e = fh.variables['e'][0,:,:,:] fh.close() xlim = [-25,0] # actual values of x in degrees ylim = [10,50] # actual values of y in degrees zlim = [0,1] # indices of zl or zi X,Y,P,Pmn,Pmx = plotrange(e,xlim[0],xlim[-1], ylim[0],ylim[-1], zlim[0],zlim[-1],xh,yh,zi,e,0) fig = plt.figure() ax = plt.axes() Vctr = np.linspace(-emax,emax,num=12,endpoint=True) Vcbar = (Vctr[1:] + Vctr[:-1])/2 im = ax.contourf(X, Y, P, Vctr, cmap=plt.cm.RdBu_r) cbar = plt.colorbar(im, ticks=Vcbar) ani = animation.FuncAnimation(fig,update_contour_plot,frames=range(nt), fargs=(fil,ax,fig,xlim,ylim,zlim,xh,yh,zi,0)) if savfil: ani.save(savfil+'.mp4', writer="avconv", fps=desfps, extra_args=['-vcodec', 'libx264']) else: plt.show() plt.close(fig)
def plot_wf_spectrum(initializer, perc=99): domain = Domain.Domain(initializer) with mfdset(initializer.fil) as fh: e = gv('e', domain, 'hi', fh).read_array(tmean='anom') fig, ax = plt.subplots(1, 2) e.plot('nanmean', initializer.meanax, ax=ax[0], cbar=True, contour=False, plot_kwargs=dict(cmap='RdBu_r')) initializer.ls = 0 initializer.le = None domain1 = Domain.Domain(initializer) h = gv('e', domain1, 'hi', fh).read_array().o1diff(1).values omega = 2 * np.pi * (1 / 24 / 3600 + 1 / 365 / 24 / 3600) lr = np.sum( np.sqrt(h * domain.db) / np.pi / (2 * omega * np.sin(np.radians(0.5 * (initializer.slat + initializer.nlat)))), axis=1, keepdims=True) lr = np.mean(lr, axis=(0, 1, 2, 3)).squeeze() sig = e.mean(axis=2).values.squeeze() fx, fx1, ft, Rsq = cross_spectrum(sig, 5 * 24 * 3600, 4000) vmax = np.percentile(Rsq, 99.9) im = ax[1].pcolormesh(fx1, ft, Rsq, cmap='Reds', vmin=0, vmax=vmax) fig.colorbar(im, ax=ax[1]) beta = 2 * omega * np.cos( np.radians(0.5 * (initializer.slat + initializer.nlat))) / domain.R_earth w = -beta * fx / (fx**2 + lr**-2) ax[1].plot(-fx, -w, 'k') return fig, ax
def get_heddy_coeffs_fromflx(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs=0, ze=None, z=np.linspace(-3000, 0, 100), perc=5, htol=1e-3): fhgeo = dset(geofil) fhvgeo = dset(vgeofil) fh = mfdset(fil) fh2 = mfdset(fil2) db = fhvgeo.variables['g'][:] fhvgeo.close() dbi = np.append(db, 0) zi = fh.variables['zi'][:] zl = fh.variables['zl'][:] dbl = np.diff(zi) * 9.8 / 1031 dt = fh.variables['average_DT'][:] dt = dt[:, np.newaxis, np.newaxis, np.newaxis] sl, dimv = rdp1.getslice(fh, xstart, xend, ystart, yend, yhyq='yq') slmx = np.s_[:, :, sl[2], (sl[3].start - 1):sl[3].stop] slpx = np.s_[:, :, sl[2], (sl[3].start + 1):sl[3].stop] slmxpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), (sl[3].start - 1):sl[3].stop] slpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), sl[3]] slmpy = np.s_[:, :, (sl[2].start - 1):(sl[2].stop + 1), sl[3]] sl2d = sl[2:] slmx2d = slmx[2:] slpx2d = slpx[2:] slpy2d = slpy[2:] dxbu = fhgeo.variables['dxBu'][slmx2d] dybu = fhgeo.variables['dyBu'][slmx2d] dxcv = fhgeo.variables['dxCv'][sl2d] dycv = fhgeo.variables['dyCv'][sl2d] dxt = fhgeo.variables['dxT'][slpy2d] dyt = fhgeo.variables['dyT'][slpy2d] v, _ = pv.getvtwa(fhgeo, fh, fh2, slmx) vx = np.diff(v, axis=3) / dxbu vx = vx[:, :, :, 1:] e = (fh2.variables['e'][slpy] * dt).sum(axis=0, keepdims=True) / dt.sum( axis=0, keepdims=True) eatv = 0.5 * (e[:, :, :-1, :] + e[:, :, 1:, :]) e = fh2.variables['e'][slmxpy] eatvmx = 0.5 * (e[:, :, :-1, :] + e[:, :, 1:, :]) vh = (fh.variables['vh_masked'][sl] * dt).sum(axis=0, keepdims=True) / np.sum(dt) h_cv = (fh.variables['h_Cv'][sl] * dt).sum(axis=0, keepdims=True) / np.sum(dt) h_cv[h_cv < htol] = np.nan sig = h_cv / dbl[:, np.newaxis, np.newaxis] h_vm = h_cv vtwa = vh / h_cv / dxcv vhforxdiff = (fh.variables['vh_masked'][slmx] * dt).sum( axis=0, keepdims=True) / np.sum(dt) h_cvforxdiff = (fh.variables['h_Cv'][slmx] * dt).sum( axis=0, keepdims=True) / np.sum(dt) h_cvforxdiff[h_cvforxdiff < htol] = np.nan vtwaforxdiff = vhforxdiff / h_cvforxdiff vtwaforxdiff = np.concatenate((vtwaforxdiff, vtwaforxdiff[:, :, :, -1:]), axis=3) vtwax = np.diff(vtwaforxdiff, axis=3) / dxbu / dybu vtwax = 0.5 * (vtwax[:, :, :, :-1] + vtwax[:, :, :, 1:]) uh = (fh.variables['uh_masked'][slmxpy] * dt).filled(0).sum( axis=0, keepdims=True) / np.sum(dt) hum = 0.25 * (uh[:, :, :-1, :-1] + uh[:, :, :-1, 1:] + uh[:, :, 1:, :-1] + uh[:, :, 1:, 1:]) / dycv huvxphvvym = (fh.variables['twa_huvxpt'][sl] * dt + fh.variables['twa_hvvymt'][sl] * dt).sum( axis=0, keepdims=True) / np.sum(dt) hvv = (fh.variables['hvv_Cv'][slmpy] * dt).sum(axis=0, keepdims=True) / np.sum(dt) hvvym = np.diff(hvv, axis=2) / dxt / dyt hvvym = 0.5 * (hvvym[:, :, :-1, :] + hvvym[:, :, 1:, :]) huvxm = -(huvxphvvym + hvvym) advx = hum * vtwax / h_vm humx = np.diff(np.nan_to_num(uh), axis=3) / dxt / dyt humx = 0.5 * (humx[:, :, :-1, :] + humx[:, :, 1:, :]) xdivep1 = -huvxm / h_vm xdivep2 = advx xdivep3 = vtwa * humx / h_vm xdivep = (xdivep1 + xdivep2 + xdivep3) xdivep *= sig uv = sint.cumtrapz( xdivep[:, :, :, ::-1], dx=-dxbu[:, 1:-1], axis=3, initial=0)[:, :, :, ::-1] / sig uvm = np.apply_over_axes(np.nanmean, uv, (0, 2)) vxm = np.apply_over_axes(np.nanmean, vx, (0, 2)) uvm = getvaratzc(uvm.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) vxm = getvaratzc(vxm.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 3)) cmax = np.fabs(np.percentile(uvm, (1, 99))).max() im = ax[0].pcolormesh(dimv[3], z, uvm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') cmax = np.fabs(np.percentile(vxm, (1, 99))).max() im = ax[1].pcolormesh(dimv[3], z, vxm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') for axc in ax: xdegtokm(axc, 0.5 * (ystart + yend)) axc.set_xlabel('x (km)') axc.grid() ax[0].set_ylabel('z (m)') fig2, ax = plt.subplots(1, 1, sharey=True) ax.linfit(vx, uv) ax.set_xlabel('v_x (m/s)') ax.set_ylabel('RS (m2/s2)') ax.grid() return fig, fig2
def get_deddy_coeffs(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs=0, ze=None, z=np.linspace(-1500, 0, 100), perc=5): fhgeo = dset(geofil) fhvgeo = dset(vgeofil) fh = mfdset(fil) fh2 = mfdset(fil2) db = fhvgeo.variables['g'][:] fhvgeo.close() dbi = np.append(db, 0) zi = fh.variables['zi'][:] zl = fh.variables['zl'][:] dbl = np.diff(zi) * 9.8 / 1031 sl, dimv = rdp1.getslice(fh, xstart, xend, ystart, yend, yhyq='yq') sl2d = sl[2:] slpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), sl[3]] f = fhgeo.variables['f'][sl2d] e = fh2.variables['e'][slpy] eatv = 0.5 * (e[:, :, :-1, :] + e[:, :, 1:, :]) v, h = pv.getvtwa(fhgeo, fh, fh2, sl) v = v[:, :, :, :-1] h = h[:, :, :, :-1] sig = h / dbl[:, np.newaxis, np.newaxis] sigaz = getvaratzc(sig.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) vb = -np.diff(v, axis=1) / dbi[1:-1, np.newaxis, np.newaxis] vb = np.concatenate((vb[:, :1, :, :], vb, vb[:, -1:, :, :]), axis=1) vbb = -np.diff(vb, axis=1) / dbl[:, np.newaxis, np.newaxis] vbb = getvaratzc(vbb.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) vi = np.concatenate((v[:, :1, :, :], v, -v[:, -1:, :, :]), axis=1) vi = 0.5 * (vi[:, :-1, :, :] + vi[:, 1:, :, :]) vib = -np.diff(vi, axis=1) / dbl[:, np.newaxis, np.newaxis] svib = sig * vib svibb = -np.diff(svib, axis=1) / dbi[1:-1, np.newaxis, np.newaxis] svibb = np.concatenate((svibb[:, :1, :, :], svibb, svibb[:, -1:, :, :]), axis=1) svibb = 0.5 * (svibb[:, :-1, :, :] + svibb[:, 1:, :, :]) svibb = getvaratzc(svibb.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) sv = sig * v svb = -np.diff(sv, axis=1) / dbi[1:-1, np.newaxis, np.newaxis] svb = np.concatenate((svb[:, :1, :, :], svb, svb[:, -1:, :, :]), axis=1) svbb = -np.diff(svb, axis=1) / dbl[:, np.newaxis, np.newaxis] svbb = getvaratzc(svbb.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) x, y, P, _, _ = py.extract_twamomy_terms(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs, ze, (0, ), z=z) fdrag = P[:, :, :, :, 7] vbbm = np.apply_over_axes(np.nanmean, vbb, (0, 2)) svibbm = np.apply_over_axes(np.nanmean, svibb, (0, 2)) svbbm = np.apply_over_axes(np.nanmean, svbb, (0, 2)) fdragm = np.apply_over_axes(np.nanmean, fdrag, (0, 2)) fig, ax = plt.subplots(1, 4, sharex=True, sharey=True, figsize=(12, 3)) cmax = np.fabs(np.percentile(vbbm, (1, 99))).max() im = ax[0].pcolormesh(dimv[3], z, vbbm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[0]) cmax = np.fabs(np.percentile(svibbm, (1, 99))).max() im = ax[1].pcolormesh(dimv[3], z, svibbm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[1]) cmax = np.fabs(np.percentile(svbbm, (1, 99))).max() im = ax[2].pcolormesh(dimv[3], z, svbbm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[2]) cmax = np.fabs(np.percentile(fdragm, (1, 99))).max() im = ax[3].pcolormesh(dimv[3], z, fdragm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[3]) fig2, ax = plt.subplots(1, 3, sharey=True, figsize=(12, 3)) ax[0].linfit(vbb, sigaz * fdrag / f**2) ax[0].set_xlabel(r'$v_{bb}$') ax[1].linfit(svibb, sigaz * fdrag / f**2) ax[1].set_xlabel(r'$(\sigma v_b)_b$') ax[2].linfit(svbb, sigaz * fdrag / f**2) ax[2].set_xlabel(r'$(\sigma v)_{bb}$') ax[0].set_ylabel('Form Drag') for axc in ax: axc.grid() return fig, fig2
def plot_sst_vort(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, ls, le, fil3=None, z=np.linspace(-10, -9, 4), htol=1e-3, whichterms=None): domain = Domain.Domain2(geofil, vgeofil, xstart, xend, ystart, yend, ls=ls, le=le, ts=450, te=451) with mfdset(fil2) as fh2: rho = gv('e', domain, 'hi', fh2).read_array(tmean=False).toz(z[0], rho=True) T = (-rho + 1031) * (1 / 0.2) T.name = '' fig, ax = plt.subplots(1, 2, sharex=True, sharey=True) T.plot('nanmean', (0, 1), contour=False, cbar=True, plot_kwargs=dict(cmap='RdYlBu_r', vmax=20, vmin=10), ax=ax[0]) rho = gv('e', domain, 'hi', fh2).read_array(tmean=False).toz(z[1], rho=True) T = (-rho + 1031) * (1 / 0.2) T.name = '' T.plot('nanmean', (0, 1), contour=False, cbar=True, plot_kwargs=dict(cmap='RdYlBu_r', vmax=10, vmin=6), ax=ax[1]) # e = gv('e',domain,'hi',fh2,plot_loc='qi').xsm().ysm().read_array(tmean=False, # extend_kwargs=dict(method='mirror')).move_to('ui').move_to('qi') # uy = gv('u',domain,'ul',fh2,plot_loc='ql').yep().read_array(tmean=False, # extend_kwargs=dict(method='vorticity')).ddx(2) # vx = gv('v',domain,'vl',fh2,plot_loc='ql').xep().read_array(tmean=False, # extend_kwargs=dict(method='vorticity')).ddx(3) # vort = (vx - uy) # vort.name = '' # vort.plot('nanmean',(0,1),perc=98,contour=False,cbar=True,plot_kwargs=dict(cmap='RdBu_r'),ax=ax[1]) # ax[1].set_ylabel('') # # vortz = vort.toz([-1],e=e) # vortz.name = '' # vortz.plot('nanmean',(0,1),perc=98,contour=False,cbar=True,plot_kwargs=dict(cmap='RdBu_r'),ax=ax[2]) # vmax = np.nanpercentile(np.fabs(vortz.values),98) # xx,yy = np.meshgrid(vortz.dom.lonq[vortz._plot_slice[3,0]:vortz._plot_slice[3,1]], # vortz.dom.latq[vortz._plot_slice[2,0]:vortz._plot_slice[2,1]]) # print(xx.shape, yy.shape, vortz.values[0,0,:,:].shape) # im = ax[2].pcolormesh(xx,yy, # vortz.values[0,0,:,:],cmap='RdBu_r',vmin=-vmax,vmax=vmax) # print(e.values.shape) # im = ax[2].pcolormesh(e.dom.lonq[e._plot_slice[3,0]:e._plot_slice[3,1]], # e.dom.latq[e._plot_slice[2,0]:e._plot_slice[2,1]], # e.values[0,0,:,:],cmap='RdBu_r') # cbar = fig.colorbar(im,ax=ax[2]) # cbar.formatter.set_powerlimits((-2,2)) # cbar.update_ticks() # ax[2].set_ylabel('') domain = Domain.Domain2(geofil, vgeofil, xstart, xend, ystart, yend, ls=0, le=1) with mfdset(fil) as fh: e = gv('e', domain, 'hi', fh).read_array() cs = ax[0].contour(e.dom.lonh[e._plot_slice[3, 0]:e._plot_slice[3, 1]], e.dom.lath[e._plot_slice[2, 0]:e._plot_slice[2, 1]], e.values.squeeze(), levels=[-0.4, -0.3, -0.15, 0, 0.15, 0.3, 0.4], colors='k') cs.clabel(inline=True) return fig
def extractT(geofil, fil, xstart, xend, ystart, yend, zs, ze, meanax, ts=0, te=None, z=None, drhodt=-0.2, rho0=1031.0, savfil=None, plotit=True, loop=True): keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fh = mfdset(fil) (xs, xe), (ys, ye), dimh = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze) fhgeo = dset(geofil) D = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[0] fhgeo.close() nt = dimh[0].size t0 = time.time() zl = rdp1.getdims(fh)[2][1] if loop: print('Reading data in loop...') e = fh.variables['e'][0:1, zs:ze, ys:ye, xs:xe] / nt for i in range(nt): e += fh.variables['e'][i:i + 1, zs:ze, ys:ye, xs:xe] / nt sys.stdout.write('\r' + str(int((i + 1) / nt * 100)) + '% done...') sys.stdout.flush() print('Time taken for data reading: {}s'.format(time.time() - t0)) else: e = fh.variables['e'][ts:te, zs:ze, ys:ye, xs:xe] X = dimh[keepax[1]] Y = dimh[keepax[0]] if 1 in keepax: Y = z if z == None: z = np.linspace(-np.nanmax(D), -1, num=50) Y = z T = getTatz(zl, z, e) T = (T - rho0) / drhodt T = np.ma.apply_over_axes(np.nanmean, T, meanax) P = T.squeeze() data = (X, Y, P) if plotit: Pmax = np.nanmax(P) Pmin = np.nanmin(P) im = m6plot(data, vmax=Pmax, vmin=Pmin, title=r'T at 40N ($^{\circ}$C)', xlabel=r'x ($^{\circ}$)', ylabel='z (m)', bvnorm=True, blevs=15) if savfil: plt.savefig(savfil + '.eps', dpi=300, facecolor='w', edgecolor='w', format='eps', transparent=False, bbox_inches='tight') else: plt.show() else: return data
def plot_twamomy_pym6(initializer, **kwargs): budgetlist = extract_twamomy_terms_pym6(initializer) terms = kwargs.get('terms', None) if terms: budgetlist = [budgetlist[i] for i in terms] with mfdset(initializer.fil) as fh, mfdset(initializer.fil2) as fh2: e = (gv('e', budgetlist[0].dom, 'hi', fh2, fh, plot_loc='vl').yep().read_array(extend_kwargs={ 'method': 'mirror' }).move_to('vi')) plot_kwargs = dict(cmap='RdBu_r') plotter_kwargs = dict(xtokm=True, zcoord=True, z=initializer.z, e=e, isop_mean=True) ax, fig = Plotter.budget_plot(budgetlist, initializer.meanax, plot_kwargs=plot_kwargs, plotter_kwargs=plotter_kwargs, individual_cbars=False, **kwargs) swash = kwargs.get('swash', True) plotter_kwargs.pop('ax') if swash: initializer_for_swash = Domain.Initializer(geofil=initializer.geofil, vgeofil=initializer.vgeofil, wlon=-0.5, elon=0, slat=10, nlat=11) domain_for_swash0 = Domain.Domain(initializer_for_swash) with mfdset(initializer.fil3) as fh: islayerdeep = (gv('islayerdeep', budgetlist[0].dom, 'ql', fh, plot_loc='vl').xsm().read_array(tmean=False, extend_kwargs={ 'method': 'mirror' }).move_to('vl')) islayerdeep0 = (gv('islayerdeep', domain_for_swash0, 'ql', fh, plot_loc='vl').xsm().read_array( tmean=False, extend_kwargs={ 'method': 'mirror' }).move_to('vl')) swashperc = (-islayerdeep / islayerdeep0.values[-1, 0, 0, 0] + 1) * 100 plot_kwargs = kwargs.get('swash_plot_kwargs', dict(colors='grey', linewidths=4)) for axc in ax.ravel(): axc, _ = swashperc.plot('nanmean', initializer.meanax, only_contour=True, clevs=np.array([1]), annotate='None', ax=axc, plot_kwargs=plot_kwargs, **plotter_kwargs) return ax, fig
def extract_uv(geofil, fil, fil2, fil3, xstart, xend, ystart, yend, zs, ze, savfil=None, utwamaxscalefactor=1, vtwamaxscalefactor=1): fh = mfdset(fil) fh2 = mfdset(fil2) zi = rdp1.getdims(fh)[2][0] fhgeo = dset(geofil) (xs, xe), (ys, ye), dimutwa = rdp1.getlatlonindx( fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xq', yhyq='yh') em = fh.variables['e'][0:, zs:ze, ys:ye, xs:xe] elm = 0.5 * (em[:, 0:-1, :, :] + em[:, 1:, :, :]) elm = np.ma.apply_over_axes(np.mean, elm, (0, 2)) dycu = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[2][1] uh = fh.variables['uh'][0:, zs:ze, ys:ye, xs:xe] h_cu = fh2.variables['h_Cu'][0:, zs:ze, ys:ye, xs:xe] utwa = uh / h_cu / dycu fig = plt.figure() ax = fig.add_subplot(221) X = dimutwa[3] X = np.meshgrid(X, dimutwa[1])[0] Y = elm.squeeze() utwa = np.ma.apply_over_axes(np.nanmean, utwa, (0, 2)) utwa = utwa.squeeze() cmax = np.nanmax(np.absolute(utwa)) * utwamaxscalefactor im = m6plot( (X, Y, utwa), ax=ax, ylabel='z (m)', txt=r'$\hat{u}$', vmin=-cmax, vmax=cmax, cmap='RdBu_r', ylim=(-3000, 0)) ax.set_xticklabels([]) (xs, xe), (ys, ye), dimvtwa = rdp1.getlatlonindx( fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xh', yhyq='yq') em = fh.variables['e'][0:, zs:ze, ys:ye, xs:xe] elm = 0.5 * (em[:, 0:-1, :, :] + em[:, 1:, :, :]) elm = np.ma.apply_over_axes(np.mean, elm, (0, 2)) dxcv = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[2][2] vh = fh.variables['vh'][0:, zs:ze, ys:ye, xs:xe] h_cv = fh2.variables['h_Cv'][0:, zs:ze, ys:ye, xs:xe] vtwa = vh / h_cv / dxcv ax = fig.add_subplot(222) X = dimvtwa[3] X = np.meshgrid(X, dimvtwa[1])[0] Y = elm.squeeze() vtwa = np.ma.apply_over_axes(np.nanmean, vtwa, (0, 2)) vtwa = vtwa.squeeze() cmax = np.nanmax(np.absolute(vtwa)) * vtwamaxscalefactor im = m6plot( (X, Y, vtwa), ax=ax, txt=r'$\hat{v}$', vmin=-cmax, vmax=cmax, cmap='RdBu_r', ylim=(-3000, 0)) ax.set_xticklabels([]) ax.set_yticklabels([]) fh2.close() fh.close() fhgeo.close() fh3 = mfdset(fil3) (xs, xe), (ys, ye), dimu = rdp1.getlatlonindx( fh3, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xq', yhyq='yh', zlzi='zlremap') u = fh3.variables['u'][0:, zs:ze, ys:ye, xs:xe] ax = fig.add_subplot(223) X = dimu[3] Y = dimu[1] u = np.ma.apply_over_axes(np.nanmean, u, (0, 2)) u = u.squeeze() cmax = np.nanmax(np.absolute(u)) im = m6plot( (X, -Y, u), ax=ax, txt='u', ylabel='z (m)', vmin=-cmax, vmax=cmax, cmap='RdBu_r') xdegtokm(ax, 0.5 * (ystart + yend)) (xs, xe), (ys, ye), dimv = rdp1.getlatlonindx( fh3, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xh', yhyq='yq', zlzi='zlremap') v = fh3.variables['v'][0:, zs:ze, ys:ye, xs:xe] ax = fig.add_subplot(224) X = dimv[3] Y = dimv[1] v = np.ma.apply_over_axes(np.nanmean, v, (0, 2)) v = v.squeeze() cmax = np.nanmax(np.absolute(v)) im = m6plot( (X, -Y, v), ax=ax, txt='v', vmin=-cmax, vmax=cmax, cmap='RdBu_r') xdegtokm(ax, 0.5 * (ystart + yend)) ax.set_yticklabels([]) fh3.close() if savfil: plt.savefig( savfil + '.eps', dpi=300, facecolor='w', edgecolor='w', format='eps', transparent=False, bbox_inches='tight') else: plt.show()
def extract_twamomy_terms(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs, ze, meanax, alreadysaved=False, xyasindices=False, calledfrompv=False): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fhvgeo = dset(vgeofil) db = -fhvgeo.variables['g'][:] dbi = np.append(db, 0) fhvgeo.close() fhgeo = dset(geofil) fh = mfdset(fil) fh2 = mfdset(fil2) zi = rdp1.getdims(fh)[2][0] dbl = np.diff(zi) * 9.8 / 1031 if xyasindices: (xs, xe), (ys, ye) = (xstart, xend), (ystart, yend) _, _, dimv = rdp1.getdimsbyindx(fh, xs, xe, ys, ye, zs=zs, ze=ze, ts=0, te=None, xhxq='xh', yhyq='yq', zlzi='zl') else: (xs, xe), (ys, ye), dimv = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, yhyq='yq') D, (ah, aq) = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[0:2] Dforgetutwaforxdiff = rdp1.getgeombyindx(fhgeo, xs - 1, xe, ys, ye)[0] Dforgetutwaforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye + 1)[0] Dforgethvforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye)[0] dxt, dyt = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye + 1)[2][6:8] dxcv, dycv = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[2][2:4] dxcvforxdiff = rdp1.getgeombyindx(fhgeo, xs - 1, xe, ys, ye)[2][2:3] dxcvforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye + 1)[2][3:4] dxbu = rdp1.getgeombyindx(fhgeo, xs - 1, xe, ys, ye)[2][4] nt_const = dimv[0].size t0 = time.time() em = fh.variables['e'][0:, zs:ze, ys:ye, xs:xe] elm = 0.5 * (em[:, 0:-1, :, :] + em[:, 1:, :, :]) vh = fh2.variables['vh'][0:, zs:ze, ys:ye, xs:xe] h_cv = fh.variables['h_Cv'][0:, zs:ze, ys:ye, xs:xe] h_vm = h_cv vtwa = vh / h_cv / dxcv vhforxdiff = fh2.variables['vh'][0:, zs:ze, ys:ye, xs - 1:xe] h_cvforxdiff = fh.variables['h_Cv'][0:, zs:ze, ys:ye, xs - 1:xe] vtwaforxdiff = vhforxdiff / h_cvforxdiff / dxcvforxdiff vtwaforxdiff = np.concatenate( (vtwaforxdiff, vtwaforxdiff[:, :, :, -1:]), axis=3) vhforydiff = fh2.variables['vh'][0:, zs:ze, ys - 1:ye + 1, xs:xe] h_cvforydiff = fh.variables['h_Cv'][0:, zs:ze, ys - 1:ye + 1, xs:xe] vtwaforydiff = vhforydiff / h_cvforydiff / dxcvforydiff vtwax = np.diff(vtwaforxdiff, axis=3) / dxbu vtwax = 0.5 * (vtwax[:, :, :, 0:-1] + vtwax[:, :, :, 1:]) vtway = np.diff(vtwaforydiff, axis=2) / dyt vtway = 0.5 * (vtway[:, :, 0:-1, :] + vtway[:, :, 1:, :]) hvmy = np.diff(vhforydiff / dxcvforydiff, axis=2) / dyt hvmy = 0.5 * (hvmy[:, :, :-1, :] + hvmy[:, :, 1:, :]) hum = fh.variables['hu_Cv'][0:, zs:ze, ys:ye, xs:xe] humforxdiff = fh.variables['hu_Cv'][0:, zs:ze, ys:ye, xs - 1:xe] humforxdiff = np.concatenate((humforxdiff, -humforxdiff[:, :, :, -1:]), axis=3) humx = np.diff(humforxdiff, axis=3) / dxbu humx = 0.5 * (humx[:, :, :, :-1] + humx[:, :, :, 1:]) huvxphvvym = fh.variables['twa_huvxpt'][ 0:, zs:ze, ys:ye, xs:xe] + fh.variables['twa_hvvymt'][0:, zs:ze, ys:ye, xs:xe] hvv = fh.variables['hvv_Cv'][0:, zs:ze, ys - 1:ye + 1, xs:xe] hvvym = np.diff(hvv, axis=2) / dyt hvvym = 0.5 * (hvvym[:, :, :-1, :] + hvvym[:, :, 1:, :]) huvxm = huvxphvvym - hvvym vtwaforvdiff = np.concatenate((vtwa[:, [0], :, :], vtwa), axis=1) vtwab = np.diff(vtwaforvdiff, axis=1) / db[:, np.newaxis, np.newaxis] vtwab = np.concatenate( (vtwab, np.zeros([vtwab.shape[0], 1, vtwab.shape[2], vtwab.shape[3]])), axis=1) vtwab = 0.5 * (vtwab[:, 0:-1, :, :] + vtwab[:, 1:, :, :]) hwb_v = fh.variables['hwb_Cv'][0:, zs:ze, ys:ye, xs:xe] hwm_v = fh.variables['hw_Cv'][0:, zs:ze, ys:ye, xs:xe] esq = fh.variables['esq_Cv'][0:, zs:ze, ys - 1:ye + 1, xs:xe] ecv = fh.variables['e_Cv'][0:, zs:ze, ys - 1:ye + 1, xs:xe] edlsqm = (esq - ecv**2) edlsqmy = np.diff(edlsqm, axis=2) / dyt edlsqmy = 0.5 * (edlsqmy[:, :, :-1, :] + edlsqmy[:, :, 1:, :]) epfv = fh.variables['epfv'][0:, zs:ze, ys:ye, xs:xe] ecv = fh.variables['e_Cv'][0:, zs:ze, ys:ye, xs:xe] pfvm = fh.variables['pfv_masked'][0:, zs:ze, ys:ye, xs:xe] edpfvdm = epfv - pfvm * ecv edpfvdmb = np.diff(edpfvdm, axis=1) edpfvdmb = np.concatenate( (edpfvdmb[:, :1, :, :], edpfvdmb, edpfvdmb[:, -1:, :, :]), axis=1) edpfvdmb = 0.5 * (edpfvdmb[:, :-1, :, :] + edpfvdmb[:, 1:, :, :]) hmfum = fh.variables['twa_hmfu'][0:1, zs:ze, ys:ye, xs:xe] hvwbm = fh.variables['twa_hvwb'][0:1, zs:ze, ys:ye, xs:xe] hdiffvm = fh.variables['twa_hdiffv'][0:1, zs:ze, ys:ye, xs:xe] hdvdtviscm = fh.variables['twa_hdvdtvisc'][0:1, zs:ze, ys:ye, xs:xe] fh2.close() fh.close() advx = hum * vtwax / h_vm advy = vtwa * vtway advb = hwm_v * vtwab / h_vm cor = hmfum / h_vm pfvm = pfvm xdivep1 = -huvxm / h_vm xdivep2 = -advx xdivep3 = -vtwa * humx / h_vm xdivep = (xdivep1 + xdivep2 + xdivep3) ydivep1 = -hvvym / h_vm ydivep2 = -advy ydivep3 = -vtwa * hvmy / h_vm ydivep4 = 0.5 * edlsqmy * dbl[:, np.newaxis, np.newaxis] / h_vm ydivep = (ydivep1 + ydivep2 + ydivep3 + ydivep4) bdivep1 = -hvwbm / h_vm bdivep2 = -advb bdivep3 = -vtwa * hwb_v / h_vm bdivep4 = edpfvdmb / h_vm bdivep = (bdivep1 + bdivep2 + bdivep3 + bdivep4) Y1twa = hdiffvm / h_vm Y2twa = hdvdtviscm / h_vm terms = np.ma.concatenate( (-advx[:, :, :, :, np.newaxis], -advy[:, :, :, :, np.newaxis], -advb[:, :, :, :, np.newaxis], cor[:, :, :, :, np.newaxis], pfvm[:, :, :, :, np.newaxis], -xdivep[:, :, :, :, np.newaxis], -ydivep[:, :, :, :, np.newaxis], -bdivep[:, :, :, :, np.newaxis], Y1twa[:, :, :, :, np.newaxis], Y2twa[:, :, :, :, np.newaxis]), axis=4) termsep = np.ma.concatenate(( -xdivep1[:, :, :, :, np.newaxis], -xdivep3[:, :, :, :, np.newaxis], -ydivep1[:, :, :, :, np.newaxis], -ydivep3[:, :, :, :, np.newaxis], -ydivep4[:, :, :, :, np.newaxis], -bdivep1[:, :, :, :, np.newaxis], -bdivep3[:, :, :, :, np.newaxis], -bdivep4[:, :, :, :, np.newaxis]), axis=4) terms[np.isinf(terms)] = np.nan termsep[np.isinf(termsep)] = np.nan termsm = np.ma.apply_over_axes(np.nanmean, terms, meanax) termsepm = np.ma.apply_over_axes(np.nanmean, termsep, meanax) X = dimv[keepax[1]] Y = dimv[keepax[0]] if 1 in keepax: em = np.ma.apply_over_axes(np.mean, em, meanax) elm = np.ma.apply_over_axes(np.mean, elm, meanax) Y = elm.squeeze() X = np.meshgrid(X, dimv[1])[0] P = termsm.squeeze() P = np.ma.filled(P.astype(float), np.nan) Pep = termsepm.squeeze() Pep = np.ma.filled(Pep.astype(float), np.nan) X = np.ma.filled(X.astype(float), np.nan) Y = np.ma.filled(Y.astype(float), np.nan) if not calledfrompv: np.savez('twamomy_complete_terms', X=X, Y=Y, P=P, Pep=Pep) else: npzfile = np.load('twamomy_complete_terms.npz') X = npzfile['X'] Y = npzfile['Y'] P = npzfile['P'] Pep = npzfile['Pep'] return (X, Y, P, Pep)
def get_pveddy_coeffs(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs=0, ze=None, z=np.linspace(-3000, 0, 100), percx=0, percy=0): fhgeo = dset(geofil) fhvgeo = dset(vgeofil) fh = mfdset(fil) fh2 = mfdset(fil2) db = fhvgeo.variables['g'][:] fhvgeo.close() dbi = np.append(db, 0) zi = fh.variables['zi'][:] zl = fh.variables['zl'][:] dbl = np.diff(zi) * 9.8 / 1031 dt = fh.variables['average_DT'][:] dt = dt[:, np.newaxis, np.newaxis, np.newaxis] sl, dimq = rdp1.getslice(fh, xstart, xend, ystart, yend, xhxq='xq', yhyq='yq') xs = sl[3].start xe = sl[3].stop ys = sl[2].start ye = sl[2].stop zs = sl[1].start ze = sl[1].stop slmx = np.s_[:, :, sl[2], (sl[3].start - 1):sl[3].stop] slpx = np.s_[:, :, sl[2], (sl[3].start + 1):sl[3].stop] slmxpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), (sl[3].start - 1):sl[3].stop] slpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), sl[3]] sl2d = sl[2:] slmx2d = slmx[2:] slpx2d = slpx[2:] dxbu = fhgeo.variables['dxBu'][sl2d] dxcv = fhgeo.variables['dxCv'][sl2d] e = (fh2.variables['e'][slpy] * dt).sum(axis=0, keepdims=True) / dt.sum( axis=0, keepdims=True) e = np.concatenate((e, e[:, :, :, -1:]), axis=3) eatq = 0.25 * (e[:, :, :-1, :-1] + e[:, :, 1:, 1:] + e[:, :, 1:, :-1] + e[:, :, :-1, 1:]) (_, _, _, q, _, _) = pv2.extract_twapv_terms(geofil, vgeofil, fil, fil2, xs - 1, xe, ys, ye, zs, ze, meanax=(0, ), fil3=None, calledfromgeteddycoeffs=True) (_, _, _, _, qbud, _) = pv2.extract_twapv_terms(geofil, vgeofil, fil, fil2, xs, xe, ys, ye, zs, ze, meanax=(0, ), fil3=None, calledfromgeteddycoeffs=True) fd = qbud[:, :, :, :, 12] q[np.isnan(q)] = 0 qx = np.diff(q, axis=3) / dxcv qx = np.concatenate((qx, qx[:, :, :, -1:]), axis=3) qxx = np.diff(qx, axis=3) / dxbu fdaz = getvaratzc(fd.astype(np.float32), z.astype(np.float32), eatq.astype(np.float32)) qxxaz = getvaratzc(qxx.astype(np.float32), z.astype(np.float32), eatq.astype(np.float32)) qxxazm = np.apply_over_axes(np.nanmean, qxxaz, (0, 2)) fdazm = np.apply_over_axes(np.nanmean, fdaz, (0, 2)) fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 3)) cmax = np.fabs(np.nanpercentile(qxxazm, (1, 99))).max() im = ax[0].pcolormesh(dimq[3], z, qxxazm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') cb = fig.colorbar(im, ax=ax[0]) cb.formatter.set_powerlimits((0, 0)) cb.update_ticks() cmax = np.fabs(np.nanpercentile(fdazm, (1, 99))).max() im = ax[1].pcolormesh(dimq[3], z, fdazm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') cb = fig.colorbar(im, ax=ax[1]) cb.formatter.set_powerlimits((0, 0)) cb.update_ticks() for axc in ax: xdegtokm(axc, 0.5 * (ystart + yend)) axc.set_xlabel('x (km)') axc.grid() ax[0].set_ylabel('z (m)') fig2, ax = plt.subplots(1, 1, sharey=True) ax.linfit(qxx, fd, percx=percx, percy=percy) ax.set_xlabel('qxx') ax.set_ylabel('grad fd') ax.grid() return fig, fig2
def gethatuv(filename,i): fh = mfdset(filename) frhatu = fh.variables['frhatu'][i,:,:,:] frhatv = fh.variables['frhatv'][i,:,:,:] fh.close() return (frhatu,frhatv)
def getPVRV(filename,i): fh = mfdset(filename) PV = fh.variables['PV'][i,:,:,:] RV = fh.variables['RV'][i,:,:,:] fh.close() return (PV,RV)
def extract_twamomy_terms(geofil, fil, xstart, xend, ystart, yend, zs, ze, meanax, alreadysaved=False): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fh = mfdset(fil) (xs, xe), (ys, ye), dimv = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, yhyq='yq') # _,(vys,vye),_ = rdp1.getlatlonindx(fh,wlon=xstart,elon=xend, # slat=ystart, nlat=yend,zs=zs,ze=ze,yhyq='yq') # (xs,xe),(ys,ye),_ = rdp1.getlatlonindx(fh,wlon=xstart,elon=xend, # slat=ystart, nlat=yend,zs=zs,ze=ze) D, (ah, aq) = rdp1.getgeombyindx(geofil, xs, xe, ys, ye)[0:2] nt_const = dimv[0].size e = fh.variables['e'][0:, zs:ze, ys:ye, xs:xe] hmfu = fh.variables['twa_hmfu'][0:, zs:ze, ys:ye, xs:xe] hpfv = fh.variables['twa_hpfv'][0:, zs:ze, ys:ye, xs:xe] huvxpt = fh.variables['twa_huvxpt'][0:, zs:ze, ys:ye, xs:xe] hvvymt = fh.variables['twa_hvvymt'][0:, zs:ze, ys:ye, xs:xe] hvwb = fh.variables['twa_hvwb'][0:, zs:ze, ys:ye, xs:xe] hdvdtvisc = fh.variables['twa_hdvdtvisc'][0:, zs:ze, ys:ye, xs:xe] hdiffv = fh.variables['twa_hdiffv'][0:, zs:ze, ys:ye, xs:xe] fh.close() terms = np.ma.concatenate( (hmfu[:, :, :, :, np.newaxis], hpfv[:, :, :, :, np.newaxis], hvwb[:, :, :, :, np.newaxis], huvxpt[:, :, :, :, np.newaxis], hvvymt[:, :, :, :, np.newaxis], hdvdtvisc[:, :, :, :, np.newaxis], hdiffv[:, :, :, :, np.newaxis]), axis=4) termsm = np.ma.apply_over_axes(np.nanmean, terms, meanax) X = dimv[keepax[1]] Y = dimv[keepax[0]] if 1 in keepax: el = 0.5 * (e[:, 0:-1, :, :] + e[:, 1:, :, :]) e = np.ma.apply_over_axes(np.mean, e, meanax) el = np.ma.apply_over_axes(np.mean, el, meanax) Y = el.squeeze() X = np.meshgrid(X, dimv[1])[0] P = termsm.squeeze() P = np.ma.filled(P.astype(float), np.nan) X = np.ma.filled(X.astype(float), np.nan) Y = np.ma.filled(Y.astype(float), np.nan) np.savez('twamomy_terms', X=X, Y=Y, P=P) else: npzfile = np.load('twamomy_terms.npz') X = npzfile['X'] Y = npzfile['Y'] P = npzfile['P'] return (X, Y, P)
def plot_forcing(fil, fil2=None): y = np.linspace(10, 60, 100) sflat = 20 nflat = 40 T = np.zeros(y.shape) Tnorth = 10 Tsouth = 20 T[y >= sflat] = (Tsouth - Tnorth) / (sflat - nflat) * (y[y >= sflat] - nflat) + Tnorth T[y < sflat] = Tsouth T[y > nflat] = Tnorth rho0 = 1031 drhodt = -0.2 rho = rho0 + drhodt * T gs = gridspec.GridSpec(2, 3, width_ratios=[1, 4, 1], height_ratios=[1, 4]) fig = plt.figure(figsize=(9, 4)) #ax = fig.add_subplot(121) ax = plt.subplot(gs[1]) ax.plot(y, T, 'k', lw=1) # ax.set_ylabel('T ($^{\circ}$C)') ax.set_xlabel('y ($^{\circ}$N)') ax.set_ylim(8, 22) ax.grid(True) ax.xaxis.tick_top() ax.xaxis.set_label_position("top") ax2 = ax.twinx() ax2.set_ylabel(r"""$\rho (kgm^{-3})$""") ax2.set_ylim(ax.get_ylim()) yticks = ax.get_yticks() ax2.set_yticks(yticks[::2]) yticks = rho0 + drhodt * yticks[::2] ax2.set_yticklabels(['{}'.format(i) for i in yticks]) z = np.linspace(0, 3000) dabyss = 1500 Tabyss = 5 Tz = (Tabyss - Tsouth) / dabyss * z + Tsouth Tz[z > dabyss] = Tabyss #ax = fig.add_subplot(122) ax = plt.subplot(gs[3]) ax.plot(Tz, z, 'k', lw=1) ax.set_xlabel('T ($^{\circ}$C)') ax.set_ylabel('z (m)') ax.set_xlim(4, 21) ax.grid(True) ax.invert_yaxis() # ax.yaxis.tick_right() # ax.yaxis.set_label_position("right") # ax2 = ax.twiny() # ax2.set_xlabel(r"""$\rho (kgm^{-3})$""") # ax2.set_xlim(ax.get_xlim()) # xticks = ax.get_xticks() # ax2.set_xticks(xticks[::2]) # xticks = rho0 + drhodt*xticks[::2] # ax2.set_xticklabels(['{}'.format(i) for i in xticks]) with mfdset(fil) as fh, mfdset(fil2) as fh2: geofil = 'ocean_geometry.nc' vgeofil = 'Vertical_coordinate.nc' domain = Domain.Domain2(geofil, vgeofil, -0.5, 0, 10, 60, ls=0, le=None) e = gv('e', domain, 'hi', fh).read_array() ax = plt.subplot(gs[4]) ax.plot(domain.lath[e.plot_slice[2, 0]:e.plot_slice[2, 1]], np.mean(e.values, axis=(0, 3)).T[:, ::2], 'k', lw=1) ax.plot(domain.lath[e.plot_slice[2, 0]:e.plot_slice[2, 1]], np.mean(e.values, axis=(0, 3)).T[:, -1], 'k', lw=1) ax.set_yticklabels('') ax.set_xlabel('y ($^{\circ}$N)') ax.axvline(x=38.5, color='k') ax.grid() swash = gv('islayerdeep', domain, 'ql', fh2, plot_loc='hl').xsm().ysm().read_array( extend_kwargs=dict(method='mirror'), tmean=False).move_to('ul').move_to('hl') swash0 = fh2.variables['islayerdeep'][-1, 0, 0, 320] swash = (-swash + swash0) * (100 / swash0) z = np.linspace(-3000, 0) swash = swash.toz(z, e=e) ax.contour(swash.dom.lath[e.plot_slice[2, 0]:e.plot_slice[2, 1]], z, np.nanmean(swash.values, axis=(0, 3)), levels=[1], colors='r') domain = Domain.Domain2(geofil, vgeofil, -0.5, 0, 38, 39, ls=0, le=None) ax = plt.subplot(gs[5]) e = gv('e', domain, 'hi', fh).read_array() ax.plot(domain.lonh[e.plot_slice[3, 0]:e.plot_slice[3, 1]], np.mean(e.values, axis=(0, 2)).T[:, ::2], 'k', lw=1) ax.plot(domain.lonh[e.plot_slice[3, 0]:e.plot_slice[3, 1]], np.mean(e.values, axis=(0, 2)).T[:, -1], 'k', lw=1) ax.set_yticklabels('') ax.set_xlabel('x ($^{\circ}$)') swash = gv('islayerdeep', domain, 'ql', fh2, plot_loc='hl').xsm().ysm().read_array( tmean=False).move_to('ul').move_to('hl') swash0 = fh2.variables['islayerdeep'][-1, 0, 0, 320] swash = (-swash + swash0) * (100 / swash0) z = np.linspace(-3000, 0) swash = swash.toz(z, e=e) ax.contour(swash.dom.lonh[swash.plot_slice[3, 0]:swash.plot_slice[3, 1]], z, np.nanmean(swash.values, axis=(0, 2)), levels=[1], colors='r') xdegtokm(ax, (38 + 39) / 2) ax.grid() #swash.plot('nanmean',(0,2),zcoord=True,e=e,z=np.linspace(-3000,0),cbar=True,ax=ax) return fig
def extract_twamomy_terms(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs, ze, meanax, fil3=None, alreadysaved=False, xyasindices=False, calledfrompv=False, z=np.linspace(-3000, 0, 100), htol=1e-3): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fhvgeo = dset(vgeofil) db = -fhvgeo.variables['g'][:] dbi = np.append(db, 0) fhvgeo.close() fhgeo = dset(geofil) fh = mfdset(fil) fh2 = mfdset(fil2) zi = rdp1.getdims(fh)[2][0] dbl = np.diff(zi) * 9.8 / 1031 if xyasindices: (xs, xe), (ys, ye) = (xstart, xend), (ystart, yend) _, _, dimv = rdp1.getdimsbyindx(fh, xs, xe, ys, ye, zs=zs, ze=ze, ts=0, te=None, xhxq='xh', yhyq='yq', zlzi='zl') else: (xs, xe), (ys, ye), dimv = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, yhyq='yq') sl = np.s_[:, :, ys:ye, xs:xe] slmx = np.s_[:, :, ys:ye, xs - 1:xe] D, (ah, aq) = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[0:2] Dforgetutwaforxdiff = rdp1.getgeombyindx(fhgeo, xs - 1, xe, ys, ye)[0] Dforgetutwaforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye + 1)[0] Dforgethvforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye)[0] dxt, dyt = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye + 1)[2][6:8] dxcv, dycv = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[2][2:4] dxcvforxdiff, dycvforxdiff = rdp1.getgeombyindx( fhgeo, xs - 1, xe, ys, ye)[2][2:4] dxcvforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye + 1)[2][3:4] dxbu, dybu = rdp1.getgeombyindx(fhgeo, xs - 1, xe, ys, ye)[2][4:6] nt_const = dimv[0].size t0 = time.time() dt = fh.variables['average_DT'][:] dt = dt[:, np.newaxis, np.newaxis, np.newaxis] if fil3: fh3 = mfdset(fil3) slmxtn = np.s_[-1:, :, ys:ye, xs - 1:xe] # islayerdeep0 = fh3.variables['islayerdeep'][:,0,0,0].sum() # islayerdeep = (fh3.variables['islayerdeep'][slmx].filled(np.nan)).sum(axis=0, # keepdims=True) islayerdeep0 = fh3.variables['islayerdeep'][-1:, 0, 0, 0] islayerdeep = (fh3.variables['islayerdeep'][slmxtn].filled(np.nan)) islayerdeep[:, :, :, -1:] = islayerdeep[:, :, :, -2:-1] swash = (islayerdeep0 - islayerdeep) / islayerdeep0 * 100 swash = 0.5 * (swash[:, :, :, :-1] + swash[:, :, :, 1:]) fh3.close() else: swash = None em = (fh2.variables['e'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) elm = 0.5 * (em[:, 0:-1, :, :] + em[:, 1:, :, :]) vh = (fh.variables['vh_masked'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) h_cv = (fh.variables['h_Cv'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) h_cv[h_cv < htol] = np.nan h_vm = h_cv vtwa = vh / h_cv / dxcv vhforxdiff = (fh.variables['vh_masked'][0:, zs:ze, ys:ye, xs - 1:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) h_cvforxdiff = (fh.variables['h_Cv'][0:, zs:ze, ys:ye, xs - 1:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) h_cvforxdiff[h_cvforxdiff < htol] = np.nan vtwaforxdiff = vhforxdiff / h_cvforxdiff #/dxcvforxdiff vtwaforxdiff = np.concatenate( (vtwaforxdiff, vtwaforxdiff[:, :, :, -1:]), axis=3) vhforydiff = ( fh.variables['vh_masked'][0:, zs:ze, ys - 1:ye + 1, xs:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) h_cvforydiff = (fh.variables['h_Cv'][0:, zs:ze, ys - 1:ye + 1, xs:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) h_cvforydiff[h_cvforydiff < htol] = np.nan vtwaforydiff = vhforydiff / h_cvforydiff #/dxcvforydiff vtwax = np.diff(vtwaforxdiff, axis=3) / dxbu / dybu vtwax = 0.5 * (vtwax[:, :, :, 0:-1] + vtwax[:, :, :, 1:]) vtway = np.diff(vtwaforydiff, axis=2) / dyt / dxt vtway = 0.5 * (vtway[:, :, 0:-1, :] + vtway[:, :, 1:, :]) hvmy = np.diff(vhforydiff, axis=2) / dyt / dxt hvmy = 0.5 * (hvmy[:, :, :-1, :] + hvmy[:, :, 1:, :]) uh = (fh.variables['uh_masked'][0:, zs:ze, ys:ye + 1, xs - 1:xe] * dt).filled(0).sum(axis=0, keepdims=True) / np.sum(dt) hum = 0.25 * (uh[:, :, :-1, :-1] + uh[:, :, :-1, 1:] + uh[:, :, 1:, :-1] + uh[:, :, 1:, 1:]) / dycv humx = np.diff(np.nan_to_num(uh), axis=3) / dxt / dyt humx = 0.5 * (humx[:, :, :-1, :] + humx[:, :, 1:, :]) huvxphvvym = ( fh.variables['twa_huvxpt'][0:, zs:ze, ys:ye, xs:xe] * dt + fh.variables['twa_hvvymt'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) hvv = (fh.variables['hvv_Cv'][0:, zs:ze, ys - 1:ye + 1, xs:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) hvvym = np.diff(hvv, axis=2) / dxt / dyt hvvym = 0.5 * (hvvym[:, :, :-1, :] + hvvym[:, :, 1:, :]) # hvv = (fh.variables['hvv_T'][0:,zs:ze,ys:ye+1,xs:xe]*dt).sum(axis=0,keepdims=True)*dxt/np.sum(dt) # hvvym = np.diff(hvv,axis=2)/dycv/dxcv huvxm = -(huvxphvvym + hvvym) # hvv = (fh.variables['hvv_Cv'][0:,zs:ze,ys-1:ye+1,xs:xe]*dt).sum(axis=0,keepdims=True)/np.sum(dt) # hvvym = np.diff(hvv,axis=2)/dxt/dyt # hvvym = 0.5*(hvvym[:,:,:-1,:] + hvvym[:,:,1:,:]) # huv = (fh.variables['huv_Bu'][0:,zs:ze,ys:ye,xs-1:xe].filled(0)*dt).sum(axis=0,keepdims=True)/np.sum(dt) # huvxm = np.diff(huv,axis=3)/dxcv vtwaforvdiff = np.concatenate((vtwa[:, [0], :, :], vtwa), axis=1) vtwab = np.diff(vtwaforvdiff, axis=1) / db[:, np.newaxis, np.newaxis] vtwab = np.concatenate( (vtwab, np.zeros([vtwab.shape[0], 1, vtwab.shape[2], vtwab.shape[3]])), axis=1) vtwab = 0.5 * (vtwab[:, 0:-1, :, :] + vtwab[:, 1:, :, :]) hwb = (fh2.variables['wd'][0:, zs:ze, ys:ye + 1, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) hwb = np.diff(hwb, axis=1) hwb_v = 0.5 * (hwb[:, :, :-1, :] + hwb[:, :, 1:, :]) hwb = (fh2.variables['wd'][0:, zs:ze, ys:ye + 1, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) hwm = hwb_v * dbl[:, np.newaxis, np.newaxis] hwm = 0.5 * (hwb[:, :-1] + hwb[:, 1:]) * dbl[:, np.newaxis, np.newaxis] hwm_v = 0.5 * (hwm[:, :, :-1, :] + hwm[:, :, 1:, :]) #hwb_v = fh.variables['hwb_Cv'][0:,zs:ze,ys:ye,xs:xe] #hwm_v = fh.variables['hw_Cv'][0:,zs:ze,ys:ye,xs:xe] esq = (fh.variables['esq'][0:, zs:ze, ys:ye + 1, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) emforydiff = (fh2.variables['e'][0:, zs:ze, ys:ye + 1, xs:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) elmforydiff = 0.5 * (emforydiff[:, 0:-1, :, :] + emforydiff[:, 1:, :, :]) edlsqm = (esq - elmforydiff**2) edlsqmy = np.diff(edlsqm, axis=2) / dycv hpfv = (fh.variables['twa_hpfv'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) pfvm = (fh2.variables['PFv'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) edpfvdmb = -hpfv + h_cv * pfvm - 0.5 * edlsqmy * dbl[:, np.newaxis, np.newaxis] hmfum = (fh.variables['twa_hmfu'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) hvwbm = (fh.variables['twa_hvwb'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) hdiffvm = (fh.variables['twa_hdiffv'][0:, zs:ze, ys:ye, xs:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) hdvdtviscm = (fh.variables['twa_hdvdtvisc'][0:, zs:ze, ys:ye, xs:xe] * dt).sum(axis=0, keepdims=True) / np.sum(dt) fh2.close() fh.close() advx = hum * vtwax / h_vm advy = vtwa * vtway advb = hwm_v * vtwab / h_vm cor = hmfum / h_vm pfvm = pfvm xdivep1 = -huvxm / h_vm xdivep2 = advx xdivep3 = vtwa * humx / h_vm xdivep = (xdivep1 + xdivep2 + xdivep3) ydivep1 = -hvvym / h_vm ydivep2 = advy ydivep3 = vtwa * hvmy / h_vm ydivep4 = -0.5 * edlsqmy * dbl[:, np.newaxis, np.newaxis] / h_vm ydivep = (ydivep1 + ydivep2 + ydivep3 + ydivep4) bdivep1 = hvwbm / h_vm bdivep2 = advb bdivep3 = vtwa * hwb_v / h_vm bdivep4 = -edpfvdmb / h_vm bdivep = (bdivep1 + bdivep2 + bdivep3 + bdivep4) Y1twa = hdiffvm / h_vm Y2twa = hdvdtviscm / h_vm terms = np.concatenate( (-advx[:, :, :, :, np.newaxis], -advy[:, :, :, :, np.newaxis], -advb[:, :, :, :, np.newaxis], cor[:, :, :, :, np.newaxis], pfvm[:, :, :, :, np.newaxis], xdivep[:, :, :, :, np.newaxis], ydivep[:, :, :, :, np.newaxis], bdivep[:, :, :, :, np.newaxis], Y1twa[:, :, :, :, np.newaxis], Y2twa[:, :, :, :, np.newaxis]), axis=4) termsep = np.concatenate( (xdivep1[:, :, :, :, np.newaxis], xdivep3[:, :, :, :, np.newaxis], ydivep1[:, :, :, :, np.newaxis], ydivep3[:, :, :, :, np.newaxis], ydivep4[:, :, :, :, np.newaxis], bdivep1[:, :, :, :, np.newaxis], bdivep3[:, :, :, :, np.newaxis], bdivep4[:, :, :, :, np.newaxis]), axis=4) termsm = np.nanmean(terms, meanax, keepdims=True) termsepm = np.nanmean(termsep, meanax, keepdims=True) X = dimv[keepax[1]] Y = dimv[keepax[0]] if 1 in keepax and not calledfrompv: em = np.nanmean(em, axis=meanax, keepdims=True) elm = np.nanmean(elm, axis=meanax, keepdims=True) #z = np.linspace(-3000,0,100) Y = z P = getvaratzc5(termsm.astype(np.float32), z.astype(np.float32), em.astype(np.float32)) Pep = getvaratzc5(termsepm.astype(np.float32), z.astype(np.float32), em.astype(np.float32)) if fil3: swash = np.nanmean(swash, meanax, keepdims=True) swash = getvaratzc(swash.astype(np.float32), z.astype(np.float32), em.astype(np.float32)).squeeze() else: P = termsm.squeeze() Pep = termsepm.squeeze() if not calledfrompv: np.savez('twamomy_complete_terms', X=X, Y=Y, P=P, Pep=Pep) else: npzfile = np.load('twamomy_complete_terms.npz') X = npzfile['X'] Y = npzfile['Y'] P = npzfile['P'] Pep = npzfile['Pep'] return (X, Y, P, Pep, swash, em.squeeze())
def get_deddy_coeffs_fromflx(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs=0, ze=None, zlim=(-1500, 0), percx=0, percy=0, nsqdep=False, fil3=None, swashperc=1): fhgeo = dset(geofil) fhvgeo = dset(vgeofil) fh = mfdset(fil) fh2 = mfdset(fil2) db = fhvgeo.variables['g'][:] fhvgeo.close() dbi = np.append(db, 0) zi = fh.variables['zi'][:] zl = fh.variables['zl'][:] dbl = np.diff(zi) * 9.8 / 1031 dt = fh.variables['average_DT'][:] dt = dt[:, np.newaxis, np.newaxis, np.newaxis] z = np.linspace(zlim[0], zlim[1], 100) sl, dimv = rdp1.getslice(fh, xstart, xend, ystart, yend, yhyq='yq') sl2d = sl[2:] dycv = fhgeo.variables['dyCv'][sl2d] slpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), sl[3]] f = fhgeo.variables['f'][sl2d] e = (fh2.variables['e'][slpy] * dt).sum(axis=0, keepdims=True) / dt.sum(axis=0) eatv = 0.5 * (e[:, :, :-1, :] + e[:, :, 1:, :]) v, h = pv.getvtwa(fhgeo, fh, fh2, sl) v = v[:, :, :, :-1] h = h[:, :, :, :-1] sig = h / dbl[:, np.newaxis, np.newaxis] hi = 0.5 * (h[:, :-1] + h[:, 1:]) sigi = hi / dbi[1:-1, np.newaxis, np.newaxis] vb = -np.diff(v, axis=1) / dbi[1:-1, np.newaxis, np.newaxis] #vb = np.concatenate((vb[:,:1,:,:],vb,vb[:,-1:,:,:]),axis=1) vi = np.concatenate((v[:, :1, :, :], v, -v[:, -1:, :, :]), axis=1) vi = 0.5 * (vi[:, :-1, :, :] + vi[:, 1:, :, :]) vib = -np.diff(vi, axis=1) / dbl[:, np.newaxis, np.newaxis] if nsqdep: fsqvb = f**2 * vb * sigi else: fsqvb = f**2 * vb fsqvbaz = getvaratzc(fsqvb.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) esq = (fh.variables['esq'][slpy] * dt).sum(axis=0, keepdims=True) / np.sum(dt) elmforydiff = 0.5 * (e[:, 0:-1, :, :] + e[:, 1:, :, :]) edlsqm = (esq - elmforydiff**2) edlsqmy = np.diff(edlsqm, axis=2) / dycv hpfv = (fh.variables['twa_hpfv'][sl] * dt).sum(axis=0, keepdims=True) / np.sum(dt) pfvm = (fh2.variables['PFv'][sl] * dt).sum(axis=0, keepdims=True) / np.sum(dt) edpfvdmb = -(-hpfv + h * pfvm - 0.5 * edlsqmy * dbl[:, np.newaxis, np.newaxis]) fh.close() fh2.close() fhgeo.close() zdpfvd = sint.cumtrapz(edpfvdmb, dx=-dbl[0], axis=1) # zdpfvd = np.concatenate((np.zeros(zdpfvd[:,:1,:,:].shape), # zdpfvd, # np.zeros(zdpfvd[:,:1,:,:].shape)),axis=1) # zdpfvd = 0.5*(zdpfvd[:,:-1,:,:]+zdpfvd[:,1:,:,:]) zdpfvdaz = getvaratzc(zdpfvd.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) fsqvbazm = np.apply_over_axes(np.nanmean, fsqvbaz, (0, 2)) zdpfvdazm = np.apply_over_axes(np.nanmean, zdpfvdaz, (0, 2)) fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 3)) cmax = np.fabs(np.percentile(zdpfvdazm, (1, 99))).max() im = ax[0].pcolormesh(dimv[3], z, zdpfvdazm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[0]) cmax = np.fabs(np.percentile(fsqvbazm, (1, 99))).max() im = ax[1].pcolormesh(dimv[3], z, fsqvbazm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[1]) if fil3: fh3 = mfdset(fil3) slmxtn = np.s_[-1:, sl[1], sl[2], (sl[3].start - 1):sl[3].stop] islayerdeep0 = fh3.variables['islayerdeep'][-1:, 0, 0, 0] islayerdeep = fh3.variables['islayerdeep'][slmxtn] if np.ma.is_masked(islayerdeep): islayerdeep = islayerdeep.filled(np.nan) islayerdeep[:, :, :, -1:] = islayerdeep[:, :, :, -2:-1] swash = (islayerdeep0 - islayerdeep) / islayerdeep0 * 100 swash = 0.5 * (swash[:, :, :, :-1] + swash[:, :, :, 1:]) fh3.close() swash = getvaratzc(swash.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) swash = np.apply_over_axes(np.nanmean, swash, (0, 2)) em = np.apply_over_axes(np.nanmean, e, (0, 2)) xx, zz = np.meshgrid(dimv[3], zi) for axc in ax: axc.contour(dimv[3], z, swash.squeeze(), np.array([swashperc]), colors='k') axc.contour(xx, em.squeeze(), zz, ls='k--') axc.set_ylim(zlim[0], zlim[1]) fig2, ax = plt.subplots(1, 1, sharey=True, figsize=(12, 3)) ax.linfit(fsqvbaz, zdpfvdaz, percx=percx, percy=percy) ax.set_xlabel(r'$f^2 v_b$') ax.set_ylabel(r'$\zeta^{\prime} m_y^{\prime}$') return fig, fig2
def extract_pvterms(geofil, fil, xstart, xend, ystart, yend, zs, ze, meanax, savfil=None, alreadysaved=False): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fh = mfdset(fil) (xs, xe), (ys, ye), dimq = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xq', yhyq='yq') _, _, dimqp1 = rdp1.getdimsbyindx(fh, xs, xe, ys - 1, ye, zs=zs, ze=ze, xhxq='xq', yhyq='yq') D, (ah, aq), (dxcu, dycu, dxcv, dycv, dxbu, dybu, dxt, dyt) = rdp1.getgeombyindx(geofil, xs, xe, ys, ye)[0:3] D_u = rdp1.getgeombyindx(geofil, xs, xe, ys - 1, ye)[0] D_v = rdp1.getgeombyindx(geofil, xs - 1, xe, ys, ye)[0] nt = dimq[0].size omega = 2 * np.pi / 24 / 3600 + 2 * np.pi / 24 / 3600 / 365 R = 6378000 f_q = 2 * omega * np.sin(dimq[2] * np.pi / 180) beta = 2 * omega * np.cos(dimq[2][None, :, None] * np.pi / 180) / R t0 = time.time() frhatu = fh.variables['frhatu'][0:1, zs:ze, ys - 1:ye, xs:xe] frhatv = fh.variables['frhatv'][0:1, zs:ze, ys:ye, xs - 1:xe] h_u = frhatu * D_u[np.newaxis, np.newaxis, :, :] h_v = frhatv * D_v[np.newaxis, np.newaxis, :, :] h_q = 0.25 * (h_u[:, :, 0:-1, :] + h_u[:, :, 1:, :] + h_v[:, :, :, 0:-1] + h_v[:, :, :, 1:]) h = fh.variables['h'][0:1, zs:ze, ys:ye, xs:xe] u = fh.variables['u'][0:1, zs:ze, ys:ye, xs - 1:xe] v = fh.variables['v'][0:1, zs:ze, ys - 1:ye, xs:xe] uh = fh.variables['uh'][0:1, zs:ze, ys:ye, xs - 1:xe] vh = fh.variables['vh'][0:1, zs:ze, ys - 1:ye, xs:xe] wd = fh.variables['wd'][0:1, zs:ze, ys:ye, xs:xe] cau = fh.variables['CAu'][0:1, zs:ze, ys:ye + 1, xs:xe] gkeu = fh.variables['gKEu'][0:1, zs:ze, ys:ye + 1, xs:xe] rvxv = fh.variables['rvxv'][0:1, zs:ze, ys:ye + 1, xs:xe] pfu = fh.variables['PFu'][0:1, zs:ze, ys:ye + 1, xs:xe] dudtvisc = fh.variables['du_dt_visc'][0:1, zs:ze, ys:ye + 1, xs:xe] diffu = fh.variables['diffu'][0:1, zs:ze, ys:ye + 1, xs:xe] cav = fh.variables['CAv'][0:1, zs:ze, ys:ye, xs:xe + 1] gkev = fh.variables['gKEv'][0:1, zs:ze, ys:ye, xs:xe + 1] rvxu = fh.variables['rvxu'][0:1, zs:ze, ys:ye, xs:xe + 1] pfv = fh.variables['PFv'][0:1, zs:ze, ys:ye, xs:xe + 1] diffv = fh.variables['diffv'][0:1, zs:ze, ys:ye, xs:xe + 1] dvdtvisc = fh.variables['dv_dt_visc'][0:1, zs:ze, ys:ye, xs:xe + 1] uadv = -gkeu - rvxv uadv = np.ma.filled(uadv.astype(float), 0) uadvym = h_q * (np.diff(uadv, axis=2) / dybu) / nt vadv = -gkev - rvxu vadv = np.ma.filled(vadv.astype(float), 0) vadvxm = h_q * (diffx_bound(vadv, dxbu)) / nt fv = cau - gkeu - rvxv fv = np.ma.filled(fv.astype(float), 0) fvym = h_q * (np.diff(fv, axis=2) / dybu) / nt fu = -cav + gkev + rvxu fu = np.ma.filled(fu.astype(float), 0) fuxm = h_q * (diffx_bound(fu, dxbu)) / nt Y1 = diffv Y1 = np.ma.filled(Y1.astype(float), 0) Y1xm = h_q * (diffx_bound(Y1, dxbu)) / nt Y2 = dvdtvisc Y2 = np.ma.filled(Y2.astype(float), 0) Y2xm = h_q * (diffx_bound(Y2, dxbu)) / nt # hbetavm = (h_v*beta*v)/nt u = np.ma.filled(u.astype(float), 0) ux = np.diff(u, axis=3) / dxt v = np.ma.filled(v.astype(float), 0) vy = np.diff(v, axis=2) / dyt uh = np.ma.filled(uh.astype(float), 0) uh_x = np.diff(uh, axis=3) / ah uhxm = f_q[np.newaxis, np.newaxis, :, np.newaxis] * (uh_x - h * ux) / nt vh = np.ma.filled(vh.astype(float), 0) vh_y = np.diff(vh, axis=2) / ah vhym = f_q[np.newaxis, np.newaxis, :, np.newaxis] * (vh_y - h * vy) / nt fdiapycm = f_q[np.newaxis, np.newaxis, :, np.newaxis] * np.diff( wd, axis=1) / nt if 1 in keepax: em = fh.variables['e'][0:1, zs:ze, ys:ye, xs:xe] / nt for i in range(1, nt): frhatu = fh.variables['frhatu'][i:i + 1, zs:ze, ys - 1:ye, xs:xe] frhatv = fh.variables['frhatv'][i:i + 1, zs:ze, ys:ye, xs - 1:xe] h_u = frhatu * D_u[np.newaxis, np.newaxis, :, :] h_v = frhatv * D_v[np.newaxis, np.newaxis, :, :] h_q = 0.25 * (h_u[:, :, 0:-1, :] + h_u[:, :, 1:, :] + h_v[:, :, :, 0:-1] + h_v[:, :, :, 1:]) h = fh.variables['h'][i:i + 1, zs:ze, ys:ye, xs:xe] u = fh.variables['u'][i:i + 1, zs:ze, ys:ye, xs - 1:xe] v = fh.variables['v'][i:i + 1, zs:ze, ys - 1:ye, xs:xe] uh = fh.variables['uh'][i:i + 1, zs:ze, ys:ye, xs - 1:xe] vh = fh.variables['vh'][i:i + 1, zs:ze, ys - 1:ye, xs:xe] wd = fh.variables['wd'][i:i + 1, zs:ze, ys:ye, xs:xe] cau = fh.variables['CAu'][i:i + 1, zs:ze, ys:ye + 1, xs:xe] gkeu = fh.variables['gKEu'][i:i + 1, zs:ze, ys:ye + 1, xs:xe] rvxv = fh.variables['rvxv'][i:i + 1, zs:ze, ys:ye + 1, xs:xe] pfu = fh.variables['PFu'][i:i + 1, zs:ze, ys:ye + 1, xs:xe] dudtvisc = fh.variables['du_dt_visc'][i:i + 1, zs:ze, ys:ye + 1, xs:xe] diffu = fh.variables['diffu'][i:i + 1, zs:ze, ys:ye + 1, xs:xe] cav = fh.variables['CAv'][i:i + 1, zs:ze, ys:ye, xs:xe + 1] gkev = fh.variables['gKEv'][i:i + 1, zs:ze, ys:ye, xs:xe + 1] rvxu = fh.variables['rvxu'][i:i + 1, zs:ze, ys:ye, xs:xe + 1] pfv = fh.variables['PFv'][i:i + 1, zs:ze, ys:ye, xs:xe + 1] diffv = fh.variables['diffv'][i:i + 1, zs:ze, ys:ye, xs:xe + 1] dvdtvisc = fh.variables['dv_dt_visc'][i:i + 1, zs:ze, ys:ye, xs:xe + 1] uadv = -gkeu - rvxv uadv = np.ma.filled(uadv.astype(float), 0) uadvym += h_q * (np.diff(uadv, axis=2) / dybu) / nt vadv = -gkev - rvxu vadv = np.ma.filled(vadv.astype(float), 0) vadvxm += h_q * (diffx_bound(vadv, dxbu)) / nt fv = cau - gkeu - rvxv fv = np.ma.filled(fv.astype(float), 0) fvym += h_q * (np.diff(fv, axis=2) / dybu) / nt fu = -cav + gkev + rvxu fu = np.ma.filled(fu.astype(float), 0) fuxm += h_q * (diffx_bound(fu, dxbu)) / nt Y1 = diffv Y1 = np.ma.filled(Y1.astype(float), 0) Y1xm += h_q * (diffx_bound(Y1, dxbu)) / nt Y2 = dvdtvisc Y2 = np.ma.filled(Y2.astype(float), 0) Y2xm += h_q * (diffx_bound(Y2, dxbu)) / nt # hbetavm += (h_v*beta*v)/nt u = np.ma.filled(u.astype(float), 0) ux = np.diff(u, axis=3) / dxt v = np.ma.filled(v.astype(float), 0) vy = np.diff(v, axis=2) / dyt uh = np.ma.filled(uh.astype(float), 0) uh_x = np.diff(uh, axis=3) / ah uhxm += f_q[np.newaxis, np.newaxis, :, np.newaxis] * (uh_x - h * ux) / nt vh = np.ma.filled(vh.astype(float), 0) vh_y = np.diff(vh, axis=2) / ah vhym += f_q[np.newaxis, np.newaxis, :, np.newaxis] * (vh_y - h * vy) / nt fdiapycm += f_q[np.newaxis, np.newaxis, :, np.newaxis] * np.diff( wd, axis=1) / nt if 1 in keepax: em += fh.variables['e'][i:i + 1, zs:ze, ys:ye, xs:xe] / nt sys.stdout.write('\r' + str(int((i + 1) / nt * 100)) + '% done...') sys.stdout.flush() fh.close() print('Time taken for reading: {}'.format(time.time() - t0)) terms = np.ma.concatenate( (uadvym[:, :, :, :, np.newaxis], vadvxm[:, :, :, :, np.newaxis], Y1xm[:, :, :, :, np.newaxis], Y2xm[:, :, :, :, np.newaxis], fdiapycm[:, :, :, :, np.newaxis], uhxm[:, :, :, :, np.newaxis], vhym[:, :, :, :, np.newaxis]), axis=4) termsm = np.ma.apply_over_axes(np.nanmean, terms, meanax) X = dimq[keepax[1]] Y = dimq[keepax[0]] if 1 in keepax: elm = 0.5 * (em[:, 0:-1, :, :] + em[:, 1:, :, :]) em = np.ma.apply_over_axes(np.mean, em, meanax) elm = np.ma.apply_over_axes(np.mean, elm, meanax) Y = elm.squeeze() X = np.meshgrid(X, dimq[1])[0] P = termsm.squeeze() P = np.ma.filled(P.astype(float), np.nan) X = np.ma.filled(X.astype(float), np.nan) Y = np.ma.filled(Y.astype(float), np.nan) np.savez('pv_terms', X=X, Y=Y, P=P) else: npzfile = np.load('pv_terms.npz') X = npzfile['X'] Y = npzfile['Y'] P = npzfile['P'] return (X, Y, P)
def get_heddy_coeffs(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs=0, ze=None, z=np.linspace(-3000, 0, 100), percx=0, percy=0): fhgeo = dset(geofil) fhvgeo = dset(vgeofil) fh = mfdset(fil) fh2 = mfdset(fil2) db = fhvgeo.variables['g'][:] fhvgeo.close() dbi = np.append(db, 0) zi = fh.variables['zi'][:] zl = fh.variables['zl'][:] dbl = np.diff(zi) * 9.8 / 1031 dt = fh.variables['average_DT'][:] dt = dt[:, np.newaxis, np.newaxis, np.newaxis] sl, dimv = rdp1.getslice(fh, xstart, xend, ystart, yend, yhyq='yq') slmx = np.s_[:, :, sl[2], (sl[3].start - 1):sl[3].stop] slpx = np.s_[:, :, sl[2], (sl[3].start + 1):sl[3].stop] slmxpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), (sl[3].start - 1):sl[3].stop] slpy = np.s_[:, :, sl[2].start:(sl[2].stop + 1), sl[3]] sl2d = sl[2:] slmx2d = slmx[2:] slpx2d = slpx[2:] dxbu = fhgeo.variables['dxBu'][slmx2d] dxcv = fhgeo.variables['dxCv'][sl2d] v, _ = pv.getvtwa(fhgeo, fh, fh2, slmx) vx = np.diff(v, axis=3) / dxbu vxx = np.diff(vx, axis=3) / dxcv e = (fh2.variables['e'][slpy] * dt).sum(axis=0, keepdims=True) / dt.sum( axis=0, keepdims=True) eatv = 0.5 * (e[:, :, :-1, :] + e[:, :, 1:, :]) vxx = getvaratzc(vxx.astype(np.float32), z.astype(np.float32), eatv.astype(np.float32)) e = fh2.variables['e'][slmxpy] eatvmx = 0.5 * (e[:, :, :-1, :] + e[:, :, 1:, :]) vaz = getvaratzc(v.astype(np.float32), z.astype(np.float32), eatvmx.astype(np.float32)) vazx = np.diff(vaz, axis=3) / dxbu vazxx = np.diff(vazx, axis=3) / dxcv x, y, P, _, _ = py.extract_twamomy_terms(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs, ze, (0, )) uv = P[:, :, :, :, 5] vvalid = vaz[:, :, :, 1:-1] vazm = np.apply_over_axes(np.nanmean, vvalid, (0, 2)) vxxm = np.apply_over_axes(np.nanmean, vxx, (0, 2)) vazxxm = np.apply_over_axes(np.nanmean, vazxx, (0, 2)) uvm = np.apply_over_axes(np.nanmean, uv, (0, 2)) fig, ax = plt.subplots(1, 4, sharex=True, sharey=True, figsize=(12, 3)) cmax = np.fabs(np.percentile(vxxm, (1, 99))).max() im = ax[0].pcolormesh(dimv[3], z, vxxm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[0]) cmax = np.fabs(np.percentile(vazxxm, (1, 99))).max() im = ax[1].pcolormesh(dimv[3], z, vazxxm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[1]) cmax = np.fabs(np.percentile(vvalid, (0.5, 99.5))).max() im = ax[2].pcolormesh(dimv[3], z, vazm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') fig.colorbar(im, ax=ax[2]) cmax = np.fabs(np.percentile(uvm, (0.5, 99.5))).max() im = ax[3].pcolormesh(dimv[3], z, uvm.squeeze(), vmax=cmax, vmin=-cmax, cmap='RdBu_r') cb = fig.colorbar(im, ax=ax[3]) cb.formatter.set_powerlimits((0, 0)) cb.update_ticks() for axc in ax: xdegtokm(axc, 0.5 * (ystart + yend)) axc.set_xlabel('x (km)') axc.grid() ax[0].set_ylabel('z (m)') fig2, ax = plt.subplots(1, 2, sharey=True) ax[0].linfit(vvalid, uv, percx=percx, percy=percy) ax[0].set_xlabel('v (m/s)') ax[0].set_ylabel('RS div (m/s2)') ax[0].grid() ax[1].linfit(vxx, uv, percx=percx, percy=percy) ax[1].set_xlabel('vxx (1/ms)') ax[1].grid() return fig, fig2
def extract_ep_terms_pym6(initializer): domain = Domain.Domain(initializer) plot_loc = 'vl' with mfdset(initializer.fil) as fh, mfdset(initializer.fil2) as fh2: #initializer.z = np.linspace(-500, 0, 20) e = (gv('e', domain, 'hi', fh2, fh, plot_loc=plot_loc) .yep().read_array( extend_kwargs={'method': 'mirror'}).move_to('vi')) h = (gv('h_Cv', domain, plot_loc, fh2, fh, plot_loc=plot_loc) .read_array(filled=0)) vr = (gv('vh', domain, plot_loc, fh2, fh, plot_loc=plot_loc, divisor='h_Cv').read_array( divide_by_dx=True, filled=0)) hum = (gv('uh', domain, 'ul', fh2, fh, plot_loc=plot_loc).xsm().yep() .read_array( divide_by_dy=True, filled=0, extend_kwargs={'method': 'vorticity'}) .move_to('hl').move_to(plot_loc)) huvm = (gv('huv_Bu', domain, 'ql', fh2, fh, plot_loc=plot_loc).xsm() .read_array( filled=0, extend_kwargs={'method': 'vorticity'}).move_to(plot_loc)) uv_e_flux = (huvm - vr * hum) / h uv_e_flux = uv_e_flux.mean(axis=initializer.meanax).toz(initializer.z, e=e) ex = (gv('e', domain, 'hi', fh2, fh, plot_loc=plot_loc) .xsm().xep().yep().read_array(extend_kwargs={'method': 'mirror'}) .ddx(3).move_to('hi').move_to('vi').move_to('vl')) ex = ex.mean(axis=initializer.meanax).toz(initializer.z, e=e) e1 = (gv('e', domain, 'hi', fh2, fh, plot_loc=plot_loc) .yep().read_array(extend_kwargs={'method': 'mirror'}) .move_to('hl')) esq = (gv('esq', domain, 'hl', fh2, fh, plot_loc=plot_loc) .yep().read_array(extend_kwargs={'method': 'mirror'})) edlsqm = esq - e1 * e1 edlsqmy = edlsqm.ddx(2) hpfv = (gv('twa_hpfv', domain, plot_loc, fh2, fh, plot_loc=plot_loc) .read_array(filled=0)) pfvm = (gv('PFv', domain, plot_loc, fh2, fh, plot_loc=plot_loc) .read_array(filled=0)) edpfvdmb = -hpfv + h * pfvm - edlsqmy * domain.db * 0.5 edpfvdmb1 = copy.copy(edpfvdmb) edpfvdmb1 = edpfvdmb1.mean(axis=initializer.meanax).toz(initializer.z, e=e) edpfvdmb = edpfvdmb / domain.db edpfvdm = edpfvdmb.vert_integral() edpfvdm = edpfvdm.mean(axis=initializer.meanax).toz(initializer.z, e=e) flux_list = [uv_e_flux, edpfvdm] lab = [ r"""$\widehat{u^{\prime \prime}v^{\prime \prime}}(\hat{i} + \bar{\zeta_{\tilde{x}}}\hat{k})$""", r"""$\overline{\zeta^\prime m_{\tilde{y}}^\prime} \hat{k}$""", r"""$\widehat{u^{\prime \prime}v^{\prime \prime}}(\hat{i} + \bar{\zeta_{\tilde{x}}}\hat{k}) +\overline{\zeta^\prime m_{\tilde{y}}^\prime} \hat{k}$""" ] dz = np.diff(initializer.z)[0] dx = np.radians( np.diff(domain.lonh[ex._plot_slice[3, 0]:ex._plot_slice[3, 1]])[0] ) * 6378000 * np.cos( np.radians(0.5 * (initializer.slat + initializer.nlat))) fig, ax = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(10, 5)) units = 'xy' angles = 'xy' q1 = ax[0].quiver( domain.lonh[ex._plot_slice[3, 0]:ex._plot_slice[3, 1]], initializer.z[::2], uv_e_flux.values.squeeze()[::2] / dx * np.sqrt(dx**2 + dz**2), uv_e_flux.values.squeeze()[::2] * ex.values.squeeze()[::2] / dz * np.sqrt(dx**2 + dz**2), units=units) # angles=angles) tx = ax[0].text(0.05, 0.1, lab[0], transform=ax[0].transAxes) tx.set_fontsize(15) tx.set_bbox(dict(facecolor='white', alpha=1, edgecolor='white')) ax[0].quiverkey( q1, 0.75, 1.05, 1e-2, r'$1e-2$', labelpos='E', coordinates='axes') xdegtokm(ax[0], 0.5 * (initializer.slat + initializer.nlat)) ax[0].set_ylabel('z (m)') q2 = ax[1].quiver( domain.lonh[ex._plot_slice[3, 0]:ex._plot_slice[3, 1]], initializer.z[::2], np.zeros(edpfvdm.values.squeeze()[::2].shape), edpfvdm.values.squeeze()[::2] / dx * np.sqrt(dx**2 + dz**2), units=units) # angles=angles) tx = ax[1].text(0.05, 0.1, lab[1], transform=ax[1].transAxes) tx.set_fontsize(15) tx.set_bbox(dict(facecolor='white', alpha=1, edgecolor='white')) ax[1].quiverkey( q2, 0.75, 1.05, 1e-3, r'$1e-3$', labelpos='E', coordinates='axes') xdegtokm(ax[1], 0.5 * (initializer.slat + initializer.nlat)) q3 = ax[2].quiver( domain.lonh[ex._plot_slice[3, 0]:ex._plot_slice[3, 1]], initializer.z[::2], np.zeros(edpfvdm.values.squeeze()[::2].shape) + uv_e_flux.values.squeeze()[::2] / dx * np.sqrt(dx**2 + dz**2), (edpfvdm.values.squeeze()[::2] + uv_e_flux.values.squeeze()[::2] * ex.values.squeeze()[::2]) / dz * np.sqrt(dx**2 + dz**2), units=units) # angles=angles) tx = ax[2].text(0.05, 0.1, lab[2], transform=ax[2].transAxes) tx.set_fontsize(15) tx.set_bbox(dict(facecolor='white', alpha=1, edgecolor='white')) ax[2].quiverkey( q3, 0.75, 1.05, 1e-2, r'$1e-2$', labelpos='E', coordinates='axes') xdegtokm(ax[2], 0.5 * (initializer.slat + initializer.nlat)) return fig
import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset as dset from netCDF4 import MFDataset as mfdset import readParams as rdp geofil = 'ocean_geometry.nc' fil = 'output__002?_01.nc' D, (ah,aq), (dxcu,dycu,dxcv,dycv,dxbu,dybu,dxt,dyt), f = rdp.getgeom(geofil) (xh,yh), (xq,yq), (zi,zl), time = rdp.getdims(fil) fh = mfdset(fil) e = fh.variables['e'][:,:,:,:] h = fh.variables['h'][:,:,:,:] fh.close() e1 = np.swapaxes(e,0,1).reshape((e.shape[1],-1)) z = np.linspace(-np.max(D),-1,num=50) rho = np.zeros((z.size,e1.shape[1])) #rho[:] = np.NaN for i in range(z.size): t1 = e1[0:-1,:] - z[i] t2 = e1[1:,:] - z[i] tt = t1*t2 indices = np.nonzero(tt<=0) rho[i,indices[1]]=zl[indices[0]] rho = rho.reshape((z.size,e.shape[0],e.shape[2],e.shape[3])).swapaxes(0,1)
def extract_twamomy_terms_pym6(initializer): domain = Domain.Domain(initializer) plot_loc = 'vl' with mfdset(initializer.fil) as fh, mfdset(initializer.fil2) as fh2: h = (gv('h_Cv', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) vr = (gv('vh', domain, plot_loc, fh2, fh, plot_loc=plot_loc, divisor='h_Cv').read_array(divide_by_dx=True, filled=0)) vrx = (gv('vh', domain, plot_loc, fh2, fh, plot_loc=plot_loc, divisor='h_Cv').xsm().xep().read_array( extend_kwargs={ 'method': 'vorticity' }, divide_by_dx=True, filled=0).ddx(3).move_to(plot_loc)) vry = (gv('vh', domain, plot_loc, fh2, fh, plot_loc=plot_loc, divisor='h_Cv').ysm().yep().read_array( extend_kwargs={ 'method': 'symmetric' }, divide_by_dx=True, filled=0).ddx(2).move_to(plot_loc)) humx = (gv('uh', domain, 'ul', fh2, fh, plot_loc=plot_loc).xsm().yep().read_array( extend_kwargs={ 'method': 'vorticity' }, filled=0).ddx(3, div_by_area=True).move_to(plot_loc)) hum = (gv('uh', domain, 'ul', fh2, fh, plot_loc=plot_loc).xsm().yep().read_array( divide_by_dy=True, filled=0, extend_kwargs={ 'method': 'vorticity' }).move_to('hl').move_to(plot_loc)) hvmy = (gv('vh', domain, plot_loc, fh2, fh, plot_loc=plot_loc).ysm().yep().read_array( filled=0, extend_kwargs={ 'method': 'symmetric' }).ddx(2, div_by_area=True).move_to(plot_loc)) huvxphvvym = ( (gv('twa_huvxpt', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) + (gv('twa_hvvymt', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0))) hvvym = (gv('hvv_Cv', domain, plot_loc, fh2, fh, plot_loc=plot_loc).ysm().yep().read_array( extend_kwargs={ 'method': 'symmetric' }, filled=0).ddx(2, div_by_area=True).move_to(plot_loc)) huvxm = -(huvxphvvym + hvvym) vrb = (gv('vh', domain, plot_loc, fh2, fh, plot_loc=plot_loc, divisor='h_Cv').lsm().lep().read_array( extend_kwargs={ 'method': 'mirror' }, divide_by_dx=True, filled=0).ddx(1).move_to(plot_loc)) hwb = (gv('wd', domain, 'hi', fh2, fh, plot_loc=plot_loc).yep().read_array( filled=0, extend_kwargs={ 'method': 'vorticity' }).o1diff(1).move_to(plot_loc)) hwm = (gv('wd', domain, 'hi', fh2, fh, plot_loc=plot_loc).yep().read_array( filled=0, extend_kwargs={ 'method': 'vorticity' }).move_to('hl').move_to(plot_loc)) * domain.db esq = (gv('esq', domain, 'hl', fh2, fh, plot_loc=plot_loc).yep().read_array( extend_kwargs={'method': 'mirror'})) e = (gv('e', domain, 'hi', fh2, fh, plot_loc=plot_loc).yep().read_array(extend_kwargs={ 'method': 'mirror' }).move_to('hl')) edlsqm = esq - e * e edlsqmy = edlsqm.ddx(2) hpfv = (gv('twa_hpfv', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) pfvm = (gv('PFv', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) edpfvdmb = -hpfv + h * pfvm - edlsqmy * domain.db * 0.5 hmfum = (gv('twa_hmfu', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) hvwbm = (gv('twa_hvwb', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) hdiffvm = (gv('twa_hdiffv', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) hdvdtviscm = (gv('twa_hdvdtvisc', domain, plot_loc, fh2, fh, plot_loc=plot_loc).read_array(filled=0)) advx = hum * vrx / h advy = vr * vry advb = hwm * vrb / h cor = hmfum / h pfvm = pfvm xdivep1 = -huvxm / h xdivep2 = advx xdivep3 = vr * humx / h xdivep = (xdivep1 + xdivep2 + xdivep3) ydivep1 = -hvvym / h ydivep2 = advy ydivep3 = vr * hvmy / h ydivep4 = -edlsqmy / 2 * domain.db / h ydivep = (ydivep1 + ydivep2 + ydivep3 + ydivep4) bdivep1 = hvwbm / h bdivep2 = advb bdivep3 = vr * hwb / h bdivep4 = -edpfvdmb / h bdivep = (bdivep1 + bdivep2 + bdivep3 + bdivep4) Y1twa = hdiffvm / h Y2twa = hdvdtviscm / h budgetlist = [ -advx, -advy, -advb, cor, pfvm, xdivep, ydivep1 + ydivep2 + ydivep3, ydivep4, bdivep1 + bdivep2 + bdivep3, bdivep4, Y1twa, Y2twa ] ti = [ '(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)', '(j)', '(k)', '(l)' ] lab = [ r'$-\hat{u}\hat{v}_{\tilde{x}}$', r'$-\hat{v}\hat{v}_{\tilde{y}}$', r'$-\hat{\varpi}\hat{v}_{\tilde{b}}$', r'$-f\hat{u}$', r'$-\overline{m_{\tilde{y}}}$', r"""$-\frac{1}{\overline{h}}(\overline{h}\widehat{u^{\prime \prime}v^{\prime \prime}})_{\tilde{x}}$""", r"""$-\frac{1}{\overline{h}}(\overline{h}\widehat{v^{\prime \prime}v^{\prime \prime}})_{\tilde{y}}$""", r"""$-\frac{1}{2\overline{\zeta_{\tilde{b}}}}(\overline{\zeta^{\prime 2}})_{\tilde{y}}$""", r"""$-\frac{1}{\overline{h}}(\overline{h}\widehat{v^{\prime \prime}\varpi ^{\prime \prime}})_{\tilde{b}}$""", r"""$-\frac{1}{\overline{\zeta_{\tilde{b}}}}(\overline{\zeta^\prime m_{\tilde{y}}^\prime})_{\tilde{b}}$""", r'$\widehat{Y^H}$', r'$\widehat{Y^V}$' ] for i, var in enumerate(budgetlist): var.name = lab[i] return budgetlist
def extract_twamomx_terms(geofil,fil,xstart,xend,ystart,yend,zs,ze,meanax, alreadysaved=False): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i,) fh = mfdset(fil) (xs,xe),(ys,ye),dimu = rdp1.getlatlonindx(fh,wlon=xstart,elon=xend, slat=ystart, nlat=yend,zs=zs,ze=ze,xhxq='xq') # _,(vys,vye),_ = rdp1.getlatlonindx(fh,wlon=xstart,elon=xend, # slat=ystart, nlat=yend,zs=zs,ze=ze,yhyq='yq') # (xs,xe),(ys,ye),_ = rdp1.getlatlonindx(fh,wlon=xstart,elon=xend, # slat=ystart, nlat=yend,zs=zs,ze=ze) D, (ah,aq) = rdp1.getgeombyindx(geofil,xs,xe,ys,ye)[0:2] nt_const = dimu[0].size t0 = time.time() print('Reading data using loop...') u = fh.variables['u'][0:1,zs:ze,ys:ye,xs:xe] nt = np.ones(u.shape)*nt_const frhatu = fh.variables['frhatu'][0:1,zs:ze,ys:ye,xs:xe] h_u = frhatu*D[np.newaxis,np.newaxis,:,:] h_u = np.ma.masked_array(h_u,mask=(h_u<=1e-3).astype(int)) nt[h_u<=1e-3] -= 1 cau = fh.variables['CAu'][0:1,zs:ze,ys:ye,xs:xe] gkeu = fh.variables['gKEu'][0:1,zs:ze,ys:ye,xs:xe] rvxv = fh.variables['rvxv'][0:1,zs:ze,ys:ye,xs:xe] pfu = fh.variables['PFu'][0:1,zs:ze,ys:ye,xs:xe] hagum = h_u*(cau - gkeu - rvxv + pfu) hagum = hagum.filled(0) hdudtviscm = h_u*fh.variables['du_dt_visc'][0:1,zs:ze,ys:ye,xs:xe] hdudtviscm = hdudtviscm.filled(0) hdiffum = h_u*fh.variables['diffu'][0:1,zs:ze,ys:ye,xs:xe] hdiffum = hdiffum.filled(0) dudtdia = fh.variables['dudt_dia'][0:1,zs:ze,ys:ye,xs:xe] wd = fh.variables['wd'][0:1,zs:ze,ys:ye,xs:xe] wd = np.diff(wd,axis=1) wd = np.concatenate((wd,wd[:,:,:,-1:]),axis=3) huwbm = (u*(wd[:,:,:,0:-1]+wd[:,:,:,1:])/2 - h_u*dudtdia) huwbm = huwbm.filled(0) uh = fh.variables['uh'][0:1,zs:ze,ys:ye,xs-1:xe] uh = np.ma.filled(uh.astype(float), 0) uhx = np.diff(uh,axis = 3)/ah uhx = np.concatenate((uhx,uhx[:,:,:,-1:]),axis=3) huuxpTm = (u*(uhx[:,:,:,0:-1]+uhx[:,:,:,1:])/2 - h_u*gkeu) huuxpTm = huuxpTm.filled(0) vh = fh.variables['vh'][0:1,zs:ze,ys-1:ye,xs:xe] vh = np.ma.filled(vh.astype(float), 0) vhy = np.diff(vh,axis = 2)/ah vhy = np.concatenate((vhy,vhy[:,:,:,-1:]),axis=3) huvymTm = (u*(vhy[:,:,:,0:-1]+vhy[:,:,:,1:])/2 - h_u*rvxv) huvymTm = huvymTm.filled(0) if 1 in keepax: em = fh.variables['e'][0:1,zs:ze,ys:ye,xs:xe]/nt_const for i in range(1,nt_const): u = fh.variables['u'][i:i+1,zs:ze,ys:ye,xs:xe] frhatu = fh.variables['frhatu'][i:i+1,zs:ze,ys:ye,xs:xe] h_u = frhatu*D[np.newaxis,np.newaxis,:,:] h_u = np.ma.masked_array(h_u,mask=(h_u<=1e-3).astype(int)) nt[h_u<=1e-3] -= 1 cau = fh.variables['CAu'][i:i+1,zs:ze,ys:ye,xs:xe] gkeu = fh.variables['gKEu'][i:i+1,zs:ze,ys:ye,xs:xe] rvxv = fh.variables['rvxv'][i:i+1,zs:ze,ys:ye,xs:xe] pfu = fh.variables['PFu'][i:i+1,zs:ze,ys:ye,xs:xe] hagum += (h_u*(cau - gkeu - rvxv + pfu)).filled(0) hdudtviscm += (h_u*fh.variables['du_dt_visc'][i:i+1,zs:ze, ys:ye,xs:xe]).filled(0) hdiffum += (h_u*fh.variables['diffu'][i:i+1,zs:ze, ys:ye,xs:xe]).filled(0) dudtdia = fh.variables['dudt_dia'][i:i+1,zs:ze,ys:ye,xs:xe] wd = fh.variables['wd'][i:i+1,zs:ze,ys:ye,xs:xe] wd = np.diff(wd,axis=1) wd = np.concatenate((wd,wd[:,:,:,-1:]),axis=3) huwbm += ((u*(wd[:,:,:,0:-1]+wd[:,:,:,1:])/2 - h_u*dudtdia)).filled(0) uh = fh.variables['uh'][i:i+1,zs:ze,ys:ye,xs-1:xe] uh = np.ma.filled(uh.astype(float), 0) uhx = np.diff(uh,axis = 3)/ah uhx = np.concatenate((uhx,uhx[:,:,:,-1:]),axis=3) huuxpTm += ((u*(uhx[:,:,:,0:-1]+uhx[:,:,:,1:])/2 - h_u*gkeu)).filled(0) vh = fh.variables['vh'][i:i+1,zs:ze,ys-1:ye,xs:xe] vh = np.ma.filled(vh.astype(float), 0) vhy = np.diff(vh,axis = 2)/ah vhy = np.concatenate((vhy,vhy[:,:,:,-1:]),axis=3) huvymTm += ((u*(vhy[:,:,:,0:-1]+vhy[:,:,:,1:])/2 - h_u*rvxv)).filled(0) if 1 in keepax: em += fh.variables['e'][i:i+1,zs:ze,ys:ye,xs:xe]/nt_const sys.stdout.write('\r'+str(int((i+1)/nt_const*100))+'% done...') sys.stdout.flush() fh.close() print('Time taken for data reading: {}s'.format(time.time()-t0)) terms = np.ma.concatenate(( hagum[:,:,:,:,np.newaxis], -huwbm[:,:,:,:,np.newaxis], -huuxpTm[:,:,:,:,np.newaxis], -huvymTm[:,:,:,:,np.newaxis], hdudtviscm[:,:,:,:,np.newaxis], hdiffum[:,:,:,:,np.newaxis]), axis=4)/nt[:,:,:,:,np.newaxis] termsm = np.ma.apply_over_axes(np.nanmean, terms, meanax) X = dimu[keepax[1]] Y = dimu[keepax[0]] if 1 in keepax: elm = 0.5*(em[:,0:-1,:,:]+em[:,1:,:,:]) em = np.ma.apply_over_axes(np.mean, em, meanax) elm = np.ma.apply_over_axes(np.mean, elm, meanax) Y = elm.squeeze() X = np.meshgrid(X,dimu[1])[0] P = termsm.squeeze() P = np.ma.filled(P.astype(float), np.nan) X = np.ma.filled(X.astype(float), np.nan) Y = np.ma.filled(Y.astype(float), np.nan) np.savez('twamomx_terms', X=X,Y=Y,P=P) else: npzfile = np.load('twamomx_terms.npz') X = npzfile['X'] Y = npzfile['Y'] P = npzfile['P'] return (X,Y,P)
def extract_twapv_terms(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs, ze, meanax, fil3=None, calledfromgeteddycoeffs=False, alreadysaved=False): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fhgeo = dset(geofil) fh = mfdset(fil) fh2 = mfdset(fil2) zi = rdp1.getdims(fh)[2][0] dbl = -np.diff(zi) * 9.8 / 1031 if not calledfromgeteddycoeffs: (xs, xe), (ys, ye), dimq = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xq', yhyq='yq') else: (xs, xe), (ys, ye), dimq = rdp1.getdimsbyindx(fh, xstart, xend, ystart, yend, zs=zs, ze=ze, ts=0, te=None, xhxq='xq', yhyq='yq') sl = np.s_[:, zs:ze, ys:ye, xs:xe] nt_const = dimq[0].size pvhash, hq = getpv(fhgeo, fh, fh2, xs, xe, ys, ye) slpy = np.s_[:, zs:ze, ys:ye + 1, xs:xe] dxcu = fhgeo.variables['dxCu'][slpy[2:]] dycv = fhgeo.variables['dyCv'][sl[2:]] dycv = np.concatenate((dycv, dycv[:, -1:]), axis=1) dxbu = fhgeo.variables['dxBu'][sl[2:]] dybu = fhgeo.variables['dyBu'][sl[2:]] aq = fhgeo.variables['Aq'][sl[2:]] f = fhgeo.variables['f'][sl[2:]] if fil3: fh3 = mfdset(fil3) sltn = np.s_[-1:, zs:ze, ys:ye, xs:xe] islayerdeep0 = fh3.variables['islayerdeep'][-1:, 0, 0, 0] islayerdeep = (fh3.variables['islayerdeep'][sltn].filled(np.nan)) swash = (islayerdeep0 - islayerdeep) / islayerdeep0 * 100 fh3.close() else: swash = None xmom = extract_twamomx_terms(geofil, vgeofil, fil, fil2, xs, xe, ys, ye + 1, zs, ze, (0, ), alreadysaved=False, xyasindices=True, calledfrompv=True)[2] ymom = extract_twamomy_terms(geofil, vgeofil, fil, fil2, xs, xe, ys, ye, zs, ze, (0, ), alreadysaved=False, xyasindices=True, calledfrompv=True)[2] xmom = xmom[np.newaxis, :, :, :, :] ymom = ymom[np.newaxis, :, :, :, :] ymom = np.concatenate((ymom, ymom[:, :, :, -1:]), axis=3) bxppvflx = np.sum(xmom[:, :, :, :, [0, 1, 3, 4]], axis=4) pvhash1, _ = getpv(fhgeo, fh, fh2, xs, xe, ys - 1, ye + 1) sl1 = np.s_[:, zs:ze, ys - 1:ye + 1, xs:xe] vtwa1, h_cv1 = getvtwa(fhgeo, fh, fh2, sl1) vtwa1 = 0.5 * (vtwa1[:, :, :, :-1] + vtwa1[:, :, :, 1:]) pvhashvtwa = pvhash1 * vtwa1 sl1 = np.s_[:, zs:ze, ys:ye + 1, xs:xe] h_cu1 = fh.variables['h_Cu'][sl1].filled(np.nan).mean(axis=0, keepdims=True) h_cu1 = np.ma.masked_array(h_cu1, mask=(h_cu1 < 1e-3)) pvflxx = h_cu1 * (pvhashvtwa[:, :, :-1, :] + pvhashvtwa[:, :, 1:, :]) / 2 byppvflx = np.sum(ymom[:, :, :, :, [0, 1, 3, 4]], axis=4) pvhash1, _ = getpv(fhgeo, fh, fh2, xs - 1, xe, ys, ye) sl1 = np.s_[:, zs:ze, ys:ye + 1, xs - 1:xe] utwa1, h_cu1 = getutwa(fhgeo, fh, fh2, sl1) utwa1 = 0.5 * (utwa1[:, :, :-1, :] + utwa1[:, :, 1:, :]) pvhashutwa = pvhash1 * utwa1 pvhashutwa[:, :, :, -1] = 0.0 sl1 = np.s_[:, zs:ze, ys:ye, xs:xe] h_cv1 = fh.variables['h_Cv'][sl1].mean(axis=0, keepdims=True) h_cv1 = np.ma.masked_array(h_cv1, mask=(h_cv1 < 1e-3)) pvflxy = h_cv1 * (pvhashutwa[:, :, :, :-1] + pvhashutwa[:, :, :, 1:]) / 2 pvflxy = np.concatenate((pvflxy, pvflxy[:, :, :, -1:]), axis=3) bx = bxppvflx - pvflxx by = byppvflx + pvflxy xmom1 = xmom[:, :, :, :, [2, 5, 6, 7, 8, 9]] xmom1 = np.concatenate( (+pvflxx[:, :, :, :, np.newaxis], xmom1, bx[:, :, :, :, np.newaxis]), axis=4) ymom1 = ymom[:, :, :, :, [2, 5, 6, 7, 8, 9]] ymom1 = np.concatenate( (-pvflxy[:, :, :, :, np.newaxis], ymom1, by[:, :, :, :, np.newaxis]), axis=4) #pv = (-np.diff(xmom*dxcu[:,:,np.newaxis],axis=2) + np.diff(ymom*dycv[:,:,np.newaxis],axis=3))/aq[:,:,np.newaxis] pv = -np.diff(xmom, axis=2) / dybu[:, :, np.newaxis] + np.diff( ymom, axis=3) / dxbu[:, :, np.newaxis] pv1x = -np.diff(xmom1 * dxcu[:, :, np.newaxis], axis=2) / aq[:, :, np.newaxis] pv1y = np.diff(ymom1 * dycv[:, :, np.newaxis], axis=3) / aq[:, :, np.newaxis] slyp = np.s_[:, :, ys:ye + 1, xs:xe] ah1 = fhgeo.variables['Ah'][slyp[2:]] slxmyp = np.s_[:, :, ys:ye + 1, xs - 1:xe] uh = fh2.variables['uh'][slxmyp].filled(0).mean(axis=0, keepdims=True) uhx = np.diff(uh, axis=3) / ah1 uhx = np.concatenate((uhx, uhx[:, :, :, -1:]), axis=3) uhx = 0.25 * (uhx[:, :, :-1, :-1] + uhx[:, :, :-1, 1:] + uhx[:, :, 1:, :-1] + uhx[:, :, 1:, 1:]) pv1y[:, :, :, :, 0] += pvhash * uhx slymp = np.s_[:, :, ys - 1:ye + 1, xs:xe] vh = fh2.variables['vh'][slymp].mean(axis=0, keepdims=True) vhy = np.diff(vh, axis=2) / ah1 vhy = np.concatenate((vhy, vhy[:, :, :, -1:]), axis=3) vhy = 0.25 * (vhy[:, :, :-1, :-1] + vhy[:, :, :-1, 1:] + vhy[:, :, 1:, :-1] + vhy[:, :, 1:, 1:]) pv1x[:, :, :, :, 0] += pvhash * vhy wd = fh2.variables['wd'][slyp].mean(axis=0, keepdims=True) wdb = np.diff(wd, axis=1) wdb = np.concatenate((wdb, wdb[:, :, :, -1:]), axis=3) wdb = 0.25 * (wdb[:, :, :-1, :-1] + wdb[:, :, :-1, 1:] + wdb[:, :, 1:, :-1] + wdb[:, :, 1:, 1:]) pv3 = pvhash * wdb pv3 = pv3[:, :, :, :, np.newaxis] #hq[hq<1] = np.nan pvnew = np.concatenate( (pv1y[:, :, :, :, :1], pv1x[:, :, :, :, :1], pv3, pv1x[:, :, :, :, 1:-1], pv1y[:, :, :, :, 1:-1], pv1x[:, :, :, :, -1:] + pv1y[:, :, :, :, -1:]), axis=4) / hq[:, :, :, :, np.newaxis] pv = np.ma.filled(pv.astype(np.float64), np.nan) pvnew = np.ma.filled(pvnew.astype(np.float64), np.nan) pvhash = np.ma.filled(pvhash.astype(np.float64), np.nan) pv = np.nanmean(pv, meanax, keepdims=True) pvnew = np.nanmean(pvnew, meanax, keepdims=True) pvhash = np.nanmean(pvhash, meanax, keepdims=True) X = dimq[keepax[1]] Y = dimq[keepax[0]] if 1 in keepax and not calledfromgeteddycoeffs: dt = fh.variables['average_DT'][:] dt = dt[:, np.newaxis, np.newaxis, np.newaxis] em = (fh2.variables['e'][0:, zs:ze, ys:ye, xs:xe] * dt).sum( axis=0, keepdims=True) / np.sum(dt) em = np.nanmean(em, meanax, keepdims=True) z = np.linspace(-3000, 0, 100) Y = z P = getvaratzc5(pv.astype(np.float32), z.astype(np.float32), em.astype(np.float32)).squeeze() Pnew = getvaratzc5(pvnew.astype(np.float32), z.astype(np.float32), em.astype(np.float32)).squeeze() pvhash = getvaratzc(pvhash.astype(np.float32), z.astype(np.float32), em.astype(np.float32)).squeeze() if fil3: swash = np.nanmean(swash, meanax, keepdims=True) swash = getvaratzc(swash.astype(np.float32), z.astype(np.float32), em.astype(np.float32)).squeeze() else: P = pv Pnew = pvnew fhgeo.close() fh.close() fh2.close() return (X, Y, P, pvhash, Pnew, swash)
def extract_twamomx_terms(geofil, vgeofil, fil, xstart, xend, ystart, yend, zs, ze, meanax, alreadysaved=False, xyasindices=False, calledfrompv=False): if not alreadysaved: keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fhvgeo = dset(vgeofil) db = -fhvgeo.variables['g'][:] dbi = np.append(db, 0) fhvgeo.close() fhgeo = dset(geofil) fh = mfdset(fil) zi = rdp1.getdims(fh)[2][0] dbl = -np.diff(zi) * 9.8 / 1031 if xyasindices: (xs, xe), (ys, ye) = (xstart, xend), (ystart, yend) _, _, dimu = rdp1.getdimsbyindx(fh, xs, xe, ys, ye, zs=zs, ze=ze, ts=0, te=None, xhxq='xq', yhyq='yh', zlzi='zl') else: (xs, xe), (ys, ye), dimu = rdp1.getlatlonindx(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze, xhxq='xq') D, (ah, aq) = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[0:2] Dforgetutwaforxdiff = rdp1.getgeombyindx(fhgeo, xs - 1, xe, ys, ye)[0] Dforgetutwaforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye + 1)[0] Dforgethvforydiff = rdp1.getgeombyindx(fhgeo, xs, xe, ys - 1, ye)[0] dxt, dyt = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[2][6:8] dxcu = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye)[2][0] dybu = rdp1.getgeombyindx(fhgeo, xs, xe, ys, ye + 1)[2][5] nt_const = dimu[0].size t0 = time.time() print('Reading data using loop...') h = fh.variables['h'][0:1, zs:ze, ys:ye, xs:xe] u = fh.variables['u'][0:1, zs:ze, ys:ye, xs:xe] nt = np.ones(u.shape) * nt_const frhatu = fh.variables['frhatu'][0:1, zs:ze, ys:ye, xs:xe] h_u = frhatu * D[np.newaxis, np.newaxis, :, :] h_u = np.ma.masked_array(h_u, mask=(h <= 1e-3).astype(int)) nt[h <= 1e-3] -= 1 hum = (h_u * u).filled(0) huum = (h_u * u * u).filled(0) h_um = h_u.filled(0) humforxdiff, h_umforxdiff, huumforxdiff = getutwaforxdiff( fh, fhgeo, Dforgetutwaforxdiff, 0, xs - 1, xe, ys, ye, zs, ze) humforydiff, h_umforydiff = getutwaforydiff(fh, fhgeo, Dforgetutwaforydiff, 0, xs, xe, ys - 1, ye + 1, zs, ze) cau = fh.variables['CAu'][0:1, zs:ze, ys:ye, xs:xe] gkeu = fh.variables['gKEu'][0:1, zs:ze, ys:ye, xs:xe] rvxv = fh.variables['rvxv'][0:1, zs:ze, ys:ye, xs:xe] hfvm = h_u * (cau - gkeu - rvxv).filled(0) pfu = fh.variables['PFu'][0:1, zs:ze, ys:ye, xs:xe] pfu = np.ma.masked_array(pfu, mask=(h <= 1e-3).astype(int)) pfum = pfu.filled(0) hdudtviscm = ( h_u * fh.variables['du_dt_visc'][0:1, zs:ze, ys:ye, xs:xe]).filled(0) hdiffum = (h_u * fh.variables['diffu'][0:1, zs:ze, ys:ye, xs:xe]).filled(0) dudtdia = fh.variables['dudt_dia'][0:1, zs:ze, ys:ye, xs:xe] wd = fh.variables['wd'][0:1, zs:ze, ys:ye, xs:xe] wd = np.diff(wd, axis=1) wd = np.concatenate((wd, wd[:, :, :, -1:]), axis=3) wdm = 0.5 * (wd[:, :, :, :-1] + wd[:, :, :, 1:]) wdm = np.ma.masked_array(wdm, mask=(h <= 1e-3).astype(int)) wdm = wdm.filled(0) huwbm = (u * (wd[:, :, :, 0:-1] + wd[:, :, :, 1:]) / 2 - h_u * dudtdia).filled(0) uh = fh.variables['uh'][0:1, zs:ze, ys:ye, xs - 1:xe] uh = np.ma.filled(uh.astype(float), 0) uhx = np.diff(uh, axis=3) / ah uhx = np.concatenate((uhx, uhx[:, :, :, -1:]), axis=3) huuxpTm = (u * (uhx[:, :, :, 0:-1] + uhx[:, :, :, 1:]) / 2 - h_u * gkeu).filled(0) vh = fh.variables['vh'][0:1, zs:ze, ys - 1:ye, xs:xe] vh = np.ma.filled(vh.astype(float), 0) vhy = np.diff(vh, axis=2) / ah vhy = np.concatenate((vhy, vhy[:, :, :, -1:]), axis=3) huvymTm = (u * (vhy[:, :, :, 0:-1] + vhy[:, :, :, 1:]) / 2 - h_u * rvxv).filled(0) v = fh.variables['v'][0:1, zs:ze, ys - 1:ye, xs:xe] v = np.concatenate((v, -v[:, :, :, [-1]]), axis=3) v = 0.25 * (v[:, :, 0:-1, 0:-1] + v[:, :, 1:, 0:-1] + v[:, :, 0:-1, 1:] + v[:, :, 1:, 1:]) hvm = (h_u * v).filled(0) hvmforydiff = gethvforydiff(fh, fhgeo, Dforgethvforydiff, 0, xs, xe, ys - 1, ye, zs, ze) wd = fh.variables['wd'][0:1, zs:ze, ys:ye, xs:xe] wd = np.concatenate((wd, -wd[:, :, :, -1:]), axis=3) hw = wd * dbi[:, np.newaxis, np.newaxis] hw = 0.5 * (hw[:, 0:-1, :, :] + hw[:, 1:, :, :]) hwm_u = 0.5 * (hw[:, :, :, 0:-1] + hw[:, :, :, 1:]) hwm_u = np.ma.masked_array(hwm_u, mask=(h <= 1e-3).astype(int)) hwm_u = hwm_u.filled(0) e = fh.variables['e'][0:1, zs:ze, ys:ye, xs:xe] em = e / nt_const el = 0.5 * (e[:, :-1, :, :] + e[:, 1:, :, :]) el = np.ma.masked_array(el, mask=(h <= 1e-3).astype(int)) elm = el.filled(0) esq = el**2 esq = np.ma.masked_array(esq, mask=(h <= 1e-3).astype(int)) esqm = esq.filled(0) el = np.concatenate((el, el[:, :, :, -1:]), axis=3) el = 0.5 * (el[:, :, :, :-1] + el[:, :, :, 1:]) elmatu = el.filled(0) epfum = (pfu * el).filled(0) for i in range(1, nt_const): h = fh.variables['h'][i:i + 1, zs:ze, ys:ye, xs:xe] u = fh.variables['u'][i:i + 1, zs:ze, ys:ye, xs:xe] frhatu = fh.variables['frhatu'][i:i + 1, zs:ze, ys:ye, xs:xe] h_u = frhatu * D[np.newaxis, np.newaxis, :, :] h_u = np.ma.masked_array(h_u, mask=(h <= 1e-3).astype(int)) nt[h <= 1e-3] -= 1 hum += (h_u * u).filled(0) h_um += h_u.filled(0) huforxdiff, h_uforxdiff, huuforxdiff = getutwaforxdiff( fh, fhgeo, Dforgetutwaforxdiff, i, xs - 1, xe, ys, ye, zs, ze) huforydiff, h_uforydiff = getutwaforydiff(fh, fhgeo, Dforgetutwaforydiff, i, xs, xe, ys - 1, ye + 1, zs, ze) humforxdiff += huforxdiff h_umforxdiff += h_uforxdiff huumforxdiff += huuforxdiff humforydiff += huforydiff h_umforydiff += h_uforydiff cau = fh.variables['CAu'][i:i + 1, zs:ze, ys:ye, xs:xe] gkeu = fh.variables['gKEu'][i:i + 1, zs:ze, ys:ye, xs:xe] rvxv = fh.variables['rvxv'][i:i + 1, zs:ze, ys:ye, xs:xe] hfv = h_u * (cau - gkeu - rvxv) hfvm += hfv.filled(0) pfu = fh.variables['PFu'][i:i + 1, zs:ze, ys:ye, xs:xe] pfu = np.ma.masked_array(pfu, mask=(h <= 1e-3).astype(int)) pfum += pfu.filled(0) hdudtvisc = h_u * fh.variables['du_dt_visc'][i:i + 1, zs:ze, ys:ye, xs:xe] hdudtviscm += hdudtvisc.filled(0) hdiffu = h_u * fh.variables['diffu'][i:i + 1, zs:ze, ys:ye, xs:xe] hdiffum += hdiffu.filled(0) dudtdia = fh.variables['dudt_dia'][i:i + 1, zs:ze, ys:ye, xs:xe] wd = fh.variables['wd'][i:i + 1, zs:ze, ys:ye, xs:xe] wd = np.diff(wd, axis=1) wd = np.concatenate((wd, wd[:, :, :, -1:]), axis=3) huwb = (u * (wd[:, :, :, 0:-1] + wd[:, :, :, 1:]) / 2 - h_u * dudtdia) huwb = np.ma.masked_array(huwb, mask=(h_u <= 1e-3).astype(int)) huwbm += huwb.filled(0) wd = 0.5 * (wd[:, :, :, :-1] + wd[:, :, :, 1:]) wd = np.ma.masked_array(wd, mask=(h <= 1e-3).astype(int)) wd = wd.filled(0) wdm += wd uh = fh.variables['uh'][i:i + 1, zs:ze, ys:ye, xs - 1:xe] uh = np.ma.filled(uh.astype(float), 0) uhx = np.diff(uh, axis=3) / ah uhx = np.concatenate((uhx, uhx[:, :, :, -1:]), axis=3) huuxpT = (u * (uhx[:, :, :, 0:-1] + uhx[:, :, :, 1:]) / 2 - h_u * gkeu) huuxpT = np.ma.masked_array(huuxpT, mask=(h_u <= 1e-3).astype(int)) huuxpTm += huuxpT.filled(0) vh = fh.variables['vh'][i:i + 1, zs:ze, ys - 1:ye, xs:xe] vh = np.ma.filled(vh.astype(float), 0) vhy = np.diff(vh, axis=2) / ah vhy = np.concatenate((vhy, vhy[:, :, :, -1:]), axis=3) huvymT = (u * (vhy[:, :, :, 0:-1] + vhy[:, :, :, 1:]) / 2 - h_u * rvxv) huvymT = np.ma.masked_array(huvymT, mask=(h_u <= 1e-3).astype(int)) huvymTm += huvymT.filled(0) v = fh.variables['v'][i:i + 1, zs:ze, ys - 1:ye, xs:xe] v = np.concatenate((v, -v[:, :, :, [-1]]), axis=3) v = 0.25 * (v[:, :, 0:-1, 0:-1] + v[:, :, 1:, 0:-1] + v[:, :, 0:-1, 1:] + v[:, :, 1:, 1:]) hv = h_u * v hvm += hv.filled(0) hvmforydiff += gethvforydiff(fh, fhgeo, Dforgethvforydiff, i, xs, xe, ys - 1, ye, zs, ze) wd = fh.variables['wd'][i:i + 1, zs:ze, ys:ye, xs:xe] wd = np.concatenate((wd, -wd[:, :, :, -1:]), axis=3) hw = wd * dbi[:, np.newaxis, np.newaxis] hw = 0.5 * (hw[:, 0:-1, :, :] + hw[:, 1:, :, :]) hw_u = 0.5 * (hw[:, :, :, 0:-1] + hw[:, :, :, 1:]) hw_u = np.ma.masked_array(hw_u, mask=(h <= 1e-3).astype(int)) hw_u = hw_u.filled(0) hwm_u += hw_u e = fh.variables['e'][i:i + 1, zs:ze, ys:ye, xs:xe] em += e / nt_const el = 0.5 * (e[:, :-1, :, :] + e[:, 1:, :, :]) el = np.ma.masked_array(el, mask=(h <= 1e-3).astype(int)) elm += el.filled(0) esq = el**2 esqm += esq.filled(0) el = np.concatenate((el, el[:, :, :, -1:]), axis=3) el = 0.5 * (el[:, :, :, :-1] + el[:, :, :, 1:]) elmatu += el.filled(0) epfum += (pfu * el).filled(0) sys.stdout.write('\r' + str(int((i + 1) / nt_const * 100)) + '% done...') sys.stdout.flush() fhgeo.close() fh.close() print('Time taken for data reading: {}s'.format(time.time() - t0)) utwa = hum / h_um utwaforxdiff = humforxdiff / h_umforxdiff utwaforydiff = humforydiff / h_umforydiff utwaforxdiff[np.isnan(utwaforxdiff)] = 0 utwax = np.diff(utwaforxdiff, axis=3) / dxt utwax = np.concatenate((utwax, -utwax[:, :, :, [-1]]), axis=3) utwax = 0.5 * (utwax[:, :, :, 0:-1] + utwax[:, :, :, 1:]) utway = np.diff(utwaforydiff, axis=2) / dybu utway = 0.5 * (utway[:, :, 0:-1, :] + utway[:, :, 1:, :]) humx = np.diff(humforxdiff, axis=3) / dxt humx = np.concatenate((humx, -humx[:, :, :, [-1]]), axis=3) humx = 0.5 * (humx[:, :, :, 0:-1] + humx[:, :, :, 1:]) hvmy = np.diff(hvmforydiff, axis=2) / dyt hvmy = np.concatenate((hvmy, -hvmy[:, :, :, [-1]]), axis=3) hvmy = 0.5 * (hvmy[:, :, :, 0:-1] + hvmy[:, :, :, 1:]) huuxphuvym = huuxpTm + huvymTm huuxm = np.diff(huumforxdiff, axis=3) / dxt huuxm = np.concatenate((huuxm, -huuxm[:, :, :, [-1]]), axis=3) huuxm = 0.5 * (huuxm[:, :, :, 0:-1] + huuxm[:, :, :, 1:]) huvym = huuxphuvym - huuxm utwaforvdiff = np.concatenate((utwa[:, [0], :, :], utwa), axis=1) utwab = np.diff(utwaforvdiff, axis=1) / db[:, np.newaxis, np.newaxis] utwab = np.concatenate( (utwab, np.zeros([utwab.shape[0], 1, utwab.shape[2], utwab.shape[3]])), axis=1) utwab = 0.5 * (utwab[:, 0:-1, :, :] + utwab[:, 1:, :, :]) hwb_u = wdm edlsqm = esqm / nt - (elm / nt)**2 edlsqm = np.concatenate((edlsqm, edlsqm[:, :, :, [-1]]), axis=3) edlsqmx = np.diff(edlsqm, axis=3) / dxcu * nt edpfudm = (epfum / nt - elmatu / nt * pfum / nt) * nt edpfudmb = np.diff(edpfudm, axis=1) # edpfudmb = np.diff(edpfudm,axis=1)/db[1:,np.newaxis,np.newaxis] edpfudmb = np.concatenate( (edpfudmb[:, :1, :, :], edpfudmb, edpfudmb[:, -1:, :, :]), axis=1) edpfudmb = 0.5 * (edpfudmb[:, :-1, :, :] + edpfudmb[:, 1:, :, :]) advx = utwa * utwax advy = hvm * utway / h_um advb = hwm_u * utwab / h_um cor = hfvm / h_um pfum = pfum / nt xdivep1 = huuxm / h_um xdivep2 = -advx xdivep3 = -utwa * humx / h_um xdivep4 = 0.5 * edlsqmx * dbl[:, np.newaxis, np.newaxis] / h_um xdivep = (xdivep1 + xdivep2 + xdivep3 + xdivep4) ydivep1 = huvym / h_um ydivep2 = -advy ydivep3 = -utwa * hvmy / h_um ydivep = (ydivep1 + ydivep2 + ydivep3) bdivep1 = huwbm / h_um bdivep2 = -advb bdivep3 = -utwa * hwb_u / h_um bdivep4 = edpfudmb / h_um bdivep = (bdivep1 + bdivep2 + bdivep3 + bdivep4) X1twa = hdiffum / h_um X2twa = hdudtviscm / h_um terms = np.ma.concatenate( (-advx[:, :, :, :, np.newaxis], -advy[:, :, :, :, np.newaxis], -advb[:, :, :, :, np.newaxis], cor[:, :, :, :, np.newaxis], pfum[:, :, :, :, np.newaxis], -xdivep[:, :, :, :, np.newaxis], -ydivep[:, :, :, :, np.newaxis], -bdivep[:, :, :, :, np.newaxis], X1twa[:, :, :, :, np.newaxis], X2twa[:, :, :, :, np.newaxis]), axis=4) termsep = np.ma.concatenate( (xdivep1[:, :, :, :, np.newaxis], xdivep3[:, :, :, :, np.newaxis], xdivep4[:, :, :, :, np.newaxis], ydivep1[:, :, :, :, np.newaxis], ydivep3[:, :, :, :, np.newaxis], bdivep1[:, :, :, :, np.newaxis], bdivep3[:, :, :, :, np.newaxis], bdivep4[:, :, :, :, np.newaxis]), axis=4) terms[np.isinf(terms)] = np.nan termsep[np.isinf(termsep)] = np.nan termsm = np.ma.apply_over_axes(np.nanmean, terms, meanax) termsepm = np.ma.apply_over_axes(np.nanmean, termsep, meanax) elm = 0.5 * (em[:, :-1, :, :] + em[:, 1:, :, :]) X = dimu[keepax[1]] Y = dimu[keepax[0]] if 1 in keepax: em = np.ma.apply_over_axes(np.mean, em, meanax) elm = np.ma.apply_over_axes(np.mean, elm, meanax) Y = elm.squeeze() X = np.meshgrid(X, dimu[1])[0] P = termsm.squeeze() P = np.ma.filled(P.astype(float), np.nan) Pep = termsepm.squeeze() Pep = np.ma.filled(Pep.astype(float), np.nan) X = np.ma.filled(X.astype(float), np.nan) Y = np.ma.filled(Y.astype(float), np.nan) if not calledfrompv: np.savez('twamomx_complete_terms', X=X, Y=Y, P=P, Pep=Pep) else: npzfile = np.load('twamomx_complete_terms.npz') X = npzfile['X'] Y = npzfile['Y'] P = npzfile['P'] Pep = npzfile['Pep'] return (X, Y, P, Pep)
def getuv(geofil, vgeofil, fil, fil2, xstart, xend, ystart, yend, zs, ze, meanax, xyasindices=False): keepax = () for i in range(4): if i not in meanax: keepax += (i, ) fhvgeo = dset(vgeofil) db = -fhvgeo.variables['g'][:] dbi = np.append(db, 0) fhvgeo.close() fhgeo = dset(geofil) fh = mfdset(fil) fh2 = mfdset(fil2) zi = rdp1.getdims(fh)[2][0] dbl = np.diff(zi) * 9.8 / 1031 slh, dimh = rdp1.getslice(fh, wlon=xstart, elon=xend, slat=ystart, nlat=yend, zs=zs, ze=ze) ys, ye = slh[2].start, slh[2].stop xs, xe = slh[3].start, slh[3].stop slhmx = np.s_[:, zs:ze, ys:ye, xs - 1:xe] slhmy = np.s_[:, zs:ze, ys - 1:ye, xs:xe] slhmpy = np.s_[:, zs:ze, ys - 1:ye + 1, xs:xe] slu, dimu = rdp1.getslice(fh, xstart, xend, ystart, yend, zs=zs, ze=ze, ts=0, te=None, xhxq='xq', yhyq='yh', zlzi='zl') slv, dimv = rdp1.getslice(fh, xstart, xend, ystart, yend, zs=zs, ze=ze, ts=0, te=None, xhxq='xh', yhyq='yq', zlzi='zl') ys, ye = slv[2].start, slv[2].stop xs, xe = slv[3].start, slv[3].stop slvpy = np.s_[:, zs:ze, ys:ye + 1, xs:xe] uh = getvaravg(fh2, 'uh', slu) u = getvaravg(fh2, 'u', slu).filled(np.nan) h_cu = getvaravg(fh, 'h_Cu', slu) h_cu = np.ma.masked_array(h_cu, mask=(h_cu < 1e-3)) dycu = fhgeo.variables['dyCu'][slu[2:]] utwa = uh / h_cu / dycu vh = getvaravg(fh2, 'vh', slv) v = getvaravg(fh2, 'v', slv) h_cv = getvaravg(fh, 'h_Cv', slv) h_cv = np.ma.masked_array(h_cv, mask=(h_cv < 1e-3)) dxcv = fhgeo.variables['dxCv'][slv[2:]] vtwa = vh / dxcv / h_cv emforxdiff = getvaravg(fh2, 'e', slhmx) elmforxdiff = 0.5 * (emforxdiff[:, 0:-1, :, :] + emforxdiff[:, 1:, :, :]) elmforxdiff = np.concatenate((elmforxdiff, elmforxdiff[:, :, :, -1:]), axis=3) dxcuforxdiff = fhgeo.variables['dxCu'][slhmx[2:]] ex = np.diff(elmforxdiff, axis=3) / dxcuforxdiff uh = getvaravg(fh2, 'uh', slhmx) h_cu = getvaravg(fh, 'h_Cu', slhmx) h_cu = np.ma.masked_array(h_cu, mask=(h_cu < 1e-3)) dycu = fhgeo.variables['dyCu'][slhmx[2:]] uzx = (uh / h_cu / dycu).filled(0) * ex uzx = 0.5 * (uzx[:, :, :, 1:] + uzx[:, :, :, :-1]) emforydiff = getvaravg(fh2, 'e', slhmpy) elmforydiff = 0.5 * (emforydiff[:, 0:-1, :, :] + emforydiff[:, 1:, :, :]) dycv = fhgeo.variables['dyCv'][slhmy[2:]] ey = np.diff(elmforydiff, axis=2) / dycv vh = getvaravg(fh2, 'vh', slhmy) h_cv = getvaravg(fh, 'h_Cv', slhmy) h_cv = np.ma.masked_array(h_cv, mask=(h_cv < 1e-3)) dxcv = fhgeo.variables['dxCv'][slhmy[2:]] vtwa = vh / dxcv / h_cv vzy = vtwa * ey vtwa = 0.5 * (vtwa[:, :, 1:, :] + vtwa[:, :, :-1, :]) vzy = 0.5 * (vzy[:, :, 1:, :] + vzy[:, :, :-1, :]) wd = getvaravg(fh2, 'wd', slh) hw = wd * dbi[:, np.newaxis, np.newaxis] hw = 0.5 * (hw[:, 1:, :, :] + hw[:, :-1, :, :]) wzb = hw / dbl[:, np.newaxis, np.newaxis] whash = uzx + vzy + wzb terms = [utwa, vtwa, whash, u, v] slices = [slu, slvpy, slh, slu, slvpy] X = [ dimu[keepax[1]], dimv[keepax[1]], dimh[keepax[1]], dimu[keepax[1]], dimv[keepax[1]] ] Y = [ dimu[keepax[0]], dimv[keepax[0]], dimh[keepax[0]], dimu[keepax[1]], dimv[keepax[1]] ] termsm = [] for item in terms: try: item = item.filled(np.nan) except AttributeError: item = item termsm.append(np.ma.apply_over_axes(np.nanmean, item, meanax)) if 1 in keepax: Y = [] for i in range(len(terms)): z = np.linspace(-3000, 0, 100) em = fh2.variables['e'][slices[i]] if i == 0 or i == 3: em = np.concatenate((em, em[:, :, :, -1:]), axis=3) em = 0.5 * (em[:, :, :, :-1] + em[:, :, :, 1:]) elif i == 1 or i == 4: em = 0.5 * (em[:, :, :-1, :] + em[:, :, 1:, :]) em = np.ma.apply_over_axes(np.mean, em, meanax) termsm[i] = getvaratzc(termsm[i].astype(np.float32), z.astype(np.float32), em.astype(np.float32)) Y.append(z) fh2.close() fh.close() fhgeo.close() P = [] for i, item in enumerate(termsm): P.append(item) X[i] = np.ma.filled(X[i].astype(float), np.nan) Y[i] = np.ma.filled(Y[i].astype(float), np.nan) return X, Y, P