# Parameters ncfile = "menor.nc" lon = (3.0, 4.5) lat = (42, 42.8) # Imports from vcmq import DS, map2, data_sample from vacumm.diag.thermdyn import mixed_layer_depth # Read temperature and depth ncfile = data_sample(ncfile) ds = DS(ncfile, "mars", lon=lon, lat=lat) temp = ds.get_temp(squeeze=1) depth = ds.get_depth(squeeze=1) # Compute MLD mld = mixed_layer_depth(temp, depth, mode="deltatemp") # Plot map2(mld, proj="merc", figsize=(6, 6), autoresize=0, colorbar_shrink=0.7, right=1, savefigs=__file__, show=False) print "Done"
"""Test :func:`~vacumm.diag.thermdyn.mixed_layer_depth` on MENOR""" # Inits ncfile = "menor.nc" # Imports from vcmq import DS, data_sample, mixed_layer_depth, rc, map2, os, code_file_name # Read data ds = DS(data_sample(ncfile),'mars', logger_level='critical') temp = ds.get_temp(squeeze=True) sal = ds.get_sal(squeeze=True) depth = ds.get_depth(squeeze=True) kz = ds.get_kz(squeeze=True) # Compute MLD kw = dict(depth=depth, format_axes=True) mld = {} mld['deltatemp'] = mixed_layer_depth(temp, mode='deltatemp',**kw) mld['deltadens'] = mixed_layer_depth((temp,sal), mode='deltadens', **kw) mld['kz'] = mixed_layer_depth(kz, mode='kz', **kw) vmin = min([v.min() for v in mld.values()]) vmax = max([v.max() for v in mld.values()]) # Plot it rc('font', size=8) for i,(mode, var) in enumerate(mld.items()): m = map2(var, fill='pcolormesh', nmax=20, vmin=vmin, vmax=vmax, subplot=(len(mld),1,i+1), figsize=(4.1,8), contour_linewidths=0.7, cmap='vacumm_rnb2_hymex', hspace=0.25, bottom=0.08, title='%%(long_name)s: mode = "%s"'%mode, show=False)
"""Test the asvar keyword of :meth:`~vacumm.data.misc.dataset.Dataset.finalize_object` on MFS""" # Inits ncfile = "mfs.nc" # Imports from vcmq import DS, data_sample # Read data ds = DS(data_sample(ncfile), 'nemo', logger_level='critical') temp = ds.get_temp() depth = ds.get_depth(asvar=temp) # For unittest result = {'assertTupleEqual':[depth.shape, temp.shape]}
print ds.dataset # Logging ds.info('Pratique') # -> ESSAYER WARNING ds.set_loglevel('debug') # Coordonnees lon = ds.get_lon() # -> ESSAYER AU POINT U grid = ds.get_grid() # Variables temp = ds.get_temp(level=slice(-1, None), squeeze=True) sst = ds.get_sst(squeeze=True) # -> VERIFIER ATTRIBUTS ds.info('Plot SST') map2(sst) sal = ds.get_sal(lon=(4., 4.5)) print temp.shape, sal.shape # Generique ds2 = DS(data_sample('mfs.nc'), 'nemo', lon=(4, 5), lat=(42.5, 43.5)) sst2 = ds2.get_sst(squeeze=True) # -> VERIFIER ATTRIBUTS # Plus evolue depth = ds.get_depth() # sigma print depth.shape mld = ds.get_mld() ds.plot_transect('temp', lons=(4.1, 4.9), lats=(43.3, 42.6), figsize=(12, 6)) # -> OUTAXIS=
def load_model_at_regular_dates(ncpat, varnames=None, time=None, lat=None, lon=None, level=None, depths=None, modeltype='mars', nt=50, dtfile=None, sort=True, asdict=False, logger=None, **kwargs): """Read model output at nearest unique dates with optional linear interpolation Parameters ---------- ncpat: string or list of strings varnames: string, strings Generic var names. If None, all variables that are known from the :mod:`vacumm.data.cf` module are used. level: string, None, list of floats, array, tuple of them, dict Here are some possible values: - "surf" or "bottom": self explenatory - None or "3d": No slice, so get all levels with no interpolation. - A list or array of negative depths: get all levels and interpolate at these depths. Variables sliced with "surf" and "bottom" are returned with an id suffixed with "_surf" or "_bottom". You can speficy different slicings using a tuple of depth specifications. You can specialise slicings of a variable using a dictionary with the key as the variable name. See also -------- :func:`sonat.misc.list_files_from_pattern` for more options Examples -------- >>> mdict = load_model_at_regular_dates('myfile.nc', level='surf') >>> mdict = load_model_at_regular_dates('myfile.nc', level=('surf', 'bottom') >>> mdict = load_model_at_regular_dates('myfile.nc', varnames=['temp', 'sal'], level={'temp':('surf', 'bottom'), 'sal':[-50, -10]}) >>> mdict = load_model_at_regular_dates('myfile.nc', varnames=['temp', 'sal'], level={'temp':('surf', '3d'), 'sal':None}, depths=[-50, -10]) """ # Logger kwlog = kwfilter(kwargs, 'logger_') if logger is None: logger = get_logger(**kwlog) logger.debug('Loading model at regular dates') # Get file list ncfiles = list_files_from_pattern(ncpat, time, dtfile=dtfile, sort=True) if not ncfiles: raise SONATError('No file found') # Time interval reqtime = time if time is None: # First taxis = ncget_time(ncfiles[0]) if taxis is None: raise SONATError("Can't get time axis for: " + ncfiles[0]) ctimes = taxis.asComponentTime() ct0 = ctimes[0] # Last if ncfiles[0] != ncfiles[-1]: taxis = ncget_time(ncfiles[-1]) if taxis is None: raise SONATError("Can't get time axis for: " + ncfiles[-1]) ctimes = taxis.asComponentTime() ct1 = ctimes[-1] # Time time = (ct0, ct1) # Generate dates dates = lindates(time[0], time[1], nt) # Get time indices iidict, iiinfo = ncfiles_time_indices(ncfiles, dates, getinfo=True, asslices=True) if iiinfo['missed'] or iiinfo['duplicates']: msg = ("You must provide at least {nt} model time steps to read " "independant dates") if reqtime: msg = msg + (", and your requested time range must be enclosed " "by model time range.") raise SONATError(msg) # Read single = isinstance(varnames, basestring) if single: varnames = [varnames] out = OrderedDict() vlevels = {} if not isinstance(level, dict): level = {'__default__': level} for ncfile, tslices in iidict.items(): # Dataset instance ds = DS(ncfile, modeltype, logger_name='SONAT.Dataset', logger_level='error') # List of well known variables if varnames is None: varnames = [] for ncvarname in ds.get_variable_names(): varname = match_known_var(ds[0][ncvarname]) if varname: varnames.append(varname) # Loop on variables vardepth = None kwvar = dict(lat=lat, lon=lon, verbose=False, bestestimate=False) for vname in list(varnames): # Level selector for this variable if vname in vlevels: # cached vlevel = vlevels[vname] else: vlevel = interpret_level(dicttree_get(level, vname), astuple=True) vlevels[vname] = vlevel # cache it # Loop on level specs for vlev in vlevel: # Output vname and vlev check if not isinstance(vlev, basestring): vnameo = vname elif vlev not in ('surf', "bottom", "3d"): raise SONATError('Depth string must one of ' 'surf, bottom, 3d') elif vlev != '3d': vnameo = vname + '_' + vlev else: vlev = None vnameo = vname # Slicing level and output depths if vlev not in ['surf', 'bottom']: # numeric so interpolation if vlev is None: vdep = depths if depths is not None else None else: vdep = vlev interp = vdep is not None if interp: vlev = None else: interp = False # Read and aggregate vout = out.setdefault(vnameo, []) # vinterp = None for tslice in tslices: # Get var kwvar['time'] = tslice var = ds(vname, level=vlev, **kwvar) # Interpolate at numeric depths if interp and var.getLevel() is not None: # Get depths if True or vardepth is None: #FIXME: bad to always read it vardepth = ds.get_depth(level=vlev, zerolid=True, **kwvar) # Interpolate var = ds._interp_at_depths_(var, vardepth, vdep, extrap='top') # Id with suffix var.id = vnameo # Store results vout.append(var) # Concatenate for vname, vout in out.items(): out[vname] = MV2_concatenate(vout) # Dict if asdict: return out # Single out = out.values() if single: return out[0] return out
#!/usr/bin/env python # -*- coding: utf8 -*- """Diagnostics thermodynamiques et dynamiques (:mod:`vacumm.diag.thermdyn` et :mod:`vacumm.diag.dynamics`)""" from vcmq import DS, data_sample, map2, density, mixed_layer_depth, barotropic_geostrophic_velocity, kinetic_energy, shapiro2d # Lecture des données de base ds = DS(data_sample('menor.nc')) temp = ds.get_temp(squeeze=1) sal = ds.get_sal(squeeze=1) depth = ds.get_depth(squeeze=1) ssh = ds.get_ssh(squeeze=1) # Densité dens_surf = density(temp[-1], sal[-1]) # -> CALCULER DENSITE 3D map2(dens_surf) # Couche mélangée mld = mixed_layer_depth((temp, sal), depth, mode='deltadens') # -> ESSAYER AUTRES MODES map2(mld, vmax=600.) # Vitesse geostrophique # - vitesses ug, vg = barotropic_geostrophic_velocity(ssh) # - energie cinetique ke = kinetic_energy((ug, vg)) # -> TESTER AVEC SSH ke.long_name = 'Surface geostrophique kinetic energy' ke = shapiro2d(ke)