rc('font', size=9) # Lecture des donnees f = cdms2.open(data_sample('wrf_2d.nc')) select = dict(lat=slice(4, -4), lon=slice(4, -4), squeeze=1) slp = f('pslvl', **select) rain = f('rain', **select) u = f('u10m', **select) v = f('v10m', **select) f.close() # Pression de surface slp[:] = generic2d(slp*0.01, 5) map2(slp, fill=False, contour=True, show=False, figsize=(6, 5.5), title='WRF Bretagne', fillcontinents=True, zorder=5, projection='merc', right=1, bottom=.07, lowhighs=True, lowhighs_smooth=9, lowhighs_zorder=5, fillcontinents_color='.95', lowhighs_color=(0, .5, 0), contour_colors=[(0, .5, 0)], drawcoastlines_linewidth=.6) # Pluie cmap_rain = cmap_custom([('0.9', 0), ('b', .8), ('r', 1.)]) rain[:] = MV2.masked_less(rain, 0.1) map2(rain, cmap=cmap_rain, vmin=0., fill='pcolor', fillcontinents=False, show=False, shadow_xoffset=4, shadow_yoffset=-4,shadow_width=4, colorbar_shrink=.7, alpha=.7, shadow=True, shadow_alpha=.3, contour=False, zorder=15) # Vent u[:] = ms2kt(u*5) v[:] = ms2kt(v*5) m = map2((u[::3, ::3], v[::3, ::3]), fill=False, contour=False, barbs=True, projection='merc',
# -*- coding: utf8 -*- # Lecture et masquage de Hs from vcmq import cdms2, MV2, data_sample, code_base_name f = cdms2.open(data_sample("swan.four.nc")) lon = f("longitude") lat = f("latitude") missing_value = f["HS"]._FillValue hs = f("HS", squeeze=1) f.close() hs[:] = cdms2.MV.masked_object(hs, missing_value, copy=0) # Trace sur grille irrégulière from vacumm.misc.plot import map2 map2( hs, xaxis=lon, yaxis=lat, figsize=(6, 4), long_name="Significant wave height", fill="pcolormesh", contour=False, savefigs=code_base_name(ext="png"), left=0.12, right=1, show=False, )
# Creer une carte se limitant a Ouessant avec fond de mer from vacumm.misc.plot import map2 from vacumm.misc.color import ocean, land from vcmq import code_base_name m = map2(lat=(48.41, 48.49), lon=(-5.15, -5), show=False, fillcontinents=False, drawcoastlines=False, figsize=(5.5, 4), bgcolor=ocean, left=.12, top=.9) # Fichier au 1/25000eme avec selection de la zone de la carte from vacumm.bathy.shorelines import Histolitt coast = Histolitt(m=m) # Chargement coast.plot(show=False) # Trace # On travail maintenant sur l'ile # - creation d'un polygone (voir le tutoriel (*@\ref{lst:misc.grid.polygons}@*)) from _geoslib import Polygon import numpy as N select = Polygon(N.array([[-5.1, 48.41], [-5, 48.41], \ [-5, 48.49], [-5.1, 48.49]])) # - recuperation de l'ile island = coast.greatest_polygon() # - sauvegarde de l'ile complete dans un fichier ascii f = N.savetxt('bathy.shorelines.dat', island.boundary) # - boucle sur les intersections import pylab as P for poly in island.intersection(select): xx, yy = poly.boundary.transpose() # coordonnees P.fill(xx, yy, alpha=.5, facecolor='g', linewidth=0) # coloriage # Fin du trace
from vacumm.diag.thermdyn import mixed_layer_depth from vacumm.misc.plot import map2 from vacumm.data.misc.sigma import NcSigma from vacumm.misc.grid import curv2rect # Read temperature print 'Read' ncfile = data_sample(ncfile) f = cdms2.open(ncfile) temp = curv2rect(f('TEMP'))(lon=lon, lat=lat, squeeze=1) # Compute depth print 'depth' s = NcSigma.factory(f) depth = curv2rect(s())(lon=lon, lat=lat, squeeze=1) f.close() # Compute MLD print 'mld' print temp.shape, depth.shape mld = mixed_layer_depth(temp, depth, mode='deltatemp', deltatemp=0.1) # Plot print 'plot' map2(mld, proj='merc', figsize=(6, 4), autoresize=0, fill='pcolormesh', contour=False, show=False, colorbar_shrink=0.7, right=1, savefigs=__file__, close=True) print 'Done'
def plot_mld_mod_on_pro(self, model, profiles, select=None, deep=False, **kwargs): '''Plot mixed layer depth of model data correspponding to profiles position :Params: - **deep**: deep water computation mode if true Other params, see: :func:`coloc_mod_on_pro` ''' self.verbose( 'Plotting MLD of colocalized %s on %s\nselect: %s\ndeep: %s\nkwargs: %s', model.__class__.__name__, profiles.__class__.__name__, select, deep, kwargs) # ===== # Lecture des donnees de stratification lons_mod, lats_mod, deps_mod, temp_mod, sal_mod, pres_mod, dens_mod = \ self.coloc_strat_mod_on_pro(model, profiles, select, **kwargs) # ===== # Calcul mld modele # MLD en eaux peu profondes if not deep: ddeps = meshweights(deps_mod, axis=0) # Densité min/max dmin = dens_mod.min(axis=0) dmax = dens_mod.max(axis=0) # Densité moyenne dmean = numpy.ma.average(dens_mod, axis=0, weights=ddeps) # Profondeur max (max+demi épaisseur) H = deps_mod[-1] + ddeps[-1] * .5 # MLD mld_mod = H * (dmax - dmean) / (dmax - dmin) # MLD en eaux profondes else: # Profondeur de référence dep = -10 # Axe pour interpolation from vacumm.misc.axes import create_dep depaxis = create_dep([dep]) # Interpolations dens_mod_ref = dens_mod_ref.reorder('-z') dens_mod_ref = regrid1dold( dens_mod, axo=depaxis, xmap=0, xmapper=deps_mod) # Required order: ...z dens_mod_ref = dens_mod_ref.reorder('z-') # Valeur du différentiel de densité (cf. de Boyer Montégut et all, 2003) delta_dens = 0.03 # Densité cible dens_mod_target = dens_mod_ref + 0.03 # Masques de la couche mélangée et des eaux profondes dens_mod_target3d = MV2.resize(dens_mod_target, dens_mod.shape) dens_mod_good = (dens_mod.asma() <= dens_mod_target3d.asma()).filled(False) dens_mod_bad = (dens_mod.asma() > dens_mod_target3d.asma()).filled(False) # Profondeurs juste au dessus et en dessous de la MLD deps_mod_above = MV2.masked_where(dens_mod_bad, deps_mod).min(axis=0) deps_mod_below = MV2.masked_where(dens_mod_good, deps_mod).max(axis=0) # Masques associés from vacumm.misc import closeto mask_above = closeto(deps_mod, MV2.resize(deps_mod_above, deps_mod.shape)) mask_below = closeto(deps_mod, MV2.resize(deps_mod_below, deps_mod.shape)) # Densités juste au dessus et en dessous de la MLD dens_mod_above = MV2.masked_where(dens_mod, mask_above).max(axis=0) dens_mod_below = MV2.masked_where(dens_mod, mask_below).min(axis=0) # Interpolation dens_mod_delta = dens_mod_above - dens_mod_below deps_mod_mld = (dens_mod_target - dens_mod_above) * deps_mod_above deps_mod_mld += (dens_mod_below - dens_mod_target) * deps_mod_below deps_mod_mld = MV2.where(dens_mod_delta.mask, MV2.masked, deps_mod_mld / dens_mod_delta) mld_mod = deps_mod_mld # Finalize mld_mod = MV2.array(mld_mod) mld_mod.units = 'm' mld_mod.long_name = u'Profondeur de la couche de melange' mld_mod.setAxisList(lons_mod.getAxisList()) model.verbose('MLD: %s', mld_mod) # ===== # Calcul mld profiles mld_pro, lats_pro, lons_pro = profiles.get_mld(select) profiles.verbose('MLD: %s', mld_pro) # ===== # Tracés vmin = mld_pro.min() vmax = mld_pro.max() if mld_mod.count(): vmin = min(mld_mod.min(), vmin) vmax = max(mld_mod.max(), vmax) else: self.warning('No model data') if 'latitude' in select: lat_min, lat_max = select['latitude'][:2] else: la = model.get_latitude() lat_min, lat_max = min(la), max(la) if 'longitude' in select: lon_min, lon_max = select['longitude'][:2] else: lo = model.get_longitude() lon_min, lon_max = min(lo), max(lo) levels = auto_scale((vmin, vmax)) vmin = levels[0] vmax = levels[-1] # Création de la palette cmap = cmap_magic(levels) # On trace de champ du modèle moyené sur la période choisie m = map2(lon=(lon_min, lon_max), lat=(lat_min, lat_max), show=False) # On trace le modèle en fond # ===== msca = None try: msca = m.map.scatter(lons_mod, lats_mod, s=100, c=mld_mod, vmin=vmin, vmax=vmax, cmap=cmap, label='model') except: self.exception('Failed plotting model data') # ===== # Triangulation du modèle # import matplotlib.tri as tri # triang = tri.Triangulation(lons_mod, lats_mod) # # On trace le modèle en fond # mod = m.axes.tripcolor(triang, mld_mod, vmin=vmin, vmax=vmax, cmap=cmap) # ===== # On trace les observations avec des points plus petits psca = None try: psca = m.map.scatter(lons_pro, lats_pro, s=25, c=mld_pro, vmin=m.vmin, vmax=m.vmax, cmap=m.cmap, label='profiles') except: self.exception('Failed plotting profiles data') # Colorbar if msca is not None: colorbar(msca) elif psca is not None: colorbar(psca)
# - si None, valeurs limites internes (i.e xyz.xmin(), ...) # - margin : marge relative en unite de resolution # -> ici : ymax = 48.3 + xyz.resol()[1]*2 # Sauvegarde print 'Sauvegarde' prefix = __file__[:-2]+'up' xyz_up.save(prefix+'.xyz') # ascii xyz_up.save(prefix+'.nc') # netcdf/grd # Plots print 'Plots' # - init P.figure(figsize=(4.5, 8)) P.rc('font', size=8) P.subplots_adjust(top=.95, hspace=.25, left=.1, bottom=.05, right=.98) m = map2(lon=(xc-xr, xc+xr), lat=(yc-yr, yc+yr), proj='merc', subplot=311, autoresize=0, resolution='f', show=False, drawmeridians_rotation=45, ticklabel_size=9, xhide=True) kwplot = dict(vmin=xyz.get_zmin(False), vmax=xyz.get_zmax(False), m=m, show=False, colorbar=False) # - xyz xyz.plot(size=10, mode='both', masked_alpha=.1, **kwplot) # - interpole manuellement kwplot.update(autoresize=0, ticklabel_size=9) map2(gridded_manual, subplot=312, xhide=True, title='Sur grille manuelle', **kwplot) # - interpole auto map2(gridded_auto, subplot=313, title='Sur grille auto', savefigs=__file__, **kwplot) #P.show()
def plot_bathy(bathy, shadow=True, contour=True, shadow_stretch=1., shadow_shapiro=False, show=True, shadow_alpha=1., shadow_black=.3, white_deep=False, nmax=30,m=None, alpha=1., zmin=None, zmax=None, **kwargs): """Plot a bathymetry - *lon*: Longitude range. - *lat*: Latitude range. - *show*:Display the figure [default: True] - *pcolor*: Use pcolor instead of contour [default: False] - *contour*: Add line contours [default: True] - *shadow*:Plot south-west shadows instead of filled contours. - *nmax*: Max number of levels for contours [default: 30] - *white_deep*: Deep contours are white [default: False] - All other keyword are passed to :func:`~vacumm.misc.plot.map2` """ # Input bb = bathy if isinstance(bathy, GriddedBathy): bathy = bathy.bathy() if shadow: xxs = getattr(bb, '_xxs', None) yys = getattr(bb, '_yys', None) if xxs is None: lon2d = bb._lon2d lat2d = bb._lat2d elif shadow: xxs = yys = None lon2d,lat2d = meshgrid(get_axis(bathy, -1).getValue(),get_axis(bathy, -2).getValue()) # Masking if 'maxdep' in kwargs: zmin = -maxdep if 'maxalt' in kwargs: zmax = maxalt if zmin is not None: bathy[:] = MV2.masked_less(bathy, zmin) if zmax is not None: bathy[:] = MV2.masked_greater(bathy, zmax) # Default arguments for map if hasattr(bathy, 'long_name'): kwargs.setdefault('title',bathy.long_name) if 'cmap' not in kwargs: vmin, vmax = minmax(bathy) # print 'cmap topo', vmin, vmax kwargs['cmap'] = auto_cmap_topo((kwargs.get('vmin', vmin), kwargs.get('vmax', vmax))) # kwargs.setdefault('ticklabel_size','smaller') kwargs.setdefault('clabel_fontsize', 8) kwargs.setdefault('clabel_alpha',.7*alpha) kwargs.setdefault('clabel_glow_alpha', kwargs['clabel_alpha']) kwargs.setdefault('fill', 'contourf') kwargs['nmax'] = nmax kwargs['show'] = False kwargs['contour'] = contour if shadow: kwargs.setdefault('alpha',.5*alpha) kwargs.setdefault('projection', 'merc') kwargs.setdefault('fmt', BathyFormatter()) kwargs.setdefault('colorbar_format', BathyFormatter()) kwargs.setdefault('units', False) kwargs.setdefault('levels_mode','normal') kwargs.setdefault('bgcolor', '0.8') kwargs.setdefault('contour_linestyle', '-') savefig = kwargs.pop('savefig', None) kwsavefig = kwfilter(kwargs, 'savefig_') # White contour when dark if contour and white_deep: levels = auto_scale(bathy,nmax=nmax) colors = [] nlevel = len(levels) for i in range(nlevel): if i < old_div(nlevel,2): colors.append('w') else: colors.append('k') kwargs.setdefault('contour_colors',tuple(colors)) # Call to map m = map2(bathy, m=m, **kwargs) # Add shadow if shadow: # Filter data = MV.array(bathy,'f',fill_value=0.) if shadow_shapiro: data = shapiro2d(data,fast=True).shape # Gradient grd = deriv2d(data,direction=45.,fast=True,fill_value=0.).filled(0.) grdn = refine(grd, 3) grdn = norm_atan(grdn,stretch=shadow_stretch).clip(0,1.) ; del grd # Grid # im = m.map.imshow(grdn,cmap=P.get_cmap('gist_yarg'),alpha=1) # gist_yarg , YlGnBu if xxs is None or yys is None: xx, yy = m(lon2d,lat2d) xxr = refine(xx, 3) yyr = refine(yy, 3) xxs, yys = meshbounds(xxr, yyr) if isinstance(bb, GriddedBathy): bb._xxs = xxs bb._yys = yys del xx, yy, xxr, yyr # Cmap cmap = cmap_custom(( ((1, )*3, 0), ((shadow_black, )*3, 1) )) # Plot pp = m.map.pcolormesh(xxs, yys, grdn,cmap=cmap)#P.get_cmap('gist_yarg')) pp.set_zorder(.9) pp.set_linewidth(0) pp.set_alpha(shadow_alpha*N.clip(alpha*2, 0, 1)) del grdn # Show it? if savefig: m.savefig(savefig, **kwsavefig) if show: P.show() return m
def plot_ped_mod_on_pro(self, model, profiles, select=None, **kwargs): '''Plot potential energy deficit of model data correspponding to profiles position :Params: See: :func:`coloc_mod_on_pro` ''' self.verbose('Plotting PED of colocalized %s on %s\nselect: %s\nkwargs: %s', model.__class__.__name__, profiles.__class__.__name__, select, kwargs) # ===== # Lecture des donnees de stratification lons_mod, lats_mod, deps_mod, temp_mod, sal_mod, pres_mod, dens_mod = \ self.coloc_strat_mod_on_pro(model, profiles, select, **kwargs) # ===== # Calcul ped modele ddeps = meshweights(deps_mod, axis=0) # Densité moyenne dmean = MV2.average(dens_mod, axis=0, weights=ddeps) # Anomalie de densité danom = dens_mod-dmean # Énergie potentielle disponible ape = danom * g ape *= ddeps # Deficit ped_mod = MV2.average(ape, axis=0, weights=ddeps) ped_mod.units = 'J.m^{-2}' ped_mod.long_name = u"Definit d'energie potentielle" ped_mod.setAxisList(lons_mod.getAxisList()) model.verbose('PED: %s', ped_mod) # ===== # Calcul ped profiles ped_pro, lats_pro, lons_pro = profiles.get_ped(select) profiles.verbose('PED: %s', ped_pro) # ===== # Tracés vmin = ped_pro.min() vmax = ped_pro.max() if ped_mod.count(): vmin = min(ped_mod.min(), vmin) vmax = max(ped_mod.max(), vmax) else: self.warning('No model data') if 'latitude' in select: lat_min, lat_max = select['latitude'][:2] else: la = model.get_latitude() lat_min, lat_max = min(la), max(la) if 'longitude' in select: lon_min, lon_max = select['longitude'][:2] else: lo = model.get_longitude() lon_min, lon_max = min(lo), max(lo) levels = auto_scale((vmin, vmax)) vmin = levels[0] vmax = levels[-1] # Création de la palette cmap = cmap_magic(levels) # On trace de champ du modèle moyené sur la période choisie m = map2(lon=(lon_min, lon_max), lat=(lat_min, lat_max), show=False) # On trace le modèle en fond msca = None try: msca = m.map.scatter(lons_mod, lats_mod, s=100, c=ped_mod, vmin=vmin, vmax=vmax, cmap=cmap, label='model') except: self.exception('Failed plotting model data') # On trace les observations avec des points plus petits psca = None try: psca = m.map.scatter(lons_pro, lats_pro, s=25, c=ped_pro, vmin=m.vmin, vmax=m.vmax, cmap=m.cmap, label='profiles') except: self.exception('Failed plotting profiles data') # Colorbar if msca is not None: colorbar(msca) elif psca is not None: colorbar(psca)
xres, yres = resol(gg, proj=True) xres /= 1000. yres /= 1000. print 'Zonal resolution : %g° / %gkm'%(lonres, xres) print 'Meridional resolution: %g° / %gkm'%(latres, yres) # Plot if options.plot or options.out: xmin, ymin, xmax, ymax = scalebox(grid, 1/options.zoom) for att in 'xmin', 'xmax', 'ymin', 'ymax': if getattr(options, att) is not None: exec att+" = %s"%getattr(options, att) if options.figsize is not None: try: options.figsize = eval(options.figsize) if not isinstance(options.figsize, tuple): options.figsize = options.figsize, options.figsize except: options.figsize = None if options.proj.lower() == 'none': options.proj = None m = map2(lon=(xmin, xmax), lat=(ymin, ymax), show=False, res=options.shoreline, title='Grid from '+os.path.basename(ncfile), figsize=options.figsize, proj = options.proj) add_grid(grid, m=m, centers=True, borders=True, color='b', markersize=5) m.legend(zorder=200, alpha=.7, title='Grid: %ix%i'%grid.shape[::-1]) if options.out: m.savefig(options.out) print 'Plot saved to '+ options.out if options.plot: m.show() f.close()
def plot_mld_mod_on_pro(self, model, profiles, select=None, deep=False, **kwargs): '''Plot mixed layer depth of model data correspponding to profiles position :Params: - **deep**: deep water computation mode if true Other params, see: :func:`coloc_mod_on_pro` ''' self.verbose('Plotting MLD of colocalized %s on %s\nselect: %s\ndeep: %s\nkwargs: %s', model.__class__.__name__, profiles.__class__.__name__, select, deep, kwargs) # ===== # Lecture des donnees de stratification lons_mod, lats_mod, deps_mod, temp_mod, sal_mod, pres_mod, dens_mod = \ self.coloc_strat_mod_on_pro(model, profiles, select, **kwargs) # ===== # Calcul mld modele # MLD en eaux peu profondes if not deep: ddeps = meshweights(deps_mod, axis=0) # Densité min/max dmin = dens_mod.min(axis=0) dmax = dens_mod.max(axis=0) # Densité moyenne dmean = numpy.ma.average(dens_mod, axis=0, weights=ddeps) # Profondeur max (max+demi épaisseur) H = deps_mod[-1]+ddeps[-1]*.5 # MLD mld_mod = H*(dmax-dmean)/(dmax-dmin) # MLD en eaux profondes else: # Profondeur de référence dep = -10 # Axe pour interpolation from vacumm.misc.axes import create_dep depaxis = create_dep([dep]) # Interpolations dens_mod_ref = dens_mod_ref.reorder('-z') dens_mod_ref = regrid1dold(dens_mod, axo=depaxis, xmap=0, xmapper=deps_mod) # Required order: ...z dens_mod_ref = dens_mod_ref.reorder('z-') # Valeur du différentiel de densité (cf. de Boyer Montégut et all, 2003) delta_dens = 0.03 # Densité cible dens_mod_target = dens_mod_ref+0.03 # Masques de la couche mélangée et des eaux profondes dens_mod_target3d = MV2.resize(dens_mod_target, dens_mod.shape) dens_mod_good = (dens_mod.asma() <= dens_mod_target3d.asma()).filled(False) dens_mod_bad = (dens_mod.asma() > dens_mod_target3d.asma()).filled(False) # Profondeurs juste au dessus et en dessous de la MLD deps_mod_above = MV2.masked_where(dens_mod_bad, deps_mod).min(axis=0) deps_mod_below = MV2.masked_where(dens_mod_good, deps_mod).max(axis=0) # Masques associés from vacumm.misc import closeto mask_above = closeto(deps_mod, MV2.resize(deps_mod_above, deps_mod.shape)) mask_below = closeto(deps_mod, MV2.resize(deps_mod_below, deps_mod.shape)) # Densités juste au dessus et en dessous de la MLD dens_mod_above = MV2.masked_where(dens_mod, mask_above).max(axis=0) dens_mod_below = MV2.masked_where(dens_mod, mask_below).min(axis=0) # Interpolation dens_mod_delta = dens_mod_above-dens_mod_below deps_mod_mld = (dens_mod_target-dens_mod_above)*deps_mod_above deps_mod_mld += (dens_mod_below-dens_mod_target)*deps_mod_below deps_mod_mld = MV2.where(dens_mod_delta.mask, MV2.masked, deps_mod_mld/dens_mod_delta) mld_mod = deps_mod_mld # Finalize mld_mod = MV2.array(mld_mod) mld_mod.units = 'm' mld_mod.long_name = u'Profondeur de la couche de melange' mld_mod.setAxisList(lons_mod.getAxisList()) model.verbose('MLD: %s', mld_mod) # ===== # Calcul mld profiles mld_pro, lats_pro, lons_pro = profiles.get_mld(select) profiles.verbose('MLD: %s', mld_pro) # ===== # Tracés vmin = mld_pro.min() vmax = mld_pro.max() if mld_mod.count(): vmin = min(mld_mod.min(), vmin) vmax = max(mld_mod.max(), vmax) else: self.warning('No model data') if 'latitude' in select: lat_min, lat_max = select['latitude'][:2] else: la = model.get_latitude() lat_min, lat_max = min(la), max(la) if 'longitude' in select: lon_min, lon_max = select['longitude'][:2] else: lo = model.get_longitude() lon_min, lon_max = min(lo), max(lo) levels = auto_scale((vmin, vmax)) vmin = levels[0] vmax = levels[-1] # Création de la palette cmap = cmap_magic(levels) # On trace de champ du modèle moyené sur la période choisie m = map2(lon=(lon_min, lon_max), lat=(lat_min, lat_max), show=False) # On trace le modèle en fond # ===== msca = None try: msca = m.map.scatter(lons_mod, lats_mod, s=100, c=mld_mod, vmin=vmin, vmax=vmax, cmap=cmap, label='model') except: self.exception('Failed plotting model data') # ===== # Triangulation du modèle # import matplotlib.tri as tri # triang = tri.Triangulation(lons_mod, lats_mod) # # On trace le modèle en fond # mod = m.axes.tripcolor(triang, mld_mod, vmin=vmin, vmax=vmax, cmap=cmap) # ===== # On trace les observations avec des points plus petits psca = None try: psca = m.map.scatter(lons_pro, lats_pro, s=25, c=mld_pro, vmin=m.vmin, vmax=m.vmax, cmap=m.cmap, label='profiles') except: self.exception('Failed plotting profiles data') # Colorbar if msca is not None: colorbar(msca) elif psca is not None: colorbar(psca)
def plot_layer_mod_on_pro(self, model, profiles, varname, depth, select=None, **kwargs): '''Get a layer of variable for a specified depth. :Params: - **varname**: variable to process - **depth**: output depth(s) Other params, see: :func:`coloc_mod_on_pro` ''' self.verbose('Plotting layer of colocalized %s on %s\nvarname: %s\ndepth: %s\nselect: %s\nkwargs: %s', model.__class__.__name__, profiles.__class__.__name__, varname, depth, select, kwargs) lons_mod, lats_mod, deps_mod, var_mod = \ self.coloc_mod_on_pro( model, profiles, # If varname is a list of possible names, wrap it into a # tuple of one element as we are requiring only one variable len(numpy.shape(varname)) and (varname,) or varname, select, **kwargs) odep = create_dep(is_iterable(depth) and depth or [depth]) var_mod = var_mod.reorder('-z') var_mod = interp1d(var_mod, axo=odep, xmap=0, xmapper=deps_mod) # Required order: ...z var_mod = var_mod.reorder('z-') model.verbose('layer: %s', var_mod) lons_pro, lats_pro, var_pro = profiles.get_layer(varname, depth, select=select) profiles.verbose('layer: %s', var_pro) # ===== # Tracés vmin = var_pro.min() vmax = var_pro.max() if var_mod.count(): vmin = min(var_mod.min(), vmin) vmax = max(var_mod.max(), vmax) else: self.warning('No model data') if 'latitude' in select: lat_min, lat_max = select['latitude'][:2] else: la = model.get_latitude() lat_min, lat_max = min(la), max(la) if 'longitude' in select: lon_min, lon_max = select['longitude'][:2] else: lo = model.get_longitude() lon_min, lon_max = min(lo), max(lo) levels = auto_scale((vmin, vmax)) vmin = levels[0] vmax = levels[-1] # Création de la palette cmap = cmap_magic(levels) # On trace de champ du modèle moyené sur la période choisie m = map2(lon=(lon_min, lon_max), lat=(lat_min, lat_max), show=False) # On trace le modèle en fond # ===== msca = None try: msca = m.map.scatter(lons_mod, lats_mod, s=100, c=var_mod, vmin=vmin, vmax=vmax, cmap=cmap, label='model') except: self.exception('Failed plotting model data') # ===== # Triangulation du modèle # import matplotlib.tri as tri # triang = tri.Triangulation(lons_mod, lats_mod) # # On trace le modèle en fond # mod = m.axes.tripcolor(triang, var_mod, vmin=vmin, vmax=vmax, cmap=cmap) # ===== # On trace les observations avec des points plus petits psca = None try: psca = m.map.scatter(lons_pro, lats_pro, s=25, c=var_pro, vmin=m.vmin, vmax=m.vmax, cmap=m.cmap, label='profiles') except: self.exception('Failed plotting profile data') # Colorbar if msca is not None: colorbar(msca) elif psca is not None: colorbar(psca)
# Rotation de la grid from vacumm.misc.grid import rotate_grid import numpy as N cgrido = rotate_grid(hs.getGrid(), -30) print 'Regrillage' from vacumm.misc.grid.regridding import regrid2d print ' - par SCRIP/conservative' hs_scripcons = regrid2d(hs, cgrido, 'conservative') print ' - par SCRIP/bilineaire' hs_scripbilin = regrid2d(hs, cgrido, 'bilinear') print 'Plots' from matplotlib import rcParams ; rcParams['font.size'] = 10 import pylab as P from vacumm.misc.plot import map2, savefigs, xhide, yhide, add_grid P.figure(figsize=(4, 7)) P.subplots_adjust(hspace=.28, bottom=.07, left=.08, right=.98) kwplot = dict(show=False, colorbar=False, vmin=hs.min(), vmax=hs.max(), drawparallels_size=8, drawmeridians_size=8, drawmeridians_rotation=45., xhide='auto', yhide='auto') m = map2(hs, title='Original', subplot=311, **kwplot) add_grid(cgrido, lw=.7, alpha=.3) map2(hs_scripcons, title='SCRIP : remapping', subplot=312, m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) map2(hs_scripbilin, title=u'SCRIP : bilinéaire', subplot=313, m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) savefigs(__file__)
# -*- coding: utf8 -*- from vacumm.misc.plot import map2 from vacumm.misc.color import cmap_rs, StepsNorm from vacumm.config import data_sample import cdms2 # Lecture f=cdms2.open(data_sample('mars3d.xy.nc')) sst = f('temp') f.close() # Spécifications # - niveaux levels = [10, 12, 12.5, 13., 13.25] # - normalisation norm = StepsNorm(levels) # - palette avec une couleur entre chaque niveau cmap = cmap_rs(['b', 'c', 'g', 'r'], lstretch=-.3) # Carte avec extension de la colorbar vers les max map2(sst, vmin=0., vmax=1.5, cmap=cmap, levels=levels, norm=norm, # in fact, StepsNorm is used by defaults fill='pcolor', clabel_glow=True, colorbar_shrink=.8, xymasked=False, colorbar_boundaries=levels+[levels[-1]], colorbar_extend='max', figsize=(5.5, 4.5), savefigs=__file__, show=False)
#!/bin/env python """Sample executable script using config""" # Init commandline parser import sys, os from argparse import ArgumentParser parser = ArgumentParser(description="Script to plot a 2D netcdf variable") parser.add_argument('ncfile', help='input netcdf file') # Configuration from vacumm.misc.config import cfgargparse cfg, args = cfgargparse('misc.config.argparse.ini', parser) print 'Current configuration:', cfg # Now use it # - load zoom lon = (cfg['zoom']['lon']['min'], cfg['zoom']['lon']['max']) lat = (cfg['zoom']['lat']['min'], cfg['zoom']['lat']['max']) # - read var import cdms2 f = cdms2.open(args.ncfile) var = f(cfg['var'], lon=lon, lat=lat, time=slice(0, 1)) f.close() # - plot from vacumm.misc.plot import map2 long_name = var.long_name map2(var, title=cfg['title']%locals(), savefigs=__file__, show=False)
P.figure(figsize=(6, 5)) P.subplots_adjust(top=.92, left=.03, bottom=.03, wspace=.05, hspace=.2) kwplot = dict(colorbar=False,cmap=C.cmap_linear([(.6, .8, 1), C.land]), \ contour=False,show=False,fillcontinents=False,fill='pcolor', drawmeridians=False, drawparallels=False, res='h', key=True, xymasked=False) # Mask using shoreline from vacumm.misc.grid.masking import polygon_mask from vacumm.misc.plot import map2 import MV2 as MV # - mask if central point sur terre (mode = 0 = 'inside') lon2, lat2 = N.meshgrid(lon, lat) mask0 = polygon_mask((lon2, lat2), 'h', mode=0, ocean=False) mask0 = MV.array(mask0, axes=[lat, lon]) mask0.long_name = "'inside'" map2(mask0, subplot=221, **kwplot) # - mask if cell more than 50% of land (mode = 1 = 'intersect') thresholds = .5 mask1 = polygon_mask((lon2, lat2), 'h', mode=1, thresholds=thresholds, ocean=False) mask1 = MV.array(mask1, axes=[lat, lon]) mask1.long_name = "'intersect': threshold=%g" % thresholds map2(mask1, subplot=222, **kwplot) # - mask if cell if more than 30% of land thresholds = .3 mask1 = polygon_mask((lon2, lat2), 'h', mode=1,
# Lecture f = cdms2.open(data_sample('mars3d.xy.nc')) sst = f('temp') f.close() # Spécifications # - niveaux levels = [10, 12, 12.5, 13., 13.25] # - normalisation norm = StepsNorm(levels) # - palette avec une couleur entre chaque niveau cmap = cmap_rs(['b', 'c', 'g', 'r'], lstretch=-.3) # Carte avec extension de la colorbar vers les max map2( sst, vmin=0., vmax=1.5, cmap=cmap, levels=levels, norm=norm, # in fact, StepsNorm is used by defaults fill='pcolor', clabel_glow=True, colorbar_shrink=.8, xymasked=False, colorbar_boundaries=levels + [levels[-1]], colorbar_extend='max', figsize=(5.5, 4.5), savefigs=__file__, show=False)
print 'Save' prefix = __file__[:-2] + 'up' xyz_up.save(prefix + '.xyz') # ascii xyz_up.save(prefix + '.nc') # netcdf/grd # %% Plots print 'Plots' # - init P.figure(figsize=(4.5, 8)) P.rc('font', size=8) P.subplots_adjust(top=.95, hspace=.25, left=.1, bottom=.05, right=.98) m = map2(lon=(xc - xr, xc + xr), lat=(yc - yr, yc + yr), proj='merc', subplot=311, autoresize=0, resolution='f', show=False, drawmeridians_rotation=45, ticklabel_size=9, xhide=True) kwplot = dict(vmin=xyz.get_zmin(False), vmax=xyz.get_zmax(False), m=m, show=False, colorbar=False) # - xyz xyz.plot(size=10, mode='both', masked_alpha=.1, **kwplot) # - manual interpolation kwplot.update(autoresize=0, ticklabel_size=9) map2(gridded_manual, subplot=312, xhide=True, title='On manual grid', **kwplot) # - auto interpolion
# Plot if options.plot or options.out: xmin, ymin, xmax, ymax = scalebox(grid, 1 / options.zoom) for att in 'xmin', 'xmax', 'ymin', 'ymax': if getattr(options, att) is not None: exec att + " = %s" % getattr(options, att) if options.figsize is not None: try: options.figsize = eval(options.figsize) if not isinstance(options.figsize, tuple): options.figsize = options.figsize, options.figsize except: options.figsize = None if options.proj.lower() == 'none': options.proj = None m = map2(lon=(xmin, xmax), lat=(ymin, ymax), show=False, res=options.shoreline, title='Grid from ' + os.path.basename(ncfile), figsize=options.figsize, proj=options.proj) add_grid(grid, m=m, centers=True, borders=True, color='b', markersize=5) m.legend(zorder=200, alpha=.7, title='Grid: %ix%i' % grid.shape[::-1]) if options.out: m.savefig(options.out) print 'Plot saved to ' + options.out if options.plot: m.show() f.close()
def plot_layer_mod_on_pro(self, model, profiles, varname, depth, select=None, **kwargs): '''Get a layer of variable for a specified depth. :Params: - **varname**: variable to process - **depth**: output depth(s) Other params, see: :func:`coloc_mod_on_pro` ''' self.verbose( 'Plotting layer of colocalized %s on %s\nvarname: %s\ndepth: %s\nselect: %s\nkwargs: %s', model.__class__.__name__, profiles.__class__.__name__, varname, depth, select, kwargs) lons_mod, lats_mod, deps_mod, var_mod = \ self.coloc_mod_on_pro( model, profiles, # If varname is a list of possible names, wrap it into a # tuple of one element as we are requiring only one variable len(numpy.shape(varname)) and (varname,) or varname, select, **kwargs) odep = create_dep(is_iterable(depth) and depth or [depth]) var_mod = var_mod.reorder('-z') var_mod = interp1d(var_mod, axo=odep, xmap=0, xmapper=deps_mod) # Required order: ...z var_mod = var_mod.reorder('z-') model.verbose('layer: %s', var_mod) lons_pro, lats_pro, var_pro = profiles.get_layer(varname, depth, select=select) profiles.verbose('layer: %s', var_pro) # ===== # Tracés vmin = var_pro.min() vmax = var_pro.max() if var_mod.count(): vmin = min(var_mod.min(), vmin) vmax = max(var_mod.max(), vmax) else: self.warning('No model data') if 'latitude' in select: lat_min, lat_max = select['latitude'][:2] else: la = model.get_latitude() lat_min, lat_max = min(la), max(la) if 'longitude' in select: lon_min, lon_max = select['longitude'][:2] else: lo = model.get_longitude() lon_min, lon_max = min(lo), max(lo) levels = auto_scale((vmin, vmax)) vmin = levels[0] vmax = levels[-1] # Création de la palette cmap = cmap_magic(levels) # On trace de champ du modèle moyené sur la période choisie m = map2(lon=(lon_min, lon_max), lat=(lat_min, lat_max), show=False) # On trace le modèle en fond # ===== msca = None try: msca = m.map.scatter(lons_mod, lats_mod, s=100, c=var_mod, vmin=vmin, vmax=vmax, cmap=cmap, label='model') except: self.exception('Failed plotting model data') # ===== # Triangulation du modèle # import matplotlib.tri as tri # triang = tri.Triangulation(lons_mod, lats_mod) # # On trace le modèle en fond # mod = m.axes.tripcolor(triang, var_mod, vmin=vmin, vmax=vmax, cmap=cmap) # ===== # On trace les observations avec des points plus petits psca = None try: psca = m.map.scatter(lons_pro, lats_pro, s=25, c=var_pro, vmin=m.vmin, vmax=m.vmax, cmap=m.cmap, label='profiles') except: self.exception('Failed plotting profile data') # Colorbar if msca is not None: colorbar(msca) elif psca is not None: colorbar(psca)
# -*- coding: utf8 -*- # Lecture et masquage de Hs from vcmq import cdms2, MV2, data_sample, code_base_name f = cdms2.open(data_sample('swan.four.nc')) lon = f('longitude') lat = f('latitude') missing_value = f['HS']._FillValue hs = f('HS', squeeze=1) f.close() hs[:] = cdms2.MV.masked_object(hs, missing_value, copy=0) # Trace sur grille irrégulière from vacumm.misc.plot import map2 map2(hs, xaxis=lon, yaxis=lat, figsize=(6, 4), long_name='Significant wave height', fill='pcolormesh', contour=False, savefigs=code_base_name(ext='png'), left=.12, right=1, show=False)
def plot_ped_mod_on_pro(self, model, profiles, select=None, **kwargs): '''Plot potential energy deficit of model data correspponding to profiles position :Params: See: :func:`coloc_mod_on_pro` ''' self.verbose( 'Plotting PED of colocalized %s on %s\nselect: %s\nkwargs: %s', model.__class__.__name__, profiles.__class__.__name__, select, kwargs) # ===== # Lecture des donnees de stratification lons_mod, lats_mod, deps_mod, temp_mod, sal_mod, pres_mod, dens_mod = \ self.coloc_strat_mod_on_pro(model, profiles, select, **kwargs) # ===== # Calcul ped modele ddeps = meshweights(deps_mod, axis=0) # Densité moyenne dmean = MV2.average(dens_mod, axis=0, weights=ddeps) # Anomalie de densité danom = dens_mod - dmean # Énergie potentielle disponible ape = danom * g ape *= ddeps # Deficit ped_mod = MV2.average(ape, axis=0, weights=ddeps) ped_mod.units = 'J.m^{-2}' ped_mod.long_name = u"Definit d'energie potentielle" ped_mod.setAxisList(lons_mod.getAxisList()) model.verbose('PED: %s', ped_mod) # ===== # Calcul ped profiles ped_pro, lats_pro, lons_pro = profiles.get_ped(select) profiles.verbose('PED: %s', ped_pro) # ===== # Tracés vmin = ped_pro.min() vmax = ped_pro.max() if ped_mod.count(): vmin = min(ped_mod.min(), vmin) vmax = max(ped_mod.max(), vmax) else: self.warning('No model data') if 'latitude' in select: lat_min, lat_max = select['latitude'][:2] else: la = model.get_latitude() lat_min, lat_max = min(la), max(la) if 'longitude' in select: lon_min, lon_max = select['longitude'][:2] else: lo = model.get_longitude() lon_min, lon_max = min(lo), max(lo) levels = auto_scale((vmin, vmax)) vmin = levels[0] vmax = levels[-1] # Création de la palette cmap = cmap_magic(levels) # On trace de champ du modèle moyené sur la période choisie m = map2(lon=(lon_min, lon_max), lat=(lat_min, lat_max), show=False) # On trace le modèle en fond msca = None try: msca = m.map.scatter(lons_mod, lats_mod, s=100, c=ped_mod, vmin=vmin, vmax=vmax, cmap=cmap, label='model') except: self.exception('Failed plotting model data') # On trace les observations avec des points plus petits psca = None try: psca = m.map.scatter(lons_pro, lats_pro, s=25, c=ped_pro, vmin=m.vmin, vmax=m.vmax, cmap=m.cmap, label='profiles') except: self.exception('Failed plotting profiles data') # Colorbar if msca is not None: colorbar(msca) elif psca is not None: colorbar(psca)
from vacumm.misc.grid import rotate_grid import numpy as N cgrido = rotate_grid(hs.getGrid(), -30) print 'Regrillage' from vacumm.misc.grid.regridding import regrid2d print ' - par SCRIP/conservative' hs_scripcons = regrid2d(hs, cgrido, 'conservative') print ' - par SCRIP/bilineaire' hs_scripbilin = regrid2d(hs, cgrido, 'bilinear') print 'Plots' from matplotlib import rcParams ; rcParams['font.size'] = 10 import pylab as P from vacumm.misc.plot import map2, savefigs, xhide, yhide, add_grid P.figure(figsize=(4, 7)) P.subplots_adjust(hspace=.28, bottom=.07, left=.08, right=.98) kwplot = dict(show=False, colorbar=False, vmin=hs.min(), vmax=hs.max(), drawparallels_size=8, drawmeridians_size=8, drawmeridians_rotation=45., xhide='auto', yhide='auto') m = map2(hs, title='Original', subplot=311, **kwplot) add_grid(cgrido, lw=.7, alpha=.3) map2(hs_scripcons, title='SCRIP : remapping', subplot=312, m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) map2(hs_scripbilin, title=u'SCRIP : bilinéaire', subplot=313, m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) savefigs(__file__) P.close()
v = f('v', **zoom) f.close() for var in u, v: var[:] = cdms2.MV.masked_object(var, 0., copy=0) # %% Plot map2((u, v), title='Vitesses en surface', show=True, units='$m s^{-1}$', figsize=(6, 5.), linewidth=.5, quiver_alpha=1, quiver_samp=2, contour_colors='.5', clabel=True, quiver_units='dots', quiver_width=2, quiver_scale_units='dots', quiver_scale=2. / 40., quiverkey_value=2., nofill=True, left=.08, right=1., top=.9, proj='merc', quiver_norm=3, savefigs=__file__, savefigs_pdf=True, close=True)
cgrido = rotate_grid(hs.getGrid(), -30) print 'Regrillage' from vacumm.misc.grid.regridding import regrid2d print ' - par natgrid' hs_nat = regrid2d(hs, cgrido, 'nat') print ' - par SCRIP/conservative' hs_scripcons = regrid2d(hs, cgrido, 'conservative') print ' - par SCRIP/bilineaire' hs_scripbilin = regrid2d(hs, cgrido, 'bilinear') print 'Plots' from matplotlib import rcParams ; rcParams['font.size'] = 10 import pylab as P from vacumm.misc.plot import map2, savefigs, xhide, yhide, add_grid P.figure(figsize=(6.5, 5)) P.subplots_adjust(hspace=.28, bottom=.07, left=.08, right=.98) kwplot = dict(show=False, colorbar=False, vmin=hs.min(), vmax=hs.max(), drawparallels_size=8, drawmeridians_size=8, drawmeridians_rotation=45.) m = map2(hs, title='Original', subplot=221, xhide=1,**kwplot) add_grid(cgrido, lw=.7, alpha=.3) map2(hs_nat, title='Natgrid', subplot=222, xhide=1,yhide=1,m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) map2(hs_scripcons, title='SCRIP : remapping', subplot=223, m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) map2(hs_scripbilin, title=u'SCRIP : bilinéaire',subplot=224,yhide=1,m=m, **kwplot) add_grid(cgridi, lw=.7, alpha=.3) savefigs(__file__)
############################################################################ # Init commandline parser import os from argparse import ArgumentParser parser = ArgumentParser(description="Script to plot a 2D netcdf variable") parser.add_argument('ncfile', help='input netcdf file') # Configuration from vacumm.misc.config import cfgargparse cfg, args = cfgargparse('misc.config.argparse.ini', parser) print 'Current configuration:', cfg # Now use it # - load zoom lon = (cfg['zoom']['lon']['min'], cfg['zoom']['lon']['max']) lat = (cfg['zoom']['lat']['min'], cfg['zoom']['lat']['max']) # - read var import cdms2 f = cdms2.open(args.ncfile) var = f(cfg['var'], lon=lon, lat=lat, time=slice(0, 1)) f.close() # - plot from vacumm.misc.plot import map2 long_name = var.long_name map2(var, title=cfg['title'] % locals(), savefigs=code_file_name(), show=False, close=True)
# Lecture et masquage de la vitesse import cdms2 from vacumm.config import data_sample zoom = dict(lat=(48.3, 48.55), lon=(-5.2, -4.8)) f = cdms2.open(data_sample('mars3d.xy.nc')) u = f('u', **zoom) v = f('v', **zoom) f.close() for var in u, v: var[:]*100. var[:] = cdms2.MV.masked_object(var, 0., copy=0) # Trace des vecteurs from vacumm.misc.plot import map2 import pylab as P ; P.rc('font', size=9) map2((u, v), title='Vitesses en surface', show=False, units='$cm s^{-1}$', figsize=(6, 5.), quiver_alpha=.5, quiver_samp=2, quiver_scale=15, quiver_width=0.006, #quiver_headaxislength=2, quiverkey_value = 2., nofill=True, left=.08, right=1., top=.9, proj='merc', quiver_norm=1, savefigs=__file__, savefigs_pdf=True,)
from vacumm.diag.thermdyn import mixed_layer_depth from vacumm.misc.plot import map2 from vacumm.data.misc.sigma import NcSigma from vacumm.misc.grid import curv2rect # Read temperature print 'Read' ncfile = data_sample(ncfile) f = cdms2.open(ncfile) temp = curv2rect(f('TEMP'))(lon=lon, lat=lat, squeeze=1) # Compute depth print 'depth' s = NcSigma.factory(f) depth = curv2rect(s())(lon=lon, lat=lat, squeeze=1) f.close() # Compute MLD print 'mld' print temp.shape, depth.shape mld = mixed_layer_depth(temp, depth, mode='deltatemp', deltatemp=0.1) # Plot print 'plot' map2(mld, proj='merc', figsize=(6, 4), autoresize=0, fill='pcolormesh', contour=False, show=False, colorbar_shrink=0.7, right=1, savefigs=__file__) print 'Done'
P.figure(figsize=(6, 5)) P.subplots_adjust(top=.92,left=.03,bottom=.03,wspace=.05,hspace=.2) kwplot = dict(colorbar=False,cmap=C.cmap_linear([(.6, .8, 1), C.land]), \ contour=False,show=False,fillcontinents=False,fill='pcolor', drawmeridians=False, drawparallels=False, res='h', key=True, xymasked=False) # Mask using shoreline from vacumm.misc.grid.masking import polygon_mask from vacumm.misc.plot import map2 import MV2 as MV # - mask if central point sur terre (mode = 0 = 'inside') lon2,lat2 = N.meshgrid(lon,lat) mask0 = polygon_mask((lon2, lat2), 'h', mode=0, ocean=False) mask0 = MV.array(mask0, axes=[lat, lon]) mask0.long_name = "'inside'" map2(mask0, subplot=221, **kwplot) # - mask if cell more than 50% of land (mode = 1 = 'intersect') thresholds = .5 mask1 = polygon_mask((lon2, lat2), 'h', mode=1, thresholds=thresholds, ocean=False) mask1 = MV.array(mask1, axes=[lat, lon]) mask1.long_name = "'intersect': threshold=%g" %thresholds map2(mask1, subplot=222, **kwplot) # - mask if cell if more than 30% of land thresholds = .3 mask1 = polygon_mask((lon2, lat2), 'h', mode=1, thresholds=thresholds, ocean=False) mask1 = MV.array(mask1, axes=[lat, lon]) mask1.long_name = "'intersect': threshold=%g" %thresholds map2(mask1, subplot=223, **kwplot) # - mask if than 70% of land if shoreline intersects cell more than once thresholds = (.3, .7) mask1 = polygon_mask((lon2, lat2), 'h', mode=1, thresholds=thresholds, ocean=False)