def create_mv2_gridder_xyzt(nx=8, ny=7, nz=6, nt=5, xmin=-6., xmax=-3, ymin=46, ymax=48, zmin=-200, zmax=0, tmin='2016', tmax='2016-02', tunits='days since 2016-01-01', rotate=0): """Create a MV2 array on a grid Return ------ MV2.array """ # Axes shape = () axes = [] if nt != 0: time = create_time(lindates(tmin, tmax, nt), tunits) axes.append(time) shape += nt, if nz != 0: dep = create_dep(N.linspace(zmin, zmax, nz)) axes.append(dep) shape += nz, if ny != 0: lat = create_lat(N.linspace(ymin, ymax, ny)) axes.append(lat) shape += ny, if nx != 0: lon = create_lon(N.linspace(xmin, xmax, nx)) axes.append(lon) shape += nx, # Array data = MV2.array(N.arange(N.multiply.reduce(shape)).reshape(shape), copy=False, axes=axes, id='temp', dtype='d') # Rotate grid if rotate: grid = data.getGrid() if grid is not None: grid = rotate_grid(grid, rotate) set_grid(data, grid) return data
def missing_interp(lon, lat, arr): grid0 = create_grid(lon[0, :], lat[:, 0]) varri = MV2.asarray(arr) varri = set_grid(varri, grid0) tempf = fill2d(varri, method='carg') lon = np.ma.masked_where(tempf == tempf.fill_value, lon) lat = np.ma.masked_where(tempf == tempf.fill_value, lat) arri = griddata(lon.compressed(), lat.compressed(), tempf.compressed(), (lon[0, :], lat[:, 0]), method='nat', ext=True, sub=10) return arri
"""Test :func:`~vacumm.misc.grid.regridding.extend1d` and :func:`~vacumm.misc.grid.regridding.extend2d`""" from vcmq import N, create_grid2d, P, rc, plot2d, MV2, set_grid, savefigs, code_file_name from vacumm.misc.grid.regridding import extend1d, extend2d # Input data nxi = 4 nyi = 3 xxi, yyi = N.meshgrid(N.arange(nxi) + .25, N.arange(nyi) - .25) for j in xrange(nyi): xxi[j, :] -= j * 0.5 for i in xrange(nxi): yyi[:, i] += i * 0.5 gridi = create_grid2d(xxi, yyi) # input cdms grid vari = MV2.array(N.arange(nyi * nxi).reshape(nyi, nxi)) + 10. set_grid(vari, gridi) # set grid and axes # Extend and plot rc('font', size=9) P.figure(figsize=(6, 6)) kw = dict(xmin=xxi.min() - 3, xmax=xxi.max() + 3, ymin=yyi.min() - 3, ymax=yyi.max() + 3, show=False, xhide='auto', yhide='auto') # - original plot2d(vari, title='Original', subplot=(2, 2, 1), **kw) # - extend1d for i, (axis, ext, mode) in enumerate([(-1, (2, 2), 'same'),
create_grid, rc, rcdefaults, plot2d from vacumm.misc.grid.regridding import regrid2d # Input grid and data nxi = 20 nyi = 15 # - rect xi = N.arange(nxi*1.) yi = N.arange(nyi*1.) gridri = create_grid(xi, yi) xxri, yyri = N.meshgrid(xi, yi) zzri = N.ma.array(yyri) zzri[int(nyi*0.3):int(nyi*0.6), int(nxi*0.3):int(nxi*0.6)] = N.ma.masked varri = MV2.asarray(zzri) set_grid(varri, gridri) # - curv gridci = rotate_grid(gridri, 30) xxci = gridci.getLongitude().getValue() yyci = gridci.getLatitude().getValue() zzci = N.ma.array(yyci) zzci[int(nyi*0.3):int(nyi*0.6), int(nxi*0.3):int(nxi*0.6)] = N.ma.masked varci = MV2.asarray(zzci) set_grid(varci, gridci) # Output positions nxo = 25 nyo = 18 # - rect dxi = xi[-1]-xi[0] dyi = yi[-1]-yi[0]
# - grille grid = create_grid(lon, lat) # -> ESSAYEZ AVEC LON EXPLICITE gridc = create_grid(lon2d, lat2d) # Verifier print islon(lon) print isgrid(grid) # -> TEST PARAM CURV=... print isrect(gridc) # -> CREEZ GRILLE NON RECT ET RETESTER print isdepthup(dep) # -> TESTEZ EN CHANGEANT ATTRIBUT POSITIVE ET VALEURS print isregular(lon) # Affecter var = MV2.ones(grid.shape) set_grid(var, grid) varc = MV2.ones(gridc.shape) set_grid(varc, gridc) # -> VERIFIEZ ID DES AXES # Récupérer mygrid = get_grid(gridc) # -> TESTEZ AVEC (LON,LAT) ET PARAMS STRICT ET INTERCEPT mylon2d = get_axis(gridc, 1) # -> COMPAREZ AVEC .GETAXIS() # Sélectionner print coord2slice(lon, lon=(2, 4.5))# -> COMPAREZ AVEC .GETINTERVALEXT(...) print coord2slice(grid, lon=(4, 8), lat=(44, 46)) # -> TESTEZ SUR GRIDC # -> TESTEZ VARSEL
# Input grid and data nxi = 20 nyi = 15 nt = 5 # - rect xi = N.arange(nxi*1.) yi = N.arange(nyi*1.) ti = create_time((nt, ), 'years since 2000') gridri = create_grid(xi, yi) xxri, yyri = N.meshgrid(xi, yi) zzri = N.ma.resize(yyri, (nt, nyi, nxi)) zzri[:, int(nyi*0.3):int(nyi*0.6), int(nxi*0.3):int(nxi*0.6)] = N.ma.masked zzri[1] = N.ma.masked varri = MV2.asarray(zzri) varri.setAxis(0, ti) set_grid(varri, gridri) # - curv gridci = rotate_grid(gridri, 30) xxci = gridci.getLongitude().getValue() yyci = gridci.getLatitude().getValue() zzci = N.ma.resize(yyci, (nt, nyi, nxi)) zzci[:, int(nyi*0.3):int(nyi*0.6), int(nxi*0.3):int(nxi*0.6)] = N.ma.masked zzci[1] = N.ma.masked varci = MV2.asarray(zzci) varci.setAxis(0, ti) set_grid(varci, gridci) # Output positions nxo = 25 nyo = 18 # - rect
ii = lon2d.getAxis(1) # - grille grid = create_grid(lon, lat) # -> ESSAYEZ AVEC LON EXPLICITE gridc = create_grid(lon2d, lat2d) # Verifier print islon(lon) print isgrid(grid) # -> TEST PARAM CURV=... print isrect(gridc) # -> CREEZ GRILLE NON RECT ET RETESTER print isdepthup(dep) # -> TESTEZ EN CHANGEANT ATTRIBUT POSITIVE ET VALEURS print isregular(lon) # Affecter var = MV2.ones(grid.shape) set_grid(var, grid) varc = MV2.ones(gridc.shape) set_grid(varc, gridc) # -> VERIFIEZ ID DES AXES # Récupérer mygrid = get_grid( gridc) # -> TESTEZ AVEC (LON,LAT) ET PARAMS STRICT ET INTERCEPT mylon2d = get_axis(gridc, 1) # -> COMPAREZ AVEC .GETAXIS() # Sélectionner print coord2slice(lon, lon=(2, 4.5)) # -> COMPAREZ AVEC .GETINTERVALEXT(...) print coord2slice(grid, lon=(4, 8), lat=(44, 46)) # -> TESTEZ SUR GRIDC # -> TESTEZ VARSEL # Transformer gridcr = curv2rect(gridc) # -> TESTEZ AVEC VOTRE GRILLE NON RECT
N.exp(-((xxr-7.)**2+(yyr-7.)**2)/4.**2))*100. zzr -= zzr.mean() zzr = N.ma.asarray(zzr) zzr[5:, 10:] = N.ma.masked # - input at random locations ij = N.unique((N.random.rand(150) * zzr.size).astype('i')) xi, yi, zi = xxr.flat[ij], yyr.flat[ij], zzr.flat[ij] zi = N.ma.resize(zi, (3, zi.size)) # - format zi = MV2.array(zi, copy=False, id='sst') taxis = zi.getAxis(0) taxis.units = 'hours since 2000' taxis.axis = 'T' ggo = create_grid(xr, yr) zzr = MV2.array(zzr) set_grid(zzr, ggo) # Call and plot kw = dict(vmin=zzr.min(), vmax=zzr.max(), lon=(xr[0], xr[-1]), cmap_lum=0.7, linewidth=.5, lat=(yr[0], yr[-1]), show=False, colorbar=False) m = map2(zzr, title='Original', subplot=221, figsize=(8, 5), **kw) m.add_point(xi, yi, color='k') for i, method in enumerate(['nearest', 'linear', 'cubic']): # Interp
"""Test :meth:`vacumm.data.misc.arakawa.CGrid.interp`""" from vcmq import MV2, N, create_grid, create_dep, set_grid, map2, \ code_file_name, CGrid, minmax, curve2, add_grid # Initial variable grid = create_grid(N.arange(-7, 0.), N.arange(43, 50.)) dep = create_dep([-5000, -3000, -2000, -1000, -500, -300, -200, -100.]) var = {} var['t'] = MV2.reshape( N.arange(grid.size() * len(dep)) * 1., (len(dep), ) + grid.shape) set_grid(var['t'], grid) var['t'].setAxis(0, dep) # Arakawa manager ag = CGrid() # Interpolations for p in 'u', 'v', 'f', 'w': var[p] = ag.interp(var['t'], 't', p, mode='extrap') # Surface plots vmin, vmax = minmax(*[var[p][-1] for p in ['u', 'v', 'f']]) kw = dict(show=False, res=None, vmin=vmin, vmax=vmax, colorbar=False, grid=False, cmap='jet') m = map2(var['t'][-1],
zi_5d = N.resize(dep[:], (nez, nt, ny, nx, nz)) zi_5d = N.moveaxis(zi_5d, -1, 2) vo = grid2xy(vi, zi=zi_5d, xo=xo, yo=yo, zo=zo, to=to, method='linear') assert vo.shape==(ne, np) N.testing.assert_allclose(vo[0], yo) # Reversed 5d z zi_5d_rev = zi_5d[:, :, ::-1, :, :] vo = grid2xy(vi_revz, zi=zi_5d_rev, xo=xo, yo=yo, zo=zo, to=to, method='linear') N.testing.assert_allclose(vo[0], yo) # Zi present but not requested vo = grid2xy(vi, xo=xo, yo=yo, to=to, method='linear') assert vo.shape==(ne, nz, np) N.testing.assert_allclose(vo[0, 0], yo) # Zi and Ti present but not requested vo = grid2xy(vi, xo=xo, yo=yo, method='linear') assert vo.shape==(ne, nt, nz, np) N.testing.assert_allclose(vo[0, 0, 0], yo) # Curvilinear xy only vi_xyc = vi[:, 0, 0] gridc = rotate_grid(vi_xyc.getGrid(), 30) set_grid(vi_xyc, gridc) vi_xyc[:] = N.ma.resize(gridc.getLatitude()[:], vi_xyc.shape) vo = grid2xy(vi_xyc, xo=xo, yo=yo, method='linear') assert vo.shape==(ne, np) N.testing.assert_allclose(vo[0], yo)
"""Test :meth:`vacumm.data.misc.arakawa.CGrid.interp`""" from vcmq import MV2, N, create_grid, create_dep, set_grid, map2, \ code_file_name, CGrid, minmax, curve2, add_grid # Initial variable grid = create_grid(N.arange(-7, 0.), N.arange(43, 50.)) dep = create_dep([-5000, -3000, -2000, -1000, -500, -300, -200, -100.]) var = {} var['t'] = MV2.reshape(N.arange(grid.size()*len(dep))*1., (len(dep), )+grid.shape) set_grid(var['t'], grid) var['t'].setAxis(0, dep) # Arakawa manager ag = CGrid() # Interpolations for p in 'u', 'v', 'f', 'w': var[p] = ag.interp(var['t'], 't', p, mode='extrap') # Surface plots vmin, vmax = minmax(*[var[p][-1] for p in ['u', 'v', 'f']]) kw = dict(show=False, res=None, vmin=vmin, vmax=vmax, colorbar=False, grid=False, cmap='jet') m = map2(var['t'][-1], fill='pcolor', title='Interpolations on an Arakawa C grid: T->U/V/F', **kw) add_grid(var['t'], linestyle='-') kw.update(fill='scatter', contour=False, fill_s=60) markers = dict(u='>', v='^', f='D', t='o') for p in 't', 'u', 'v', 'f': m = map2(var[p][-1], fill_marker=markers[p], shadow=True, zorder=100, **kw)
config = { 'esmf':['linear', 'patch', 'conserv'], 'libcf':['linear'], } # Imports from vcmq import MV2, create_grid2d, code_file_name, os, CDATRegridder, N, set_grid, psinfo from vacumm.misc.grid import rotate_grid from time import time # Input nx = ny = 300 vari = MV2.array(N.arange(nx*ny*1.).reshape(ny, nx)) gridi = create_grid2d(vari.getAxis(1)[:]*50/nx, vari.getAxis(0)[:]*50/nx) set_grid(vari, gridi) # Output grid gridor = create_grid2d(vari.getAxis(1)[:]*0.09*50/nx, vari.getAxis(0)[:]*0.09*50/nx) gridoc = rotate_grid(gridi, 30) # Log logfile = code_file_name(ext='log') if os.path.exists(logfile): os.remove(logfile) f = open(logfile, 'w') print >>f, 'NY=%(ny)i, NX=%(nx)i'%locals() # Loop on methods for tool, methods in config.items(): for method in methods:
"""Test :func:`~vacumm.misc.grid.misc.varsel`""" # %% Imports from vcmq import N, MV2, create_grid, varsel, set_grid # %% With specified grid rgrid = create_grid((-14., -4, .25), (43., 52, .25), 'rect') var_ = MV2.reshape(MV2.arange(2 * rgrid.shape[0] * rgrid.shape[1]), (2, ) + rgrid.shape) var = var_.clone() cache = {} rvar0 = varsel(var, grid=rgrid, lon=(-9, -6, 'co'), lat=(44.1, 48.2), cache=cache) assert rvar0.shape == (2, 16, 12) assert rvar0.getLongitude()[-1] == -6.25 assert rvar0.getLatitude()[-1] == 48 set_grid(var, rgrid) # %% Without grid specification rvar1 = varsel(var, lon=(-9, -6, 'co'), lat=(44.1, 48.2)) N.testing.assert_allclose(rvar0.asma(), rvar1.asma()) # %% With cached gridded selector assert 'gridded_selector' in cache rvar2 = varsel(var_.clone(), lon=(-9, -6, 'co'), lat=(44.1, 48.2), cache=cache) N.testing.assert_allclose(rvar0.asma(), rvar2.asma())
"""Test :meth:`vacumm.data.misc.arakawa.CGrid.interp`""" from vcmq import MV2, N, create_grid, create_dep, set_grid, map2, \ CGrid, minmax, curve2, add_grid, ArakawaGridTransfer, set_loc # Initial variable grid = create_grid(N.arange(-7, 0.), N.arange(43, 50.)) dep = create_dep([-5000, -3000, -2000, -1000, -500, -300, -200, -100.]) varc = {} varc['t'] = MV2.reshape( N.arange(grid.size() * len(dep)) * 1., (len(dep), ) + grid.shape) set_grid(varc['t'], grid) varc['t'].setAxis(0, dep) set_loc(varc['t'], 't') # Arakawa managers ag = CGrid() gt = ArakawaGridTransfer('c', 'a') # Interpolations within same C grid for p in 'u', 'v', 'f', 'w': varc[p] = ag.interp(varc['t'], 't', p, mode='extrap') # Interpolation to A grid vara = {} for p in 't', 'u', 'v', 'f', 'w': vara[p] = gt.interp(varc[p], mode='extrap') # For unittest result = [] for p in 't', 'u', 'v', 'f', 'w':
"""Test :meth:`vacumm.data.misc.arakawa.CGrid.interp`""" from vcmq import MV2, N, create_grid, create_dep, set_grid, map2, \ CGrid, minmax, curve2, add_grid, ArakawaGridTransfer, set_loc # Initial variable grid = create_grid(N.arange(-7, 0.), N.arange(43, 50.)) dep = create_dep([-5000, -3000, -2000, -1000, -500, -300, -200, -100.]) varc = {} varc['t'] = MV2.reshape(N.arange(grid.size()*len(dep))*1., (len(dep), )+grid.shape) set_grid(varc['t'], grid) varc['t'].setAxis(0, dep) set_loc(varc['t'],'t') # Arakawa managers ag = CGrid() gt = ArakawaGridTransfer('c', 'a') # Interpolations within same C grid for p in 'u', 'v', 'f', 'w': varc[p] = ag.interp(varc['t'], 't', p, mode='extrap') # Interpolation to A grid vara = {} for p in 't', 'u', 'v', 'f', 'w': vara[p] = gt.interp(varc[p], mode='extrap') # For unittest result = [] for p in 't', 'u', 'v', 'f', 'w': result.append(('assertTrue', N.ma.allclose(varc['t'], vara[p])))
yyi[:,i] += i*0.5 gridi = create_grid2d(xxi,yyi) # input cdms grid xxib,yyib = meshbounds(xxi,yyi) # coordinates of cell corners # Output curved grid nxo = 7 nyo = 7 xxo, yyo = N.meshgrid(N.arange(nxo)+.5, N.arange(nyo)-.5) grido = create_grid2d(xxo, yyo) # output cdms grid xxob,yyob = meshbounds(xxo,yyo) # coordinates of cell corners # Input field vari = MV2.array(N.arange(nyi*nxi).reshape(nyi,nxi))+10. vari[1,1:3] = 100 vari[:2,1:3] = MV2.masked set_grid(vari, gridi) # set grid and axes #gridi.setMask(vari.mask) # Define plot function figfile = code_file_name(ext=False)+'_%(ifig)i.png' #'%(tool)s_%(method)s.png' figfiles = [] rc('font',size=9) kw = dict(vmin=vari.min(),vmax=vari.max()) # Define logger logfile = code_file_name(ext='log') f = open(logfile, 'w') def log(f, text): # logger # print text print >>f, text