def do_something(self): num, den = 0, 0 try: num / den except: self.exception('Division by 0 failed !\n%s', self.exception_trace()) self.info('The function emitting this message is: %s', self.func_name()) self.info('The stack trace of the function emitting this message is:\n%s', self.stack_trace()) t = create_time(['1900-01-01 00:00:00', '9999-12-31 23:59:59']) y = create_lat(range(-90, 90)) x = create_lon(range(-180, 180)) v = cdms2.createVariable(numpy.random.ranf((len(t), len(y), len(x))), axes=[t, y, x], id='data', long_name='random data') self.info('Time:\n%s', self.describe(t)) self.info('Latitude:\n%s', self.describe(y)) self.info('Longitude:\n%s', self.describe(x, stats=True)) self.info('Variable:\n%s', self.describe(v, stats=True))
lo = U.getLongitude() la = U.getLatitude() # Longitudes toute les 1 minute loi = np.arange(lo[0], lo[-1], 1. / 60.) # Latitudes toute les 1 minute lai = np.arange(la[0], la[-1], 1. / 60.) xo = cdms2.createAxis(loi) yo = cdms2.createAxis(lai) LONGITUDE = create_lon(loi, id='longitude', attributes=dict( long_name='Longitude of each location', standard_name='longitude', units='degrees_east', valid_min='-180.', valid_max='180.', axis='X')) LATITUDE = create_lat(lai, id='latitude', attributes=dict( long_name='Latitude of each location', standard_name='latitude', units='degrees_north', valid_min='-90.', valid_max='90.', axis='Y')) z = U.getLevel()
def read(self): """ Lecture des fichiers NetCDF de NAR SST """ import cdms2, sys, os, glob import numpy, MV2 import cdtime from vacumm.misc.axes import create_lon from vacumm.misc.grid import create_grid, set_grid from vacumm.misc.atime import create_time from vacumm.misc.phys.units import kel2degc # -- Dans le cas d'un NAR SST on lit la grille lon lat dans le fichier grid # -- Lecture de la grille znar = self.ZONE_NAR gridfile = "grid_%(znar)s.nc" % vars() f = cdms2.open(gridfile) la = f('latitude') lo = f('longitude') f.close() # -- Creation des axes longitude et latitude lat_axis = create_lon(la, id='latitude') lon_axis = create_lon(lo, id='longitude') # -- Creation de la grille grid = create_grid(lon_axis, lat_axis) # -- Creation d'un objet cdms nomme self.data et d'un tableau cumt pour les dates extraites des noms de fichiers self.data = () #Initialise un tuple # =============== ATTENTION ==================== # Initialiser self.data pour ne pas dupliquer en memoire !!!!!!!!! # ============================================ #cumt = [] # Initialise un array # -- Boucle sur les fichiers presents dans le WORKDIR #url_file_def="%(YYYY)s%(MM)s%(DD)s%(HH)s%(ext)s"%vars() #self.ctdeb # -- Ancienne methode #files = glob.glob(os.path.join(self.WORKDIR, '2*.nc')) #files.sort() # -- # -- Methode amelioree # Cree une liste files = [] # Cree la liste des fichiers correspondants a la periode consideree ctest = self.ctdeb while ctest <= self.ctfin: flnme_only = '%(#)04d%(##)02d%(###)02d*.nc' % { '#': ctest.year, '##': ctest.month, '###': ctest.day } files.extend(glob.glob(os.path.join(self.WORKDIR, flnme_only))) ctest = ctest.add(1, cdtime.Days) # -- for filename in files: # -- Lecture du fichier filename f = cdms2.open(filename) temp = f('sea_surface_temperature') # =============== ATTENTION ================================== # Verifier que temp utilise tout le temps le meme espace memoire ... voir du cote de cdms # ========================================================== f.close() # -- Extraction de la date et heure du nom du fichier #ty = numpy.int(filename[-15:-11]) #tm = numpy.int(filename[-11:-9]) #tj = numpy.int(filename[-9:-7]) #th = numpy.int(filename[-7:-5]) #tt = cdtime.comptime(ty,tm,tj,th) #cumt.append(tt) # -- Transfert de temp dans l'objet cdat self.data (concatenation) # =============== ATTENTION ==================== # Faire une variable intermediaire qui sera au prealable allouee en memoire pour eviter # trop de copies en memoire !!!!!!!!!!!!!!!! # ============================================ self.data += temp, # -- Creation de l'axe temporel #taxis = create_time(cumt) # -- MV2.concatenate pour concatener les informations dans self.data (entre autre construit l'axe temporel) self.data = MV2.concatenate(self.data) # -- Attribution de la grille a l'objet self.data set_grid(self.data, grid, axes=True) # -- Informations sur le dataset self.data.name = "NAR_SST" self.data.units = "degree_Celsius" self.data.standard_name = "satellite_sea_surface_temperature" self.data.long_name = "Satellite Sea Surface Temperature - NAR" # -- Change unit self.data = kel2degc(self.data)
b = NcGriddedBathy(lon=lon, lat=lat, name=options.name, cfgfile=options.cfgfile, varname=options.varname, lonname=options.lonname, latname=options.latname, imargin=2, jmargin=2, maxvalue=None, reverse=options.reverse) # Interpolate on section bathy = b.bathy() lons, lats, xx, yy = transect_specs(bathy.getGrid(), options.x0, options.y0, options.x1, options.y1, getxy=True) tbathy = grid2xy(bathy, lons, lats) if not isinstance(options.along, basestring) or options.along not in ['lon', 'lat', 'm', 'km', 'dist', 'auto']: options.along = 'auto' if options.along=='auto': options.along = 'lon' if xx.max()-xx.min() > yy.max()-yy.min() else 'lat' if options.along=='lon': taxis = create_lon(lons) elif options.along=='lat': taxis = create_lat(lats) else: xy = N.sqrt((xx-xx[0])**2+(yy-yy[0])**2) if xy.max()-xy.min()>2500 or options.along=='km': units = 'km' xy *= 1e-3 else: units = 'm' taxis = cdms2.createAxis(xy) taxis.units = units taxis.long_name = 'Distance' tbathy.setAxis(0, taxis) # Plot
# Grid (15x15) nx, ny = 15, 10 import numpy as N from vacumm.misc.axes import create_lon, create_lat lon = create_lon(N.linspace(-5.2, -4.4, nx)) lat = create_lat(N.linspace(48, 48.6, ny)) # Plot params import pylab as P import vacumm.misc.color as C 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,
lons, lats, xx, yy = transect_specs(bathy.getGrid(), options.x0, options.y0, options.x1, options.y1, getxy=True) tbathy = grid2xy(bathy, lons, lats) if not isinstance(options.along, basestring) or options.along not in [ 'lon', 'lat', 'm', 'km', 'dist', 'auto' ]: options.along = 'auto' if options.along == 'auto': options.along = 'lon' if xx.max() - xx.min() > yy.max() - yy.min( ) else 'lat' if options.along == 'lon': taxis = create_lon(lons) elif options.along == 'lat': taxis = create_lat(lats) else: xy = N.sqrt((xx - xx[0])**2 + (yy - yy[0])**2) if xy.max() - xy.min() > 2500 or options.along == 'km': units = 'km' xy *= 1e-3 else: units = 'm' taxis = cdms2.createAxis(xy) taxis.units = units taxis.long_name = 'Distance' tbathy.setAxis(0, taxis) # Plot
# print marr.mask # print marr print 'Array dimension :', marr.shape print 'Fill value: ',marr.fill_value # Back to numpy array ... nparr=marr.getValue() # print nparr # ---- A Cdms2 object = MV2 + Axes + Attributes ... print 10*'-'+' CDMS2 '+10*'-' # cdms2.createVariable() # Geographic axis creation # - longitude: changing 'lon' id to 'longitude' ax1 = create_lon(N.arange(10)-7.,id='longitude') # - latitude ax2 = create_lat(N.arange(15)*.5+44.) # ==> Practice: Create cdarr with depth/lat axes. - see doc Vacumm - # # - depth # ax1 = create_dep(N.linspace(-1000,0,10)) # # - latitude # ax2 = create_lat(N.arange(15)*.5+44.) # ==> Practice: Create cdarr with time/lat axes. - see doc Vacumm - # # - time # ax1 = create_time(N.arange(10.), # 'days since 2006-10-01',long_name='Mon axe de temps') # # - latitude
from vacumm.config import data_sample f =cdms2.open(data_sample('mars3d.x.uv.nc')) v = f('v', squeeze=1, lon=(-5.08, -4.88)) f.close() v = MV2.masked_values(v, 0.) v.long_name = 'Original' # On ajoute un peu de bruit v[:] += N.random.random(len(v)) # Creation des deux axes de longitudes from vacumm.misc.axes import create_lon lon = v.getLongitude().getValue() dlon = N.diff(lon).mean() # - basse résolution lon_lr = create_lon((lon.min()+dlon*.7, lon.max()+dlon, dlon*3.3)) # - haute résolution lon_hr = create_lon((lon.min()+dlon, lon.max()+dlon, dlon/3.3)) # - dict lons = dict(haute=lon_hr, basse=lon_lr) # Regrillages et plots from matplotlib import rcParams ; rcParams['font.size'] = 9 from vacumm.misc.grid.regridding import regrid1d from vacumm.misc.plot import curve2,savefigs, yscale ; import pylab as P P.figure(figsize=(5.5, 6)) kwplot = dict(show=False,vmin=v.min(),vmax=v.max(),alpha=.7) for ilh,resdst in enumerate(['basse', 'haute']): # Regrillage vlinear = regrid1d(v, lons[resdst], 'linear')
# -- Profondeurs d'interpolation lo = U.getLongitude() la = U.getLatitude() # Longitudes toute les 1 minute loi = np.arange(lo[0],lo[-1],1./60.) # Latitudes toute les 1 minute lai = np.arange(la[0],la[-1],1./60.) xo = cdms2.createAxis(loi) yo = cdms2.createAxis(lai) LONGITUDE = create_lon(loi, id='longitude', attributes=dict(long_name='Longitude of each location',standard_name='longitude',units='degrees_east',valid_min='-180.',valid_max='180.',axis='X')) LATITUDE = create_lat(lai, id='latitude', attributes=dict(long_name='Latitude of each location',standard_name='latitude',units='degrees_north',valid_min='-90.',valid_max='90.',axis='Y')) z = U.getLevel() DEPTH = create_dep(z,attributes=dict(long_name='sea water depth',standard_name='depth',units='m',valid_min='0.',valid_max='12000.')) #axes = [TIME,DEPTH,LATITUDE,LONGITUDE] axes = [DEPTH,LATITUDE,LONGITUDE] Uis=np.arange(U.getLevel().__len__()*yo.__len__()*xo.__len__()).reshape(U.getLevel().__len__(),yo.__len__(),xo.__len__()) Vis=np.arange(U.getLevel().__len__()*yo.__len__()*xo.__len__()).reshape(U.getLevel().__len__(),yo.__len__(),xo.__len__()) Uis = cdms2.createVariable(Uis, typecode='f',id='UZ', axes=axes, attributes=dict(long_name='3d zonal velocity',standard_name='eastward_sea_water_velocity',units='m.s-1',valid_min='-100.',valid_max='100.')) Vis = cdms2.createVariable(Vis, typecode='f',id='VZ', axes=axes, attributes=dict(long_name='3d meridional velocity',standard_name='northward_sea_water_velocity',units='m.s-1',valid_min='-100.',valid_max='100.'))
def read(self): """ Lecture des fichiers NetCDF de NAR SST """ import cdms2,sys,os, glob import numpy,MV2 import cdtime from vacumm.misc.axes import create_lon from vacumm.misc.grid import create_grid, set_grid from vacumm.misc.atime import create_time from vacumm.misc.phys.units import kel2degc # -- Dans le cas d'un NAR SST on lit la grille lon lat dans le fichier grid # -- Lecture de la grille znar=self.ZONE_NAR gridfile="grid_%(znar)s.nc"%vars() f=cdms2.open(gridfile) la = f('latitude') lo = f('longitude') f.close() # -- Creation des axes longitude et latitude lat_axis = create_lon(la,id='latitude') lon_axis = create_lon(lo,id='longitude') # -- Creation de la grille grid = create_grid(lon_axis, lat_axis) # -- Creation d'un objet cdms nomme self.data et d'un tableau cumt pour les dates extraites des noms de fichiers self.data = () #Initialise un tuple # =============== ATTENTION ==================== # Initialiser self.data pour ne pas dupliquer en memoire !!!!!!!!! # ============================================ #cumt = [] # Initialise un array # -- Boucle sur les fichiers presents dans le WORKDIR #url_file_def="%(YYYY)s%(MM)s%(DD)s%(HH)s%(ext)s"%vars() #self.ctdeb # -- Ancienne methode #files = glob.glob(os.path.join(self.WORKDIR, '2*.nc')) #files.sort() # -- # -- Methode amelioree # Cree une liste files = [] # Cree la liste des fichiers correspondants a la periode consideree ctest = self.ctdeb while ctest <= self.ctfin: flnme_only = '%(#)04d%(##)02d%(###)02d*.nc'%{'#':ctest.year, '##':ctest.month, '###':ctest.day} files.extend(glob.glob(os.path.join(self.WORKDIR, flnme_only))) ctest=ctest.add(1,cdtime.Days) # -- for filename in files: # -- Lecture du fichier filename f = cdms2.open(filename) temp = f('sea_surface_temperature') # =============== ATTENTION ================================== # Verifier que temp utilise tout le temps le meme espace memoire ... voir du cote de cdms # ========================================================== f.close() # -- Extraction de la date et heure du nom du fichier #ty = numpy.int(filename[-15:-11]) #tm = numpy.int(filename[-11:-9]) #tj = numpy.int(filename[-9:-7]) #th = numpy.int(filename[-7:-5]) #tt = cdtime.comptime(ty,tm,tj,th) #cumt.append(tt) # -- Transfert de temp dans l'objet cdat self.data (concatenation) # =============== ATTENTION ==================== # Faire une variable intermediaire qui sera au prealable allouee en memoire pour eviter # trop de copies en memoire !!!!!!!!!!!!!!!! # ============================================ self.data += temp, # -- Creation de l'axe temporel #taxis = create_time(cumt) # -- MV2.concatenate pour concatener les informations dans self.data (entre autre construit l'axe temporel) self.data = MV2.concatenate(self.data) # -- Attribution de la grille a l'objet self.data set_grid(self.data, grid, axes=True) # -- Informations sur le dataset self.data.name = "NAR_SST" self.data.units = "degree_Celsius" self.data.standard_name = "satellite_sea_surface_temperature" self.data.long_name = "Satellite Sea Surface Temperature - NAR" # -- Change unit self.data = kel2degc(self.data)
# Grid (15x15) nx, ny = 15, 10 import numpy as N from vacumm.misc.axes import create_lon, create_lat lon = create_lon(N.linspace(-5.2, -4.4, nx)) lat = create_lat(N.linspace(48, 48.6, ny)) # Plot params import pylab as P import vacumm.misc.color as C 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