method='conservative', diag=diag, coordSys='cart') # Norm frac = diag['dstAreaFractions'] mask = frac == 0. frac[mask] = 1. varo[:] /= frac varo[:] = MV2.masked_where(mask, varo, copy=0) # Plot rc('font', size=9) kw = dict(vmin=vari.min(), vmax=vari.max()) axis = [xxbi.min(), xxbi.max(), yybo.min(), yybo.max()] P.figure(figsize=(7, 3)) P.subplot(121, aspect=1) P.pcolormesh(xxbi, yybi, vari, **kw) P.colorbar(shrink=0.7) add_grid(gridi, color='0.5') add_grid(grido) P.axis(axis) P.title('Original: max=%g min=%g' % (vari.max(), vari.min())) P.subplot(122, aspect=1) P.pcolormesh(xxbo, yybo, varo, **kw) P.colorbar(shrink=0.7) add_grid(gridi) add_grid(grido, color='0.5') P.axis(axis) P.title('Regridded: max=%g min=%g' % (varo.max(), varo.min())) P.tight_layout()
"""Test the :func:`~vacumm.misc.grid.masking.create_polygon` function""" from vcmq import N, P, create_polygon, plot_polygon, code_file_name from _geoslib import Polygon # Data xx = N.array([0., 5., 4., 1.]) yy = N.array([0., 0., 2., 2.]) # From Polygon P.figure(figsize=(5, 5)) p0 = create_polygon(Polygon(N.array([xx, yy]).T)) plot_polygon(p0, color='b', label='From poly') # From data p1 = create_polygon(N.array([xx, yy]).T - .25) plot_polygon(p1, color='r', label='From data') # From transposed data p2 = create_polygon(N.array([xx, yy]) - 0.5) plot_polygon(p2, color='g', label='From transposed data') # From min/max p3 = create_polygon([xx.min(), yy.min(), xx.max(), yy.max()]) plot_polygon(p3, color='m', label='From min/max') # With projection proj = lambda x, y: (x * 1.5, y * 1.5) p4 = create_polygon(p0, proj=proj) plot_polygon(p4, color='cyan', label='With projection') # Save
"""Test the :func:`~vacumm.misc.grid.masking.create_polygon` function""" from vcmq import N, P, create_polygon, plot_polygon, code_file_name from _geoslib import Polygon # Data xx = N.array([0., 5., 4., 1.]) yy = N.array([0., 0., 2., 2.]) # From Polygon P.figure(figsize=(5, 5)) p0 = create_polygon(Polygon(N.array([xx, yy]).T)) plot_polygon(p0, color='b', label='From poly') # From data p1 = create_polygon(N.array([xx, yy]).T-.25) plot_polygon(p1, color='r', label='From data') # From transposed data p2 = create_polygon(N.array([xx, yy])-0.5) plot_polygon(p2, color='g', label='From transposed data') # From min/max p3 = create_polygon([xx.min(), yy.min(), xx.max(), yy.max()]) plot_polygon(p3, color='m', label='From min/max') # With projection proj = lambda x, y: (x*1.5, y*1.5) p4 = create_polygon(p0, proj=proj) plot_polygon(p4, color='cyan', label='With projection') # Save
"""Test :class:`~vacumm.misc.color.desaturate` """ # Imports from vcmq import P, desaturate, code_file_name, plot_cmap cmap_name = "CMRmap" cmap_old = P.get_cmap(cmap_name) # Max cmap_10 = desaturate(cmap_old, 1) # Medium cmap_05 = desaturate(cmap_old, 0.5) # Min cmap_00 = desaturate(cmap_old, 0) # Plot fig = P.figure(figsize=(6, 2)) kw = dict(fig=fig, figsize=None, aspect=.15, show=False, close=False) P.subplot(221) plot_cmap(cmap_old, title='Original', **kw) P.subplot(222) plot_cmap(cmap_00, title='f = 0.0', **kw) P.subplot(223) plot_cmap(cmap_05, title='f = 0.5', **kw) P.subplot(224) plot_cmap(cmap_10, title='f = 1.0', **kw) P.tight_layout() P.figtext(.5, 1, 'Desaturate '+cmap_name, va='top', ha='center', size=12)
# 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'), (-2, 2, 'linear')]): varo = extend1d(vari, ext=ext, axis=axis, mode=mode) plot2d(varo, subplot=(2, 2, i + 3),
zzov = griddata(xi, yi, zi, (xr, yr), method='nat', ext=True, sub=10) # -> Tester la methode "carg" # -> Testez parametre sub=... # -> Essayer avec GridData zov2 = xy2xy(xi, yi, zi, xo, yo) # Krigeage from vacumm.misc.grid.kriging import krig zzok = krig(xi, yi, zi, xxr.ravel(), yyr.ravel(), nproc=1).reshape(zzr.shape) # -> Tester nproc et npmax # Plots from vcmq import meshbounds, P xxrb, yyrb = meshbounds(xr, yr) P.figure(figsize=(10, 8)) axis = [xxrb.min(), xxrb.max(), yyrb.min(), yyrb.max()] # P.subplot(332) P.pcolormesh(xxrb, yyrb, zzr, **vminmax) P.scatter(xi, yi, c='k') P.title('Original') P.axis(axis) # P.subplot(334) P.pcolormesh(xxrb, yyrb, zzoc, **vminmax) P.title('CDAT/Natgrid') P.axis(axis) # P.subplot(335) P.pcolormesh(xxrb, yyrb, zzork, **vminmax)
vari[int(nyi*0.4):int(nyi*0.4)+3, int(nxi*0.4):int(nxi*0.4)+2] = N.ma.masked xxib, yyib = meshcells(xi, yi) nxo = 40 nyo = 25 xo = N.linspace(int(nxi*0.2),int(nxi*1.2),nxo) yo = N.linspace(int(-nyi*0.2),int(nyi*0.8),nyo) xxob, yyob = meshcells(xo, yo) vari.shape = (1, )+vari.shape varo = N.ma.masked_values(dstwgt(vari.filled(), xi, yi, xo, yo, mv, 0), mv) kw = dict(vmin=vari.min(), vmax=vari.max()) axlims = [min(xi.min(), xo.min()), max(xi.max(), xo.max()), min(yi.min(), yo.min()), max(yi.max(), yo.max())] P.figure(figsize=(8, 4)) P.subplot(211) P.pcolor(xxib, yyib, vari[0], **kw) P.axis(axlims) P.title('Original') P.subplot(212) P.pcolor(xxob, yyob, varo[0], **kw) P.axis(axlims) P.title('Distance weight') P.tight_layout() figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.show() P.close()
"""Test the :func:`~vacumm.misc.grid.io.Shapes` class""" from vcmq import N, P, code_file_name, data_sample from vacumm.misc.io import Shapes result = [] # File names shpfile = data_sample("ne_110m_land/ne_110m_land") figfile = code_file_name(ext=False) + '_%i.png' # Basic S = Shapes(shpfile) result.append(('assertEqual', [len(S), 127])) S.plot(title='Basic', show=False) P.savefig(figfile % 0) P.close() # Min area S = Shapes(shpfile, min_area=1000) result.append(('assertEqual', [len(S), 3])) S.plot(title='Min area', show=False) P.savefig(figfile % 1) P.close() # Projection S = Shapes(shpfile, proj='merc') result.append(('assertGreater', [S[1].area(), 1e12])) S.plot(title='Projected', show=False) P.savefig(figfile % 2) P.close()
diag = {'dstAreaFractions':None} varo = vari.regrid(grido, tool='esmf', method='conservative', diag=diag, coordSys='cart') # Norm frac = diag['dstAreaFractions'] mask = frac==0. frac[mask]=1. varo[:] /= frac varo[:] = MV2.masked_where(mask, varo, copy=0) # Plot rc('font', size=9) kw = dict(vmin=vari.min(), vmax=vari.max()) axis = [xxbi.min(), xxbi.max(), yybo.min(), yybo.max()] P.figure(figsize=(7, 3)) P.subplot(121, aspect=1) P.pcolormesh(xxbi, yybi, vari, **kw) P.colorbar(shrink=0.7) add_grid(gridi, color='0.5') add_grid(grido) P.axis(axis) P.title('Original: max=%g min=%g'%(vari.max(), vari.min())) P.subplot(122, aspect=1) P.pcolormesh(xxbo, yybo, varo, **kw) P.colorbar(shrink=0.7) add_grid(gridi) add_grid(grido, color='0.5') P.axis(axis) P.title('Regridded: max=%g min=%g'%(varo.max(), varo.min())) P.tight_layout()
from vacumm.misc.grid.misc import rotate_grid from vacumm.misc.grid.regridding import CurvedInterpolator from vcmq import P, N, set_grid, plot2d, MV2, add_grid, code_file_name, os # Curved grid nxy = 10 lon = N.arange(nxy*1.) lat = N.arange(nxy*1.) gridi = rotate_grid((lon, lat), 30) xxi = gridi.getLongitude()[:].filled() yyi = gridi.getLatitude()[:].filled() vari = MV2.array(yyi) set_grid(vari, gridi) kw = dict(vmin=vari.min(), vmax=vari.max()) P.figure(figsize=(10, 3.5)) P.subplot(131, aspect=1) P.contourf(xxi, yyi, vari.asma(), **kw) add_grid(gridi, edges=False, centers=-1) xylims = (xxi.min(), xxi.max(), yyi.min(), yyi.max()) P.axis(xylims) P.title('Curved grid') # Interpolate to grid xg, yg = N.meshgrid(N.arange(-3.5, 14.5), N.arange(-3.5, 14.5)) nxyg = xg.shape cig = CurvedInterpolator(gridi, (xg, yg), g2g=True) varog = cig(vari) P.subplot(132, aspect=1) P.scatter(xg, yg, c=varog.asma(), s=120, linewidth=0, **kw) add_grid(gridi, edges=False, centers=-1)
def plot_fields(self, variables, surf=None, bottom=None, horiz_sections=False, points=None, zonal_sections=None, merid_sections=None, titlepat="{var_name} - {slice_loc}", props=None, subst={}, figpat='sonat.ens.{var_name}_{slice_type}_{slice_loc}.png', fmtlonlat=u'{:.2f}°{}', fmtdep='{:04.0f}m', savefig=True, obs=None, close=True, show=False, **kwargs): """Plot one or several platform like variables Parameters ---------- depths: string, floats List of depths for horizontal slices. All by default. It accepts scalars or list of floats and of the two special values "bottom" and "surf". In the latter case, these variable must be explicitely included in the ensemble, like "temp_surf". A depth of 0 is not equivalent to "surf", despite results may be similar, or equivalent when the sea level is always 0. In the case of floats, the ensemble must contain 3d variables. props: dict, None Dictionary of graphic properties passed as keywords to plotting functions. The keys must be valid diagnostics names such as "mean", or one of the follow plotting function: map, curve. """ # Init if props is None: props = {} kwprops = dict_merge(props, DEFAULT_PLOT_KWARGS_PER_ENS_DIAG) kwprops.update(fig='new') # TODO: must be more flexible like for obs figs = OrderedDict() kwobs = kwfilter(kwargs, 'obs') kwobs.update(surf=False, bottom=False, zonal_sections=None, merid_sections=None, horiz_sections=None) # Loop on variables for variable in ArgList(variables).get(): var_short_name, var_depth, diag_name = split_varname(variable) diag_name = getattr(variable, 'sonat_ens_diag', diag_name) var_name = (var_short_name if var_depth is None else (var_short_name + '_' + var_depth)) varname = var_name id = variable.id self.debug(' Variable: ' + id) order = variable.getOrder() if diag_name: kw = kwprops.get(diag_name, {}) else: kw = {} toplot = [] # Maps if (horiz_sections is not False or surf is not False or bottom is not False): # Surf/bottom/3D if ((var_depth == 'surf' and surf is not False) or (var_depth == 'bottom' and bottom is not False)): # 2D slice_loc = var_depth toplot.append( dict(slice_loc=slice_loc, kw=kw, keys=(var_short_name, 'map', slice_loc), obs_plot={var_depth: True}, slice_type='map')) elif (variable.getLevel() is not None and horiz_sections is not False and horiz_sections is not None): # 3D # Surf and bottom for ok, slice_loc in [(surf, 'surf'), (bottom, 'bottom')]: if ok is True: toplot.append( dict( slice_loc=slice_loc, slice_type='map', keys=(var_short_name, 'map', slice_loc), kw=dict_merge(dict(depth=slice_loc), kw), obs_plot={slice_loc: True}, )) # Loop on 3D depths specs if horiz_sections is True: depths = variable.getLevel() else: depths = horiz_sections if N.isscalar(depths): depths = [depths] depths = list(depths) for depth in depths: if isinstance(depth, str): slice_loc = depth else: slice_loc = fmtdep.format(abs(depth)) toplot.append( dict( slice_loc=slice_loc, slice_type='map', keys=(var_name, 'map', slice_loc), kw=dict_merge(dict(depth=depth), kw), obs_plot={'horiz_sections': depth}, )) # Zonal sections if zonal_sections is not None and zonal_sections is not False: slice_type = 'zonal' if N.isscalar(zonal_sections): zonal_sections = [zonal_sections] for lat in zonal_sections: slice_loc = latlab(lat, no_symbol=True) toplot.append( dict( slice_loc=slice_loc, slice_type=slice_type, keys=(var_name, slice_type, slice_loc), kw=dict_merge(dict(lat=lat), kw), obs_plot={'zonal_sections': lat}, )) # Meridional sections if merid_sections is not None and merid_sections is not False: slice_type = 'merid' if N.isscalar(merid_sections): merid_sections = [merid_sections] for lon in merid_sections: slice_loc = lonlab(lon, no_symbol=True) toplot.append( dict( slice_loc=slice_loc, slice_type=slice_type, keys=(var_name, slice_type, slice_loc), kw=dict_merge(dict(lon=lon), kw), obs_plot={'merid_sections': lon}, )) # # Points # if points: # slice_type = 'point' # if isinstance(points, tuple): # points = [points] # for lon, lat in points: # slice_loc = (lonlab(lon, no_symbol=True) + '-' + # latlab(lat, no_symbol=True)) # toplot.append(dict( # slice_loc=slice_loc, # slice_type=slice_type, # keys=(var_name, slice_type, slice_loc), # kw=dict_merge(dict(lon=lon, lat=lat), kw), # obs_plot={'points':(lon, lat)}, # )) # Make all pending plots for this variable for spec in toplot: # Get specs slice_loc = spec['slice_loc'] slice_type = spec['slice_type'] obs_plot = spec['obs_plot'] keys = map(str.title, spec['keys']) kw = kwargs.copy() kw.update(spec['kw']) self.debug(' Location: ' + slice_loc) # Setup dfmt = locals() dfmt.update(subst) title = titlepat.format(**dfmt) kw.update(title=title, savefig=False, close=False) dict_check_defaults(kw, fig='new', **DEFAULT_PLOT_KWARGS_PER_ENS_DIAG) # Plot p = plot_gridded_var(variable, **kw) # Action ! # Plot obs locations on 2D plots only if obs and isinstance(p, Plot2D): #FIXME: should we pass lon/lat/level from variable? kwo = kwobs.copy() kwo.update(obs_plot, full3d=False, full2d=False, plotter=p, savefig=False, close=False, title=False, colorbar=False) # obs.set_cached_plot('locations', slice_type, slice_loc, p) obs.plot('locations', **kwo) # Finalise if savefig: figfile = figpat.format(**dfmt) checkdir(figfile) p.savefig(figfile) close = True self.created(figfile) kw = {keys[-1]: figfile, '__class__': OrderedDict} dicttree_set(figs, *keys[:-1], **kw) if not show and close: p.close() if show: P.show() elif close: P.close() return figs
# Generate random field xg, yg, zzg = gridded_gauss3() xi, yi, zi = random_gauss3(np=npi) # Interpolate to random points xo, yo = random_points(np=npo) zo = krig(xi, yi, zi, xo, yo) # Plot # - source data axis = [xg.min(), xg.max(), yg.min(), yg.max()] kw = dict(vmin=zzg.min(), vmax=zzg.max()) kwim = dict(extent=axis, interpolation='bilinear', origin='lower', alpha=.2, **kw) kwsc = dict(lw=0.2, **kw) P.figure(figsize=(6, 3.5)) P.subplot(121) P.title('Source field') P.imshow(zzg, **kwim) P.scatter(xi, yi, c=zi, **kwsc) P.axis(axis) # - interpolated data P.subplot(122) P.title('Interpolated points') P.imshow(zzg, **kwim) P.scatter(xo, yo, c=zo, marker='s', s=30, **kwsc) P.axis(axis) P.tight_layout() savefigs(code_file_name(), verbose=False) P.close()
xg, yg, zzg = gridded_gauss3() xi, yi, zi = random_gauss3(np=npi) zi = N.vstack((zi, zi)) # simulate several time steps for multifit # Init kriger kriger = OrdinaryCloudKriger(xi, yi, zi, npmax=npmax, nproc=nproc) # Output points xo, yo = random_points(np=npo) # Interpolate t0 = time() zo = kriger(xo, yo) # Plot P.figure(figsize=(6, 8)) axis = [xg.min(), xg.max(), yg.min(), yg.max()] kw = dict(vmin=zi.min(), vmax=zi.max()) kwim = dict(extent=axis, interpolation='bilinear', origin='lower', alpha=.2, **kw) kwsc = dict(lw=0.2, **kw) P.subplot(211) P.imshow(zzg, **kwim) P.scatter(xi, yi, c=zi if zi.ndim==1 else zi[0], s=20, **kwsc) P.title('Input points') P.subplot(212) P.imshow(zzg, **kwim) P.scatter(xo, yo, c=zo if zo.ndim==1 else zo[0], s=40, **kwsc) P.title('Interpolated points') P.tight_layout() savefigs(code_file_name(), verbose=False) P.close()
"""Test the :func:`~vacumm.misc.grid.io.Shapes` class""" from vcmq import N, P, code_file_name, data_sample from vacumm.misc.io import Shapes result = [] # File names shpfile = data_sample("ne_110m_land/ne_110m_land") figfile = code_file_name(ext=False)+'_%i.png' # Basic S = Shapes(shpfile) result.append(('assertEqual', [len(S), 127])) S.plot(title='Basic', show=False) P.savefig(figfile%0);P.close() # Min area S = Shapes(shpfile, min_area=1000) result.append(('assertEqual', [len(S), 3])) S.plot(title='Min area', show=False) P.savefig(figfile%1);P.close() # Projection S = Shapes(shpfile, proj='merc') result.append(('assertGreater', [S[1].area(), 1e12])) S.plot(title='Projected', show=False) P.savefig(figfile%2);P.close() # Clips S = Shapes(shpfile, clip=[-10, 42, 10, 51.]) result.append(('assertEqual', [len(S), 3])) S.plot(title='Clipped', show=False)
yi = N.arange(nxy*1.) xxi, yyi = N.meshgrid(xi, yi) zi = N.ma.array(yyi) zi[int(nxy*0.3):int(nxy*0.8), int(nxy*0.3):int(nxy*0.8)] = N.ma.masked zi.shape = 1, nxy, nxy # Output positions no = 1000 xo = N.random.uniform(-nxy/4., nxy+nxy/4., no) yo = N.random.uniform(-nxy/4., nxy+nxy/4., no) # Interpolate mv = zi.get_fill_value() zo = nearest2dto1d(xi,yi,zi.filled(mv),xo,yo,mv) zo = N.ma.masked_values(zo, mv) # Plot kw = dict(vmin=zi.min(), vmax=zi.max()) P.figure(figsize=(6, 6)) P.subplot(111, aspect=1) P.contourf(xxi, yyi, zi[0], **kw) add_grid((xi, yi), edges=False, centers=True, marker='o') P.scatter(xo, yo, c=zo[0], s=50, **kw) P.title('nearest2dto1d') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.close()
nb = 10 xxbi, yybi = meshbounds(xxi, yyi) # Output grid grido = rotate_grid((N.linspace(0, 6, 50)-1, N.linspace(0, 4, 35)+1.), -20) xxo = grido.getLongitude()[:].filled() yyo = grido.getLatitude()[:].filled() xxbo, yybo = meshbounds(xxo, yyo) # Nearest varo = nearest2d(vari, xxi, yyi, xxo, yyo, nb) # Plot vmin = varo.min() vmax = varo.max() P.figure(figsize=(8, 4)) P.subplot(121, aspect=1) P.pcolor(xxbi, yybi, vari[0], vmin=vmin, vmax=vmax) add_grid(grido) P.title('original') P.subplot(122, aspect=1) P.pcolor(xxbo, yybo, varo[0], vmin=vmin, vmax=vmax) add_grid(gridi) P.title('nearest2d') P.axis('image') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.show() P.close()
# Generate random gridded field xi, yi, zzi = gridded_gauss3(nx=nxi, ny=nyi) xxi, yyi = N.meshgrid(xi, yi) # Refined grid xo = N.linspace(xi[0], xi[-1], (nxi-1)*r+1) yo = N.linspace(yi[0], yi[-1], (nyi-1)*r+1) xxo, yyo = N.meshgrid(xo, yo) # Interpolate zzo = krig(xxi.ravel(), yyi.ravel(), zzi.ravel(), xxo.ravel(), yyo.ravel()) zzo.shape = xxo.shape # Section P.figure(figsize=(8, 4)) iyis = [3, 4] for iyi in iyis: label = iyi==iyis[0] P.plot(xi, zzi[iyi], 'ob-', markersize=8, label='Original' if label else None) P.plot(xo, zzo[iyi*r], 'or-', markersize=5, lw=.8, label='Interpolated' if label else None) P.legend(loc='best', framealpha=0.5) P.grid() P.title('Section') P.tight_layout() savefigs(code_file_name(ext='_0.png'), verbose=False, pdf=True) # Maps P.figure(figsize=(8, 4)) levels = auto_scale(vmin=zzi.min(), vmax=zzi.max(), nmax=30) P.subplot(121)
# -*- coding: utf8 -*- # Read sea level at Brest from vcmq import cdms2, P, curve2, savefigs, data_sample f = cdms2.open(data_sample("tide.sealevel.BREST.mars.nc")) sea_level = f('sea_level') f.close() # Filtering from vacumm.tide.filters import demerliac cotes, tide = demerliac(sea_level, get_tide=True) # Plots kwplot = dict(date_fmt='%d/%m', show=False, date_rotation=0) # - tidal signal curve2(sea_level, 'k', subplot=211, label='Original', title='Sea level at Brest',**kwplot) curve2(tide, 'b', label='Tidal signal', **kwplot) P.legend().legendPatch.set_alpha(.7) # - surcotes/decotes curve2(cotes, 'r', subplot=212, hspace=.3, label='Demerliac', **kwplot) P.legend().legendPatch.set_alpha(.7) savefigs(__file__, savefigs_pdf=True)
def plot(xx, yy, target, label, figfiles, figfile, lon=None, lat=None, show=False): xs, ys, mask = coord2slice(target, lon=lon, lat=lat) P.figure(figsize=(6, 3.5)) P.title('Target=%(label)s / select: lon=%(lon)s, lat=%(lat)s'%locals()) add_grid((xx, yy)) xx = xx.asma() yy = yy.asma() if isinstance(lon, tuple): P.axvline(lon[0], color='m', ls='--', lw=2) P.axvline(lon[1], color='m', ls='--', lw=2) elif isinstance(lon, slice): i, j, k = lon.indices(xx.shape[1]) P.plot(xx[:, i], yy[:, i], 'c--', lw=2) P.plot(xx[:, j-1], yy[:, j-1], 'c--', lw=2) if isinstance(lat, tuple): P.axhline(lat[0], color='m', ls='--', lw=2) P.axhline(lat[1], color='m', ls='--', lw=2) elif isinstance(lat, slice): i, j, k = lat.indices(yy.shape[0]) P.plot(xx[i], yy[i], 'c--', lw=2) P.plot(xx[j-1], yy[j-1], 'c--', lw=2) P.xticks(N.arange(xx.min()-1, xx.max()+1)) P.yticks(N.arange(yy.min()-1, yy.max()+1)) xxi, yyi = xx, yy xx = xx[ys, xs] yy = yy[ys, xs] # mask = mask[ys, xs] xxb, yyb = meshbounds(xx, yy) P.pcolor(xxb, yyb, mask, shading='faceted') P.scatter(xx.ravel(), yy.ravel(), c=(0, 1, 0)) P.grid('on') P.axis('image') P.tight_layout() i = len(figfiles) savefig = figfile%i if os.path.exists(savefig): os.remove(savefig) P.savefig(savefig) figfiles.append(savefig) if show: P.show() else: P.close()
create_time, CurvedInterpolator, rotate_grid) # Curved grid nxy = 10 nt = 5 lon = N.arange(nxy * 1.) lat = N.arange(nxy * 1.) time = create_time((nt, ), 'years since 2000') gridi = rotate_grid((lon, lat), 30) xxi = gridi.getLongitude()[:].filled() yyi = gridi.getLatitude()[:].filled() vari = MV2.resize(yyi, (nt, nxy, nxy)) vari.setAxis(0, time) set_grid(vari, gridi) kw = dict(vmin=vari.min(), vmax=vari.max()) P.figure(figsize=(10, 3.5)) P.subplot(131, aspect=1) P.contourf(xxi, yyi, vari[0].asma(), **kw) add_grid(gridi, edges=False, centers=-1) xylims = (xxi.min(), xxi.max(), yyi.min(), yyi.max()) P.axis(xylims) P.title('Curved grid') # Interpolate to grid xg, yg = N.meshgrid(N.arange(-3.5, 14.5), N.arange(-3.5, 14.5)) nxyg = xg.shape cig = CurvedInterpolator(gridi, (xg, yg), g2g=True) varog = cig(vari) P.subplot(132, aspect=1) P.scatter(xg, yg, c=varog[0].asma(), s=120, linewidth=0, **kw) add_grid(gridi, edges=False, centers=-1)
nx = ny = 50 np = 500 mtype = 'gauss' dmax = 2.5 from vcmq import N, P, code_file_name, savefigs from vacumm.misc.grid.kriging import gridded_gauss3, random_gauss3, variogram, variogram_fit # Generate random field xxg, yyg, zzg = gridded_gauss3(nx=nx, ny=ny) x, y, z = random_gauss3(np=np) # Variogram from data d, v = variogram(x, y, z, dmax=dmax) # Variogram fit with null nugget vm = variogram_fit(x, y, z, mtype, n=0, dmax=dmax) D = N.linspace(0, d.max()) V = vm(D) # Compare P.figure(figsize=(6, 4)) P.title('Variogram') P.plot(d, v, 'ob', label='From data') P.plot(D, V, '-r', label='Fitted model (%s)'%mtype) P.legend(loc='best') P.ylim(ymin=0) savefigs(code_file_name(ext=False), pdf=True, verbose=False) P.close()
yi = N.array(yi) zi = N.array(zi) xxg, yyg = N.meshgrid(xg, yg) xo = xxg.ravel() yo = yyg.ravel() vgm = variogram_model('linear', n=0, s=sill, r=range) # Setup the kriger sck = SimpleCloudKriger(xi, yi, zi, vgf=vgm, farvalue=farvalue) # Interpolate zo = sck(xo, yo) # Check a far value zzg = zo.reshape(ny, nx) N.testing.assert_allclose(zzg[-1, -1], farvalue) # Plot vmin = min(zi.min(), zo.min()) vmax = max(zi.max(), zo.max(), farvalue) cmap = 'cmocean_ice' kw = dict(vmin=vmin, vmax=vmax) P.pcolormesh(xxg, yyg, zzg, cmap=cmap, **kw) P.colorbar() P.scatter(xi, yi, c=zi, s=100, cmap=cmap, **kw) P.axis('image') P.title('Simple kriging with fixed far value') P.savefig(code_file_name(ext='.png')) P.show() P.close()
"""Test :class:`~vacumm.misc.color.pastelise` """ # Imports from vcmq import P, pastelise, code_file_name, plot_cmap cmap_name = "jet" cmap_old = P.get_cmap(cmap_name) # Pastelise cmap_new = pastelise(cmap_old, s=.15, v=.9) # Plot fig = P.figure(figsize=(6, 2)) kw = dict(fig=fig, figsize=None, aspect=.15, show=False, close=False) P.subplot(211) plot_cmap(cmap_old, title='Original', **kw) P.subplot(212) plot_cmap(cmap_new, title='Pastelised', **kw) P.tight_layout() P.figtext(.5, 1, 'Pastelise ' + cmap_name, va='top', ha='center', size=12) P.show() P.savefig(code_file_name(ext='png')) P.close()
# Format and convert xx, yy = N.meshgrid(N.arange(-2, 4, 0.25), N.arange(-1, 5, 0.25)) nxy = xx.shape xx.shape = -1 yy.shape = -1 pp, qq = [], [] for x, y in zip(xx, yy): p, q = curv2rect(x1,x2,x3,x4,y1,y2,y3,y4,x,y) pp.append(p) qq.append(q) pp = N.array(pp) qq = N.array(qq) # Plot xp = [x1, x2, x3, x4, x1] yp = [y1, y2, y3, y4, y1] P.subplot(211) levels = N.array([-10, 0, 1, 10.]) o = P.contourf(xx.reshape(nxy), yy.reshape(nxy), pp.reshape(nxy), levels=levels) P.colorbar(o) P.plot(xp, yp, 'k') P.subplot(212) o = P.contourf(xx.reshape(nxy), yy.reshape(nxy), qq.reshape(nxy), levels=levels) P.colorbar(o) P.plot(xp, yp, 'k') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.close()
"""Test :func:`~vacumm.misc.plot.add_logo`""" # Imports from vcmq import N, P, add_logo, os, code_file_name, data_sample import matplotlib.image as mpimg # Inits logofile = data_sample('logo_ifremer.png') P.plot([2, 6]) # Default add_logo(logofile, scale=1) # Upper right / no rescale add_logo(logofile, loc='upper right') # Rescale add_logo(logofile, loc='upper left', scale=2) # Alpha add_logo(logofile, loc='lower right', alpha=0.2) # Save figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile)
iib, jjb = meshbounds(ii, jj) zzi = jj * nyi + ii #relpos2index(ii, jj) zzbi = jjb * nyi + iib # ny+1? relpos2index(iib, jjb) # Input random points N.random.seed(0) np = 100 xxo = N.random.random(np) * (xxbi.max() - xxbi.min()) + xxbi.min() yyo = N.random.random(np) * (yybi.max() - yybi.min()) + yybi.min() xxo = N.concatenate((xxo, xxi.ravel())) yyo = N.concatenate((yyo, yyi.ravel())) np = xxo.size # Convert to relative indices pp, qq = curv2rel(xxbi, yybi, xxo, yyo) bad = pp < 0 zzo = (qq - 1) * nyi + pp - 1 #relpos2index(pp-1, qq-1) zzo[bad] = -1 # Plot vmin = zzbi.min() vmax = zzbi.max() P.pcolor(xxbi, yybi, zzi, vmin=vmin, vmax=vmax) P.scatter(xxo, yyo, c=zzo, vmin=vmin, vmax=vmax, s=80) P.grid() P.title('curv2rel') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.close()
"""Test :class:`~vacumm.misc.color.pastelise` """ # Imports from vcmq import P, pastelise, code_file_name, plot_cmap cmap_name = "jet" cmap_old = P.get_cmap(cmap_name) # Pastelise cmap_new = pastelise(cmap_old, s=.15, v=.9) # Plot fig = P.figure(figsize=(6, 2)) kw = dict(fig=fig, figsize=None, aspect=.15, show=False, close=False) P.subplot(211) plot_cmap(cmap_old, title='Original', **kw) P.subplot(212) plot_cmap(cmap_new, title='Pastelised', **kw) P.tight_layout() P.figtext(.5, 1, 'Pastelise '+cmap_name, va='top', ha='center', size=12) P.show() P.savefig(code_file_name(ext='png')) P.close()
"""Test :class:`~vacumm.misc.color.darken` """ # Imports from vcmq import P, darken, code_file_name, plot_cmap cmap_name = "CMRmap" cmap_old = P.get_cmap(cmap_name) # Max cmap_10 = darken(cmap_old, 1) # Medium cmap_05 = darken(cmap_old, 0.5) # Min cmap_00 = darken(cmap_old, 0) # Plot fig = P.figure(figsize=(6, 2)) kw = dict(fig=fig, figsize=None, aspect=.15, show=False, close=False) P.subplot(221) plot_cmap(cmap_old, title='Original', **kw) P.subplot(222) plot_cmap(cmap_00, title='f = 0.0', **kw) P.subplot(223) plot_cmap(cmap_05, title='f = 0.5', **kw) P.subplot(224) plot_cmap(cmap_10, title='f = 1.0', **kw) P.figtext(.5, 1, 'Darken ' + cmap_name, va='top', ha='center', size=12) P.tight_layout() P.savefig(code_file_name(ext='png'))
nb = 10 xxbi, yybi = meshbounds(xxi, yyi) # Output grid grido = rotate_grid((N.linspace(0, 6, 50) - 1, N.linspace(0, 4, 35) + 1.), -20) xxo = grido.getLongitude()[:].filled() yyo = grido.getLatitude()[:].filled() xxbo, yybo = meshbounds(xxo, yyo) # Nearest varo = nearest2d(vari, xxi, yyi, xxo, yyo, nb) # Plot vmin = varo.min() vmax = varo.max() P.figure(figsize=(8, 4)) P.subplot(121, aspect=1) P.pcolor(xxbi, yybi, vari[0], vmin=vmin, vmax=vmax) add_grid(grido) P.title('original') P.subplot(122, aspect=1) P.pcolor(xxbo, yybo, varo[0], vmin=vmin, vmax=vmax) add_grid(gridi) P.title('nearest2d') P.axis('image') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.show() P.close()
m.add_key('B', pos='top right', xmargin=20) # Point m.add_point(-5.3, 48.3, color='b', shadow=True, edgecolor='r', size=120) # Place = point + text m.add_place(-4.62138, 48.38197, 'Plouzane', size=100) # Add lines m.add_line([-5.3, 48, -5, 49], color='r') m.add_lines([-5.3, -4.7, -5], [48, 48.5, 49], color='g') # Add box m.add_box([-6.1, 48.1, -5.5, 48.9], color='k', shadow=True, linewidth=3) # Add arrow m.add_arrow(-6, 48.5, 5, 5) # Add map scale (maps only) m.add_mapscale(barstyle='fancy') # Add compass(maps only) m.add_compass(pos=(0.97, .5)) # Add both! m.add_mscp(pos='upper left') P.tight_layout() P.subplots_adjust(bottom=0.08) m.savefigs(__file__)
"""Test function :func:`~vacumm.misc.grid.kriging.cloud_split`""" nps = [100, 60, 40] npmax = 90 dxy = 5 from vcmq import P, simple_colors, savefigs, code_file_name, N from vacumm.misc.grid.kriging import cloud_split # Input clouds xx = [] yy = [] P.figure(figsize=(7, 3.5)) P.subplot(121, aspect=1) colors = simple_colors[1:] for i, np in enumerate(nps): xc = P.rand(1)*dxy*2.5 yc = P.rand(1)*dxy*2.5 x = P.rand(np)*dxy+xc y = P.rand(np)*dxy+yc xx.extend(x) yy.extend(y) P.scatter(x, y, c=colors[i:i+1], s=40) P.title('Original (mixed clouds)') # Spliting indices, centroids = cloud_split(xx, yy, getdist=False, getcent=True, npmax=npmax) # Plot P.subplot(122, aspect=1) xx = N.array(xx)
zzbi = relpos2index(iib, jjb, nyi) # Input random points N.random.seed(0) np = 100 xxo = N.random.random(np)*(xxbi.max()-xxbi.min()) + xxbi.min() yyo = N.random.random(np)*(yybi.max()-yybi.min()) + yybi.min() xxo = N.concatenate((xxo, xxi.ravel())) yyo = N.concatenate((yyo, yyi.ravel())) np = xxo.size # Convert to relative indices zzo = N.zeros(np)-1 for i, (xo, yo) in enumerate(zip(xxo, yyo)): p, q = curv2rel_single(xxbi, yybi, xo, yo) # print xo, yo, '|', p, q, (q-1) * nxi + p - 1 if q>=0: zzo[i] = relpos2index(p-1, q-1, nyi) # Plot vmin = zzbi.min() vmax = zzbi.max() P.pcolor(xxbi, yybi, zzi, vmin=vmin, vmax=vmax) P.scatter(xxo, yyo, c=zzo, vmin=vmin, vmax=vmax, s=80) P.grid() P.title('curv2rel_single') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.close()
plot2d(varo[0], title='ESMF / Bilinear', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - bilin c2c / libcf varo = regrid2d(varci, gridco, method='bilinear', tool='libcf') plot2d(varo[0], title='LibCF / Bilinear', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - dstwgt c2c / vacumm varo = regrid2d(varci, gridco, method='dstwgt', tool='vacumm') plot2d(varo[0], title='VACUMM / Dstwgt', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - patch c2c / emsf varo = regrid2d(varci, gridco, method='patch', tool='esmf') plot2d(varo[0], title='ESMF / Patch', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - cellave r2r / regrid2 varo = regrid2d(varri, gridro, method='cellave', tool='regrid2') plot2d(varo[0], title='Regrid2 / Cellave', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridri, **kwg) # - cellave c2c / esmf varo = regrid2d(varci, gridco, method='cellave', tool='esmf') plot2d(varo[0], title='ESMF / Cellave', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - conserv c2c / esmf varo = regrid2d(varci, gridco, method='conserv', tool='esmf') plot2d(varo[0], title='ESMF / Conserv', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) P.tight_layout() P.savefig(code_file_name(ext='png')) rcdefaults() P.close()
npi = 50 from vcmq import P, savefigs, code_file_name from vacumm.misc.grid.kriging import (gridded_gauss3, random_gauss3, random_points, OrdinaryCloudKriger) # Generate random field xg, yg, zzg = gridded_gauss3() xi, yi, zi = random_gauss3(np=npi) # Setup kriger ock = OrdinaryCloudKriger(xi, yi, zi, n=0) # nugget = 0 # Interpolate to grid and get error xo, yo = P.meshgrid(xg[::4], yg[::4]) xo.shape = yo.shape = xo.size zo, zoe = ock(xo, yo, geterr=True) # Relative error zoemax = ock.variogram_func(P.inf) zoe /= zoemax zoe *= 100 # Variogram evolution rr = P.linspace(0, P.sqrt(xg.ptp()**2+yg.ptp()**2), 100) vv = ock.variogram_func(rr) # Plot P.figure(figsize=(8, 8)) axis = [xg.min(), xg.max(), yg.min(), yg.max()]
"""Test :class:`~vacumm.misc.color.to_grey` """ # Imports from vcmq import P, to_grey, code_file_name, plot_cmap cmap_name = "CMRmap" cmap_old = P.get_cmap(cmap_name) # Max cmap_10 = to_grey(cmap_old, 1) # Medium cmap_05 = to_grey(cmap_old, 0.5) # Min cmap_00 = to_grey(cmap_old, 0) # Plot fig = P.figure(figsize=(6, 2)) kw = dict(fig=fig, figsize=None, aspect=.15, show=False, close=False) P.subplot(221) plot_cmap(cmap_old, title='Original', **kw) P.subplot(222) plot_cmap(cmap_00, title='f = 0.0', **kw) P.subplot(223) plot_cmap(cmap_05, title='f = 0.5', **kw) P.subplot(224) plot_cmap(cmap_10, title='f = 1.0', **kw) P.tight_layout()
fill_value=1e20) N.random.seed(0) xo = N.random.uniform(lon0, lon1, np) yo = N.random.uniform(lat0, lat1, np) zo = N.random.uniform(dep0, dep1, np) to = comptime(N.random.uniform(reltime(time0, time.units).value, reltime(time1, time.units).value, np), time.units) # Rectangular xyzt with 1d z vo = grid2xy(vi, xo=xo, yo=yo, zo=zo, to=to, method='linear') von = grid2xy(vi, xo=xo, yo=yo, zo=zo, to=to, method='nearest') assert vo.shape==(ne, np) N.testing.assert_allclose(vo[0], yo) kwp = dict(vmin=vi.min(), vmax=vi.max()) P.figure(figsize=(6, 3)) P.subplot(121) P.scatter(xo, yo, c=vo[0], cmap='jet', **kwp) add_grid(vi.getGrid()) P.title('linear4d') P.subplot(122) P.scatter(xo, yo, c=von[0], cmap='jet', **kwp) add_grid(vi.getGrid()) P.title('nearest4d') P.figtext(.5, .98, 'grid2xy in 4D', va='top', ha='center', weight='bold') P.tight_layout() P.savefig(code_file_name(ext='.png')) P.close() # Reversed z and y vi_revz = vi[:, :, ::-1, ::-1, :]
nx = ny = 50 np = 500 mtype = 'gauss' distmax = 2.5 from vcmq import N, P, code_file_name, savefigs from vacumm.misc.grid.kriging import gridded_gauss3, random_gauss3, variogram, variogram_fit # Generate random field xxg, yyg, zzg = gridded_gauss3(nx=nx, ny=ny) x, y, z = random_gauss3(np=np) # Variogram from data d, v = variogram(x, y, z, distmax=distmax) # Variogram fit with null nugget vm = variogram_fit(x, y, z, mtype, n=0, distmax=distmax) D = N.linspace(0, d.max()) V = vm(D) # Compare P.figure(figsize=(6, 4)) P.title('Variogram') P.plot(d, v, 'ob', label='From data') P.plot(D, V, '-r', label='Fitted model (%s)' % mtype) P.legend(loc='best') P.ylim(ymin=0) savefigs(code_file_name(ext=False), pdf=True, verbose=False) P.close()
# Interpolate to random points xo, yo = random_points(np=npo) zo = krig(xi, yi, zi, xo, yo) # Plot # - source data axis = [xg.min(), xg.max(), yg.min(), yg.max()] kw = dict(vmin=zzg.min(), vmax=zzg.max()) kwim = dict(extent=axis, interpolation='bilinear', origin='lower', alpha=.2, **kw) kwsc = dict(lw=0.2, **kw) P.figure(figsize=(6, 3.5)) P.subplot(121) P.title('Source field') P.imshow(zzg, **kwim) P.scatter(xi, yi, c=zi, **kwsc) P.axis(axis) # - interpolated data P.subplot(122) P.title('Interpolated points') P.imshow(zzg, **kwim) P.scatter(xo, yo, c=zo, marker='s', s=30, **kwsc) P.axis(axis) P.tight_layout() savefigs(code_file_name(), verbose=False) P.close()
taxi.toRelativeTime("hours since 2000") ctimesi = taxi.asComponentTime() ct0 = round_date(ctimesi[0], "hour") ct1 = round_date(ctimesi[-1], "hour") taxo = create_time(lindates(ct0, ct1, 1, "hour"), taxi.units) # Lag error # - estimation els = [] lags = N.arange(1, 6) for lag in lags: els.append(N.sqrt(((sp[lag:] - sp[:-lag]) ** 2).mean())) els = N.array(els) a, b, _, _, _ = linregress(lags, els) # - plot P.figure(figsize=(6, 6)) P.subplot(211) P.plot(lags, els, "o") P.plot([0, lags[-1]], [b, a * lags[-1] + b], "g") P.axhline(b, color="0.8", ls="--") P.ylim(ymin=0) P.xlabel("Lag [hour]") P.ylabel("Error [m s-1]") add_key(1) P.title("Linear lag error model") # Interpolation sph, speh = regrid1d(sp, taxo, method="cellerr", erri=spe, errl=-a, geterr=True) # Time zoom for plot clarity tzoom = (ct1.sub(7, cdtime.Hour), ctimesi[-1])
zo = sck(xo, yo) zoe = scke(xo, yo) zzg = zo.reshape(ny, nx) zzge = zoe.reshape(ny, nx) # Plot vmin = min(zi.min(), zo.min(), zoe.min()) vmax = max(zi.max(), zo.max(), zoe.max()) vmax = max(abs(vmin), abs(vmax)) vmin = -vmax cmap = 'cmocean_tempo' cmap = 'cmocean_delta' kw = dict(vmin=vmin, vmax=vmax) P.figure(figsize=(6, 5.5)) ax = P.subplot(221) P.pcolormesh(xxg, yyg, zzg, cmap=cmap, **kw) P.colorbar() P.scatter(xi, yi, c=zi, s=100, cmap=cmap, **kw) P.title('Without obs error') P.subplot(222, sharex=ax, sharey=ax) P.pcolormesh(xxg, yyg, zzge, cmap=cmap, **kw) P.colorbar() P.scatter(xi, yi, c=zi, s=100, cmap=cmap, **kw) #P.axis('image') P.title('With obs error') P.subplot(223, sharex=ax, sharey=ax)
nxy = 15 xi = N.arange(nxy * 1.) yi = N.arange(nxy * 1.) xxi, yyi = N.meshgrid(xi, yi) zi = N.ma.array(yyi) zi[int(nxy * 0.3):int(nxy * 0.8), int(nxy * 0.3):int(nxy * 0.8)] = N.ma.masked zi.shape = 1, nxy, nxy # Output positions no = 1000 xo = N.random.uniform(-nxy / 4., nxy + nxy / 4., no) yo = N.random.uniform(-nxy / 4., nxy + nxy / 4., no) # Interpolate mv = zi.get_fill_value() zo = dstwgt2dto1d(xi, yi, zi.filled(mv), xo, yo, mv) zo = N.ma.masked_values(zo, mv) # Plot kw = dict(vmin=zi.min(), vmax=zi.max()) P.figure(figsize=(6, 6)) P.subplot(111, aspect=1) P.contourf(xxi, yyi, zi[0], **kw) add_grid((xi, yi), edges=False, centers=True, marker='o') P.scatter(xo, yo, c=zo[0], s=50, **kw) P.title('dstwgt2dto1d') figfile = code_file_name(ext='png') if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.close()
# Output grido = create_grid(xi[:]+2*2.5, yi[:]+3*1.5) xo = grido.getLongitude() yo = grido.getLatitude() xo.setBounds(bounds1d(xo)) yo.setBounds(bounds1d(yo)) xxob, yyob = meshbounds(xo, yo) # Regridding varo, wo = vari.regrid(grido, tool='regrid2', returnTuple=1) # Plot kw = dict(fill='pcolor', contour=False, xhide=True, yhide=True, xticks=[], yticks=[], cmap='jet', colorbar=False, show=False) P.figure(figsize=(6, 3)) p = plot2d(vari, subplot=131, title='Original', **kw) add_grid(gridi) add_grid(grido) P.axis('image') p = plot2d(varo, subplot=132, title='Regridded', **kw) add_grid(gridi) add_grid(grido) P.axis('image') P.subplot(133) P.pcolor(xxob, yyob, wo) add_grid(grido) P.title("Output weights") P.tight_layout() savefigs(code_file_name(),pdf=True, verbose=False) P.close()
taxi.toRelativeTime('hours since 2000') ctimesi = taxi.asComponentTime() ct0 = round_date(ctimesi[0], 'hour') ct1 = round_date(ctimesi[-1], 'hour') taxo = create_time(lindates(ct0, ct1, 1, 'hour'), taxi.units) # Lag error # - estimation els = [] lags = N.arange(1, 6) for lag in lags: els.append(N.sqrt(((sp[lag:] - sp[:-lag])**2).mean())) els = N.array(els) a, b, _, _, _ = linregress(lags, els) # - plot P.figure(figsize=(6, 6)) P.subplot(211) P.plot(lags, els, 'o') P.plot([0, lags[-1]], [b, a * lags[-1] + b], 'g') P.axhline(b, color='0.8', ls='--') P.ylim(ymin=0) P.xlabel('Lag [hour]') P.ylabel('Error [m s-1]') add_key(1) P.title('Linear lag error model') # Interpolation sph, speh = regrid1d(sp, taxo, method='cellerr', erri=spe,
print method # Regrillage ssto = regrid2d(ssti, grido, method=method) # -> CHANGEZ LA METHODE # -> UTILISEZ USECDR=TRUE # Regrilleur de CDAT regridder = CDATRegridder(gridi, grido, method='cellave') # -> CHANGEZ LA METHODE ssto2 = regridder.regrid(ssti) ssto3, cdr = regrid2d(ssti, grido, cdr=regridder, getcdr=True) # -> VERIFIEZ LE TYPE # Plots kwp = dict(vmin=ssti.min(), vmax=ssti.max(), res=None, show=False, colorbar=False, drawmeridians_linewidth=0, drawparallels_linewidth=0, grid=False, yhide='auto', **select) map2(ssti, title='Original',figsize=(15, 5), subplot=131, **kwp) add_grid(gridi, alpha=1) map2(ssto, title='Avec regrid2d', subplot=132, **kwp) add_grid(grido, alpha=1) add_grid(gridi, edges=False, centers=True, alpha=.5, markersize=3, marker='o') map2(ssto2, title='Avec CDATRegridder', subplot=133, **kwp) add_grid(grido, alpha=1) add_grid(gridi, edges=False, centers=True, alpha=.5, markersize=3, marker='o') P.tight_layout() P.show()
plot2d(varo, title='ESMF / Bilinear', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - bilin c2c / libcf varo = regrid2d(varci, gridco, method='bilinear', tool='libcf') plot2d(varo, title='LibCF / Bilinear', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - dstwgt c2c / vacumm varo = regrid2d(varci, gridco, method='dstwgt', tool='vacumm') plot2d(varo, title='VACUMM / Dstwgt', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - patch c2c / emsf varo = regrid2d(varci, gridco, method='patch', tool='esmf') plot2d(varo, title='ESMF / Patch', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - cellave r2r / regrid2 varo = regrid2d(varri, gridro, method='cellave', tool='regrid2') plot2d(varo, title='Regrid2 / Cellave', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridri, **kwg) # - cellave c2c / esmf varo = regrid2d(varci, gridco, method='cellave', tool='esmf') plot2d(varo, title='ESMF / Cellave', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) # - conserv c2c / esmf varo = regrid2d(varci, gridco, method='conserv', tool='esmf') plot2d(varo, title='ESMF / Conserv', subplot=(4,3,ip), **kw);ip+=1 add_grid(gridci, **kwg) P.tight_layout() P.savefig(code_file_name(ext='png')) rcdefaults() P.close()
continue if rank==0: print >>f, tool.upper(), method, ':', '%5.1f'%(time()-t0), 'seconds', psinfo() frac = diag['dstAreaFractions'] if frac is not None: mask = frac<=1.e-3 frac[mask] = 1. frac = N.resize(frac, varo.shape) mask = N.resize(mask, varo.shape) varo[:] /= frac varo[:] = MV2.masked_where(mask, varo, copy=0) # del r gc.collect() if rank==0: print >>f, ' plot' P.figure(figsize=(12, 6)) P.subplots_adjust(right=0.9) P.subplot(121) P.pcolormesh(xi, yi, vari[0,0].asma(),vmin=vmin,vmax=vmax) P.axis([xmin, xmax, ymin, ymax]) P.colorbar() P.title('Original') P.subplot(122) P.pcolormesh(xo, yo, varo[0,0].asma(),vmin=vmin,vmax=vmax) P.axis([xmin, xmax, ymin, ymax]) P.title(tool.upper()+' / '+method.upper()) P.colorbar(extend='min')#cax=P.axes([0.92, 0.3, 0.02, 0.6])) figfile = basefile+'_%(tool)s_%(method)s.png'%vars() if os.path.exists(figfile): os.remove(figfile) P.savefig(figfile) P.close()
yi = N.array(yi) zi = N.array(zi) xxg, yyg = N.meshgrid(xg, yg) xo = xxg.ravel() yo = yyg.ravel() vgm = variogram_model('linear', n=0, s=sill, r=range) # Setup the kriger sck = SimpleCloudKriger(xi, yi, zi, vgf=vgm, farvalue=farvalue) # Interpolate zo = sck(xo, yo) # Check a far value zzg = zo.reshape(ny, nx) N.testing.assert_allclose(zzg[-1, -1],farvalue) # Plot vmin = min(zi.min(), zo.min()) vmax = max(zi.max(), zo.max(), farvalue) cmap = 'cmocean_ice' kw = dict(vmin=vmin, vmax=vmax) P.pcolormesh(xxg, yyg, zzg, cmap=cmap, **kw) P.colorbar() P.scatter(xi, yi, c=zi, s=100, cmap=cmap, **kw) P.axis('image') P.title('Simple kriging with fixed far value') P.savefig(code_file_name(ext='.png')) P.show() P.close()
yi = N.random.uniform(ymin, ymax, 500) zi = N.ma.masked_array(get_values(xi, yi)) mask = (xi > (xmin + xmax) * .5) & (yi > (ymin + ymax) * .5) zi[mask] = 1e20 zi[mask] = N.ma.masked # - output xo = N.random.uniform(xmin, xmax, 500) yo = N.random.uniform(ymin, ymax, 500) zot = N.ma.masked_array(get_values(xo, yo)) mask = (xo > (xmin + xmax) * .5) & (yo > (ymin + ymax) * .5) zot[mask] = 1e20 zot[mask] = N.ma.masked # Call and plot kw = dict(vmin=zi.min(), vmax=zi.max()) P.figure(figsize=(8, 8)) P.subplot(221) trii = get_tri((xi, yi), ttype='mpl', mask=zi) P.tripcolor(trii, zi, **kw) cc = N.zeros(len(xi), '|S3') cc[:] = 'k' cc[zi.mask] = '.5' P.scatter(xi, yi, c=cc, s=7, marker='o') P.title('Input') for i, method in enumerate(['nearest', 'linear', 'cubic']): # Interp zo = xy2xy(xi, yi, zi, xo, yo, method=method) #[0] # Triangles trio = get_tri((xo, yo), ttype='mpl', mask=zo)
# Generate random gridded field xi, yi, zzi = gridded_gauss3(nx=nxi, ny=nyi) xxi, yyi = N.meshgrid(xi, yi) # Refined grid xo = N.linspace(xi[0], xi[-1], (nxi - 1) * r + 1) yo = N.linspace(yi[0], yi[-1], (nyi - 1) * r + 1) xxo, yyo = N.meshgrid(xo, yo) # Interpolate zzo = krig(xxi.ravel(), yyi.ravel(), zzi.ravel(), xxo.ravel(), yyo.ravel()) zzo.shape = xxo.shape # Section P.figure(figsize=(8, 4)) iyis = [3, 4] for iyi in iyis: label = iyi == iyis[0] P.plot(xi, zzi[iyi], 'ob-', markersize=8, label='Original' if label else None) P.plot(xo, zzo[iyi * r], 'or-', markersize=5, lw=.8, label='Interpolated' if label else None) P.legend(loc='best', framealpha=0.5)
# Regrilleur de CDAT regridder = CDATRegridder(gridi, grido, method="cellave") # -> CHANGEZ LA METHODE ssto2 = regridder.regrid(ssti) ssto3, cdr = regrid2d(ssti, grido, cdr=regridder, getcdr=True) # -> VERIFIEZ LE TYPE # Plots kwp = dict( vmin=ssti.min(), vmax=ssti.max(), res=None, show=False, colorbar=False, drawmeridians_linewidth=0, drawparallels_linewidth=0, grid=False, yhide="auto", **select ) map2(ssti, title="Original", figsize=(15, 5), subplot=131, **kwp) add_grid(gridi, alpha=1) map2(ssto, title="Avec regrid2d", subplot=132, **kwp) add_grid(grido, alpha=1) add_grid(gridi, edges=False, centers=True, alpha=0.5, markersize=3, marker="o") map2(ssto2, title="Avec CDATRegridder", subplot=133, **kwp) add_grid(grido, alpha=1) add_grid(gridi, edges=False, centers=True, alpha=0.5, markersize=3, marker="o") P.tight_layout() P.show()
vari[nx/3:2*nx/3, nyi/3:2*nyi/3] = N.ma.masked x = N.arange(nx) dyi = (yi[1]-yi[0])*0.49 dyo = (yo[1]-yo[0])*0.49 yyi = N.resize(yi, vari.shape)+N.random.uniform(-dyi, dyi, vari.shape) yyo = N.resize(yo, (nx, len(yo)))+N.random.uniform(-dyo, dyo, (nx, len(yo))) yyib, xxib = meshcells(yyi, x) yyob, xxob = meshcells(yyo, x) varon = N.ma.masked_values(interp1dxx(vari.filled(), yyi, yyo, mv, 0, extrap=0), mv) varol = N.ma.masked_values(interp1dxx(vari.filled(), yyi, yyo, mv, 1, extrap=0), mv) varoh = N.ma.masked_values(interp1dxx(vari.filled(), yyi, yyo, mv, 3, extrap=0), mv) kw = dict(vmin=vari.min(), vmax=vari.max()) axlims = [x[0], x[-1], yo[0], yo[-1]] P.figure(figsize=(8, 8)) P.subplot(221) P.pcolor(xxib, yyib, vari) P.axis(axlims) P.title('Original') P.subplot(222) P.pcolor(xxob, yyob, varon, **kw) P.axis(axlims) P.title('Nearest1dxx') P.subplot(223) P.pcolor(xxob, yyob, varol, **kw) P.axis(axlims) P.title('Linear1dxx') P.subplot(224) P.pcolor(xxob, yyob, varoh, **kw) P.axis(axlims)
dyo = (yo[1] - yo[0]) * 0.49 yyi = N.resize(yi, vari.shape) + N.random.uniform(-dyi, dyi, vari.shape) yyo = N.resize(yo, (nx, len(yo))) + N.random.uniform(-dyo, dyo, (nx, len(yo))) yyib, xxib = meshcells(yyi, x) yyob, xxob = meshcells(yyo, x) varon = N.ma.masked_values( interp1dxx(vari.filled(), yyi, yyo, mv, 0, extrap=0), mv) varol = N.ma.masked_values( interp1dxx(vari.filled(), yyi, yyo, mv, 1, extrap=0), mv) varoh = N.ma.masked_values( interp1dxx(vari.filled(), yyi, yyo, mv, 3, extrap=0), mv) kw = dict(vmin=vari.min(), vmax=vari.max()) axlims = [x[0], x[-1], yo[0], yo[-1]] P.figure(figsize=(8, 8)) P.subplot(221) P.pcolor(xxib, yyib, vari) P.axis(axlims) P.title('Original') P.subplot(222) P.pcolor(xxob, yyob, varon, **kw) P.axis(axlims) P.title('Nearest1dxx') P.subplot(223) P.pcolor(xxob, yyob, varol, **kw) P.axis(axlims) P.title('Linear1dxx') P.subplot(224) P.pcolor(xxob, yyob, varoh, **kw) P.axis(axlims)
# -*- coding: utf8 -*- # Read sea level at Brest from vcmq import cdms2, P, curve2, savefigs, data_sample f = cdms2.open(data_sample("tide.sealevel.BREST.mars.nc")) sea_level = f('sea_level') f.close() # Filtering from vacumm.tide.filters import demerliac cotes, tide = demerliac(sea_level, get_tide=True) # Plots kwplot = dict(date_fmt='%d/%m', show=False, date_rotation=0) # - tidal signal curve2(sea_level, 'k', subplot=211, label='Original', title='Sea level at Brest', **kwplot) curve2(tide, 'b', label='Tidal signal', **kwplot) P.legend().legendPatch.set_alpha(.7) # - surcotes/decotes curve2(cotes, 'r', subplot=212, hspace=.3, label='Demerliac', **kwplot) P.legend().legendPatch.set_alpha(.7) savefigs(__file__, savefigs_pdf=True) P.close()
def myplot(vari, depi, varol, varoc, depo, figfile): def getdv(var, dep): v = var[1, :, 1, :] if dep[:].ndim==var.ndim: dep = dep[1, :, 1, :] elif dep[:].ndim==3: dep = dep[:, 1, :] xb, yb = meshcells(v.getAxis(-1), dep) return xb, yb, v.asma() xbi, ybi, vi = getdv(vari, depi) xbo, ybo, vol = getdv(varol, depo) _, _, voc = getdv(varoc, depo) vmin, vmax = minmax(vi, vol, voc) kw = dict(vmin=vmin, vmax=vmax) P.figure(figsize=(10, 4)) ax = P.subplot(131) P.pcolormesh(xbi, ybi, vi, **kw) P.title('Original') P.subplot(132, sharex=ax, sharey=ax) P.pcolormesh(xbo, ybo, vol, **kw) P.title('Linear') P.subplot(133, sharex=ax, sharey=ax) P.pcolormesh(xbo, ybo, voc, **kw) P.ylim(ymin=min(ybi.min(), ybo.min()), ymax=max(ybi.max(), ybo.max())) P.title('Cellave') P.tight_layout() P.savefig(figfile)