# Lecture d'un fichier xyz et plot from vacumm.misc.io import XYZ from vacumm.config import data_sample xyz = XYZ(data_sample('celtic_sea.xyz')) # Verifs print len(xyz) # -> 23538 print xyz[0:3] # -> [(-5.93,52.97,25.0),(-5.90,52.97,41.0),(-5.85,52.97,33.0)] # Exclusion xyz.exclude([[-6., 52.], [-5.5, 52], [-5.5, 52.5], [-6., 52.5]]) # Modification print xyz.z.max() # -> 141.0 xyz *= -1 print xyz.z.max() # -> -141.0 # Plot import pylab as P P.figure(figsize=(5.5, 8)) P.subplots_adjust(left=.12, top=.96, right=1, bottom=.06) P.subplot(211) xyz.plot(title='Mer celtique', units='m', m=True, show=False, size=2, cmap='cmap_bathy') # Zoom xyz_zoom = xyz.clip((-6, 51.5, -4, 52.5), long_name='Zoom')
# Lecture des donnnees import cdms2, MV2, numpy as N from vacumm.config import data_sample select = dict(lon=(-5.3, -4.72), lat=(47.9, 48.8), time=slice(0, 24)) f = cdms2.open(data_sample("mars2d.xyt.nc")) v = MV2.masked_values(f("v", **select), 0.0, copy=False) f.close() # Diagonale lon = v.getLongitude() lat = v.getLatitude() nd = N.sqrt(len(lon) ** 2.0 + len(lat) ** 2) / 2.0 xo = N.linspace(lon[0], lon[-1], nd) yo = N.linspace(lat[0], lat[-1], nd) # Interpolation from vacumm.misc.grid.regridding import grid2xy vo = grid2xy(v, xo, yo, method="bilinear") # Plot # - variable interpolee from vacumm.misc.plot import hov2 as hov, savefigs, map2 as map hov(vo, cmap="jet", show=False, top=0.9, date_fmt="%H", colorbar_shrink=0.5, left=0.13) # - carte + diagonal import pylab as P m = map( v[0],
# from StringIO import StringIO import cdms2 as cdms from vacumm.misc.atime import strftime, ch_units, strptime import scipy.io as SC import matplotlib.pyplot as mp # Inits drifterfile = "drifter.txt" adcpfile = "adcp.txt" # ----------------------------------------------------------------------------------------------------------- # ---- Read an ASCII file ---- print 10*'-'+' ASCII file '+10*'-' # We load a cdms variable f = cdms.open(data_sample('mars3d.t.nc')) temp = f('temp') u = f('u') v = f('v') f.close() # We get the Time time = temp.getTime() # axis ctime = time.asComponentTime() # time cdtime.comptime() # Create the file with the format : YYYY/MM/DDZHH:MM TEMP U V f = open('misc.io.ascii.1.dat', 'w') f.write('# Ligne de commentaire\n') for it in xrange(len(temp)): t = strftime('%Y/%m/%dZ%H:%M', ctime[it]) f.write('%s %.4f %f %f\n' % (t, temp[it], u[it], v[it]))
# On recupere une variable cdms import cdms2 as cdms from vacumm.config import data_sample f = cdms.open(data_sample("mars3d.t.nc")) temp = f("temp") u = f("u") v = f("v") f.close() # On recupre le temps time = temp.getTime() # axe ctime = time.asComponentTime() # temps cdtime.comptime() # Creation a la main au format : YYYY/MM/DDZHH:MM TEMP U V from vacumm.misc.atime import strftime, ch_units, strptime f = open("misc.io.ascii.1.dat", "w") f.write("# Ligne de commentaire\n") for it in xrange(len(temp)): t = strftime("%Y/%m/%dZ%H:%M", ctime[it]) f.write("%s %.4f %f %f\n" % (t, temp[it], u[it], v[it])) f.close() # Verification rapide (deux premieres lignes) f = open("misc.io.ascii.1.dat") print "".join(f.readlines()[:3]) f.close() # -> # Ligne de commentaire # -> 2008/01/07Z00:00 12.0672 0.359631 0.156422 # -> 2008/01/07Z01:00 11.9421 0.493174 0.158244
# -*- coding: utf8 -*- # Lecture de la temperature import cdms2, MV2 from vacumm.config import data_sample from vcmq import code_base_name f = cdms2.open(data_sample('mars3d.xy.nc')) temp = f('temp', lon=(-5.5, -4), lat=(47, 49)) f.close() temp.long_name = 'Original' # On crée un trou temp[15:60, 40:80] = MV2.masked # On rempli des trous from vacumm.misc.grid.regridding import fill2d tempf = fill2d(temp, method='carg') tempf.long_name = 'Rempli' # On masque la terre from vacumm.misc.grid.masking import masked_polygon tempf[:] = masked_polygon(tempf, 'h', copy=0) # Plots from vacumm.misc.plot import map2 as map, P P.rc('font', size=9) kw = dict(vmin=9, vmax=13) map(temp, show=False, subplot=211, hspace=.2, bottom=.05,
import cdms2, MV2 from vacumm.misc.plot import map2 from vacumm.misc.color import cmap_custom from vacumm.misc.filters import generic2d from vacumm.misc.phys.units import ms2kt from vacumm.config import data_sample from matplotlib import rc 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,
# Un axe quelconque bad_axis = cdms2.createAxis([1], id="pipo") # Verification des types d'axes avec 'axis_type' # - affichage pour tous print " | ".join(["%s:%s" % (axis.id, axis_type(axis)) for axis in time_axis, lon_axis, lat_axis, dep_axis, bad_axis]) # -> time:t | other_time:t | longitude:x | lat:y | depth:z | pipo:- # - verification ponctuele print islon(lon_axis), islon(lat_axis), is_geo_axis(lat_axis) # -> True False False # Reformattage des axes pour deviner identifier # ceux geographiques (lon,lat,dep,time) # Le reformattage peut changer : id, units, long_name. # - un axe pourri mais avec 'long_name' explitcite time_axis2 = cdms2.createAxis([6], id="other_time") time_axis2.long_name = "Time" check_axis(time_axis2) print istime(time_axis2) # en fait, 'check_axis' appelle 'istime' # -> True # - une variable tiree d'un fichier (voir le tutoriel (*@\ref{lst:misc.io.netcdf}@*)) from vacumm.config import data_sample f = cdms2.open(data_sample("mars3d.xt.xe.nc")) var = f("xe", time=slice(0, 1), squeeze=1) f.close() check_axes(var) lon_axis = var.getAxis(0) print lon_axis.axis, islon(lon_axis) # -> X True
# -*- coding: utf8 -*- # Lecture d'une serie 1D de niveau de la mer du modele import cdms2 from vacumm.config import data_sample f = cdms2.open(data_sample('tide.sealevel.BREST.mars.nc')) sea_level = f('sea_level', ('2006-10-01', '2006-10-02'))[1::4] # Toutes les heures f.close() # Recuperation des pleines mers, basses mers et zeros from vacumm.tide.filters import extrema, zeros bm, pm = extrema(sea_level, spline=True, reference='mean') zz = zeros(sea_level, ref='mean') # Plots from vacumm.misc.plot import curve2 as curve curve(sea_level, 'ko', markersize=3, figsize=(6, 4), show=False) curve(zz, 'go', linewidth=0, show=False, xstrict=False) curve(pm, 'ro', linewidth=0, show=False, xstrict=False) curve(bm, 'bo', linewidth=0, xstrict=False, title="Niveau de la mer", savefigs=__file__, savefigs_pdf=True, show=False)
# -*- coding: utf8 -*- # Lecture des donnees from matplotlib import rc;rc('font', size=11) import cdms2, MV2 from vacumm.config import data_sample zone = dict(yc=slice(0, 40), xc=slice(10, 40)) f = cdms2.open(data_sample('swan.four.nc')) lon2d = f('longitude', **zone) lat2d = f('latitude', **zone) hs = MV2.masked_values(f('HS', squeeze=1, **zone), f['HS']._FillValue) dlon = float(f.longitude_resolution) dlat = float(f.latitude_resolution) f.close() # Affectation de la grille curvilineaire à la variable from vacumm.misc.grid import curv_grid, set_grid cgridi = curv_grid(lon2d, lat2d) hs = set_grid(hs, cgridi) # 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 natgrid' hs_nat = regrid2d(hs, cgrido, 'nat') print ' - par SCRIP/conservative' hs_scripcons = regrid2d(hs, cgrido, 'conservative')
'time': ('TIME', ), 'depth': ('DEPH', ), # Force using the DEPH variable as depth 'latitude': ('LATITUDE', ), 'longitude': ('LONGITUDE', ), 'temperature': ('TEMP', ), }, # The variable argument specify which variables will be used when using the load/save methods. # Do not specify time, depth, latitude and longitude as they # are special variables which are always required variables=('temperature', ), # We could also add a quality code filter: # qualities=(1,2) ) from vacumm.config import data_sample p.load(data_sample('data.misc.profile.nc')) ########## # 2) Save profiles into a file suitable for profiles.py, that can be loaded by ProfilesDataset ########## of = 'data.misc.profile.converted.nc' p.save(of) # We could also have specified the variables to write here: # p.save(of, variables=('temperature',)) ########## # 3) Load the previously converted file using ProfilesDataset, which is more restrictive, # it is expecting input file to have profile and level axis, time, latitude, longitude variables. ########## p = P.ProfilesDataset(of)
# -*- coding: utf8 -*- # Lecture des donnees from matplotlib import rc;rc('font', size=11) import cdms2, MV2 from vacumm.config import data_sample zone = dict(yc=slice(0, 40), xc=slice(10, 40)) f = cdms2.open(data_sample('swan.four.nc')) lon2d = f('longitude', **zone) lat2d = f('latitude', **zone) hs = MV2.masked_values(f('HS', squeeze=1, **zone), f['HS']._FillValue) dlon = float(f.longitude_resolution) dlat = float(f.latitude_resolution) f.close() # Affectation de la grille curvilineaire à la variable from vacumm.misc.grid import curv_grid, set_grid cgridi = curv_grid(lon2d, lat2d) hs = set_grid(hs, cgridi) # 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')
# *-* coding: utf-8 *-* # Lecture de la temperature import cdms2, MV2, numpy as N 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']):
# -*- coding: utf8 -*- # Lecture du niveau de la mer sur 9 pas de temps à une latitude import cdms2, MV2 from vacumm.config import data_sample f =cdms2.open(data_sample('mars3d.xt.xe.nc')) xe = f('xe', squeeze=1, time=slice(0, 9), lon=(-5, -4.83)) f.close() xe.long_name = 'Original' # On crée un trou xe[3:4, 20:30] = MV2.masked # Nouvel axe temporel plus précis from vacumm.misc.axes import create_time #old_time = xe.getTime() old_time=create_time((xe.shape[0], ), 'hours since 2000') xe.setAxis(0, old_time) dt = (old_time[1]-old_time[0])/10. new_time = create_time((old_time[0], old_time[-1]+dt, dt), old_time.units) # Interpolation from vacumm.misc.grid.regridding import interp1d # - nearest xe_nea = interp1d(xe, new_time, method='nearest') xe_nea.long_name = 'Nearest' # - linear xe_lin = interp1d(xe, new_time, method='linear') xe_lin.long_name = 'Linear' # - cubic xe_cub = interp1d(xe, new_time, method='cubic') xe_cub.long_name = 'Cubic'
from vacumm.misc.plot import section2 # Initialisation pour un compteur de temps de calcul print_time_format = "%a, %d %b %Y %H:%M:%S" t0 = time() time_format = "%Y%m%d" date = strftime(time_format) print "Begin : " + strftime(print_time_format) # Profondeurs sur lesquelles nous souhaitons interpoler (en m) depths = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20, 22,24,26,28,30,32,34,36,38,40,45,50,55,60,65,70,75,80,85,90,95,100,120,140,160]) depths = -depths[::-1] # croissantes et négatives # Lecture de la température f = cdms2.open(data_sample('mars3d.tsigyx.nc')) data_in = f('TEMP') # T-YX (- = level) # Détermination des profondeurs d'après les sigma # - détection auto de la classe de sigma d'après fichier sigma_class = NcSigma.factory(f) # - initialisation du convertisseur sigma_converter = sigma_class(copyaxes=True) # - lecture de eta (sans sélection de domaine) et calcul des profondeurs depths_in = sigma_converter().filled() f.close() # Creation de l'axe des profondeurs cibles depth_out = create_depth(depths) # Interpolation
# On recupere une variable cdms import cdms2 as cdms from vacumm.config import data_sample f = cdms.open(data_sample('mars3d.t.nc')) temp = f('temp') u = f('u') v = f('v') f.close() # On recupre le temps time = temp.getTime() # axe ctime = time.asComponentTime() # temps cdtime.comptime() # Creation a la main au format : YYYY/MM/DDZHH:MM TEMP U V from vacumm.misc.atime import strftime, ch_units, strptime f = open('misc.io.ascii.1.dat', 'w') f.write('# Ligne de commentaire\n') for it in xrange(len(temp)): t = strftime('%Y/%m/%dZ%H:%M', ctime[it]) f.write('%s %.4f %f %f\n' % (t, temp[it], u[it], v[it])) f.close() # Verification rapide (deux premieres lignes) f = open('misc.io.ascii.1.dat') print ''.join(f.readlines()[:3]) f.close() # -> # Ligne de commentaire # -> 2008/01/07Z00:00 12.0672 0.359631 0.156422 # -> 2008/01/07Z01:00 11.9421 0.493174 0.158244 # Ecriture rapide via numpy
# -*- coding: utf8 -*- import pylab as P # Création de bathymétries fictives à partir de Smith and Sandwell import cdms2 from vacumm.config import data_sample cdms2.axis.longitude_aliases.append('x') cdms2.axis.latitude_aliases.append('y') f = cdms2.open(data_sample('ETOPO2v2g_flt.grd')) # - large var_large = f('z', lon=(-7, -1), lat=(46, 49)) # - petite var_small = f('z', lon=(-4.5, -.5), lat=(44.5, 46.5)) f.close() # - regrillage de la large vers une grille moins fine from vacumm.misc.grid import regridding, resol, create_grid xr, yr = resol(var_large.getGrid()) grid_large = create_grid((-7., -1, xr * 4.5), (46., 49, yr * 4.5)) var_large = regridding.regrid2d(var_large, grid_large) # On ajoute un traît de côte pour le masquage from vacumm.bathy.bathy import GriddedBathy, GriddedBathyMerger bathy_large = GriddedBathy(var_large, shoreline='i') bathy_small = var_small # Création de la grille finale de résolution intermédiaire final_grid = create_grid((-6., .5, xr * 2.5), (45, 47., yr * 2.5)) # On crée maintenant le merger merger = GriddedBathyMerger(final_grid) # - ajout de la bathy basse resolution en premier (en dessous)
"""Basic stick plot""" from vacumm.config import data_sample from vacumm.misc.plot import stick2 # Read speed import cdms2 f = cdms2.open(data_sample('mars3d.t.nc')) u = f('u') v = f('v') f.close() # Plot stick2(u, v, title='Current in the Iroise Sea', units='m/s', bottom=.2, top=.85, quiver_headwidth=2, quiverkey_value=.5, quiver_width=0.002, quiver_scale=5., savefigs=__file__, figsize=(5.5, 3), show=False)
# Parameters ncfile = "menor.nc" lon=(3.,4.5) lat=(42, 42.8) # Imports import cdms2 from vacumm.config import data_sample 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
# -*- coding: utf8 -*- # Lecture d'une serie 1D de niveau de la mer du modele import cdms2 from vacumm.config import data_sample f = cdms2.open(data_sample('tide.sealevel.BREST.mars.nc')) sea_level = f('sea_level', ('2006-10-01', '2006-10-02'))[1::4] # Toutes les heures f.close() # Recuperation des pleines mers, basses mers et zeros from vacumm.tide.filters import extrema, zeros bm, pm = extrema(sea_level, spline=True, reference='mean') zz = zeros(sea_level, ref='mean') # Plots from vacumm.misc.plot import curve2 as curve curve(sea_level, 'ko', markersize=3, figsize=(6, 4), show=False) curve(zz, 'go', linewidth=0, show=False, xstrict=False) curve(pm, 'ro', linewidth=0, show=False, xstrict=False) curve(bm, 'bo', linewidth=0, xstrict=False, title="Niveau de la mer", savefigs=__file__, savefigs_pdf=True, show=False, close=True)
# -*- coding: utf8 -*- # Récupération d'une bathy sous la forme d'une variable cdat import cdms2 cdms2.axis.latitude_aliases.append('y') cdms2.axis.longitude_aliases.append('x') from vacumm.config import data_sample f = cdms2.open(data_sample('ETOPO2v2g_flt.grd')) var = f('z', lon=(-6.1, -3), lat=(47.8, 48.8)) f.close() # Création de l'objet de bathy grillee from vacumm.bathy.bathy import GriddedBathy bathy = GriddedBathy(var) # On définit le traît de côte pour le masquage bathy.set_shoreline('f') # On récupère une version masquée bathy_orig = bathy.bathy(mask=False) bathy_masked = bathy.bathy(mask=True) # Definition d'une grille zoom from vacumm.misc.grid import create_grid new_grid = create_grid((-5.5, -4.6, 0.009), (48.25, 48.6, .006)) # On interpole la bathy masquée sur une autre grille interp_bathy_masked = bathy.regrid(new_grid) # On interpole et masque la bathy originale sur une autre grille # - interpolation
# Lecture des donnnees import cdms2, MV2, numpy as N from vacumm.config import data_sample select = dict(lon=(-5.3, -4.72), lat=(47.9, 48.8), time=slice(0, 24)) f = cdms2.open(data_sample('mars2d.xyt.nc')) v = MV2.masked_values(f('v', **select), 0., copy=False) f.close() # Diagonale lon = v.getLongitude() lat = v.getLatitude() nd = N.sqrt(len(lon)**2. + len(lat)**2) / 2. xo = N.linspace(lon[0], lon[-1], nd) yo = N.linspace(lat[0], lat[-1], nd) # Interpolation from vacumm.misc.grid.regridding import grid2xy vo = grid2xy(v, xo, yo, method='bilinear') # Plot # - variable interpolee from vacumm.misc.plot import hov2 as hov, savefigs, map2 as map hov(vo, cmap='jet', show=False, top=.9, date_fmt='%H', colorbar_shrink=.5, left=.13) # - carte + diagonal import pylab as P
# Ouverture import cdms2 from vacumm.config import data_sample f = cdms2.open(data_sample('mars2d.xyt.nc')) # Lister les variables print f.variables.keys() # -> ['bounds_lon', 'h0', 'v', 'xe', 'u', 'bounds_lat'] # Avoir des informations sur une variables sans la lire, via [] nt = f['xe'].shape[0] print f['xe'].getTime().asComponentTime()[0:nt:nt-1] # -> [2008-8-15 0:0:0.0, 2008-8-15 23:0:0.0] # Lire une selection de la variable import cdtime xe = f('xe', ('2008-8-15',cdtime.comptime(2008,8,15,12), 'cc'), lon=slice(5,6), lat=(48.1, 48.5), squeeze=1) print xe.shape # -> (13, 29) # squeeze a supprime l'axes des longitudes de dim 1 # Fermer le fichier lu f.close() # Definir la compression netcdf4 cdms2.setNetcdfShuffleFlag(1) cdms2.setNetcdfDeflateFlag(1) cdms2.setNetcdfDeflateLevelFlag(3) # Creer un nouveau fichier
'time':('TIME',), 'depth':('DEPH',), # Force using the DEPH variable as depth 'latitude':('LATITUDE',), 'longitude':('LONGITUDE',), 'temperature':('TEMP',), }, # The variable argument specify which variables will be used when using the load/save methods. # Do not specify time, depth, latitude and longitude as they # are special variables which are always required variables=('temperature',), # We could also add a quality code filter: # qualities=(1,2) ) from vacumm.config import data_sample p.load(data_sample('data.misc.profile.nc')) ########## # 2) Save profiles into a file suitable for profiles.py, that can be loaded by ProfilesDataset ########## of = 'data.misc.profile.converted.nc' p.save(of) # We could also have specified the variables to write here: # p.save(of, variables=('temperature',)) ########## # 3) Load the previously converted file using ProfilesDataset, which is more restrictive, # it is expecting input file to have profile and level axis, time, latitude, longitude variables. ########## p = P.ProfilesDataset(of)