def make_frc(frcname, grd, date0, date1): g = roms.Grid(grd) if not os.path.isfile(frcname): # create file: gen_frc(frcname, grd) else: last = netcdf.nctime(frcname, 'wind_time', wind_time=-1) print '-->found file %s with last time %s' % (frcname, last.isoformat()) date0 = last + datetime.timedelta(1.) # daily dates = [date0] while dates[-1] < date1: dates += [dates[-1] + datetime.timedelta(1.)] # daily n = -1 for d in dates: n += 1 if d == dates[0]: x, y, u, v, ij = read_wind(grd, d, ij=False) else: u, v = read_wind(grd, d, ij) U = calc.griddata(x, y, u, g.lon, g.lat, extrap=True) V = calc.griddata(x, y, v, g.lon, g.lat, extrap=True) # rotate wind, print ' --> rot U,V' angle = g.use('angle') U, V = calc.rot2d(U, V, angle) print ' filling %s' % d.isoformat(' ') fill_frc(frcname, d, U, V)
def read_wind(grd, date, ij=False): f = source(date) print('-- reading from %s' % f) time = netcdf.nctime(f, 'time') if 0: try: i = np.where(time == date)[0][0] except: return 'date %s not found' % date.isoformat(' ') else: i = 0 returnXY = False if ij is False: returnXY = True lon = netcdf.use(f, 'longitude') # -180..180 lat = netcdf.use(f, 'latitude') g = roms.Grid(grd) xl0 = np.asarray((g.lon.min(), g.lon.max())) xl = np.asarray((g.lon.min(), g.lon.max())) if np.any(xl > 180) or np.any(xl < -180): print('ERROR: grid is supposed to be -180<x<180') print( 'Can be implemented with mpl_toolkits.basemap.shiftgrid ... TODO' ) print('(http://matplotlib.org/basemap/api/basemap_api.html)') return yl = g.lat.min(), g.lat.max() ij = calc.ij_limits(lon, lat, xl, yl, margin=1) i0, i1, j0, j1 = ij u = netcdf.use(f, 'eastward_wind', longitude='%d:%d' % (i0, i1), latitude='%d:%d' % (j0, j1), time=i) v = netcdf.use(f, 'northward_wind', longitude='%d:%d' % (i0, i1), latitude='%d:%d' % (j0, j1), time=i) if returnXY: lon = netcdf.use(f, 'longitude', longitude='%d:%d' % (i0, i1), latitude='%d:%d' % (j0, j1)) lat = netcdf.use(f, 'latitude', longitude='%d:%d' % (i0, i1), latitude='%d:%d' % (j0, j1)) lon, lat = np.meshgrid(lon, lat) #if np.all(xl0<0): lon=lon-360 # this may be wrong ... if xl is near 0, lon ay have pos and neg values !!! fix this one day ... return lon, lat, u, v, ij else: return u, v
def make_frc(frcname, grd, date0, date1): g = roms.Grid(grd) if not os.path.isfile(frcname): # create file: gen_frc(frcname, grd) else: last = netcdf.nctime(frcname, 'wind_time', wind_time=-1) print('-->found file %s with last time %s' % (frcname, last.isoformat())) date0 = last + datetime.timedelta(1 / 4.) # 6h data dates = [date0] while dates[-1] < date1: dates += [dates[-1] + datetime.timedelta(1 / 4.)] # 6h data n = -1 ij = False for d in dates: n += 1 if ij is False: tmp = read_wind(grd, d, ij=False) if isinstance(tmp, basestring): continue # some error, like date not found! else: x, y, u, v, ij = tmp else: tmp = read_wind(grd, d, ij) if isinstance(tmp, basestring): continue else: u, v = tmp U = calc.griddata(x, y, u, g.lon, g.lat, extrap=True) V = calc.griddata(x, y, v, g.lon, g.lat, extrap=True) # rotate wind, print(' --> rot U,V') angle = g.use('angle') U, V = calc.rot2d(U, V, angle) print(' filling %s' % d.isoformat(' ')) fill_frc(frcname, d, U, V)
def plot_segments(grd, nseg=(10, 10), addxy=(.001, .001)): g = roms.Grid(grd) xb, yb = g.border() pl.figure() pl.plot(xb, yb, 'b.') xy, ij = ww3_specpoints(grd, nseg, addxy) x = xy[:, 0] y = xy[:, 1] xx = xy[:, 2] yy = xy[:, 3] pl.plot(x, y, 'o') pl.plot(xx, yy, '.') for i in range(len(x)): #print [x[i],xx[i]],[y[i],yy[i]] pl.plot([x[i], xx[i]], [y[i], yy[i]], 'r') raw_input()
def read_wind(grd,date,ij=False): f=source(date) print '-- reading from %s'%f time=netcdf.nctime(f,'time') try: i=np.where(time==date)[0][0] except: return 'date %s not found'%d.isoformat(' ') returnXY=False if ij is False: returnXY=True lon=netcdf.use(f,'lon') lat=netcdf.use(f,'lat') g=roms.Grid(grd) xl0=np.asarray((g.lon.min(),g.lon.max())) xl=np.asarray((g.lon.min(),g.lon.max())) if np.all(xl<0): xl=xl+360 elif np.any(xl<0) and np.any(xl>0): print 'ERROR: zero crossing not implemented !!!' print 'can be done with mpl_toolkits.basemap.shiftgrid ... TODO' print '(http://matplotlib.org/basemap/api/basemap_api.html)' return yl=g.lat.min(),g.lat.max() ij=calc.ij_limits(lon,lat,xl,yl,margin=1) i0,i1,j0,j1=ij u=netcdf.use(f,'uwnd',lon='%d:%d'%(i0,i1),lat='%d:%d'%(j0,j1),time=i) v=netcdf.use(f,'vwnd',lon='%d:%d'%(i0,i1),lat='%d:%d'%(j0,j1),time=i) if returnXY: lon=netcdf.use(f,'lon',lon='%d:%d'%(i0,i1),lat='%d:%d'%(j0,j1)) lat=netcdf.use(f,'lat',lon='%d:%d'%(i0,i1),lat='%d:%d'%(j0,j1)) lon,lat=np.meshgrid(lon,lat) if np.all(xl0<0): lon=lon-360 # this may be wrong ... if xl is near 0, lon ay have pos and neg values !!! fix this one day ... return lon,lat,u,v, ij else: return u,v
def data(self,date0=False,date1=False,quiet=True,grd=False): ''' Returns atm data date0 (>=) and date1 (<=) ''' if grd: from okean import roms r=roms.Grid(grd) xlim=r.lon.min(),r.lon.max() ylim=r.lat.min(),r.lat.max() lims=xlim,ylim else: lims=False # get data for all times in file: res=cordex_file_data(self.f,lims=lims,quiet=quiet) time=res['time'] if date0: date0=dateu.parse_date(date0) i,=np.where(time>=date0) i=i[0] else: i=0 if date1: date1=dateu.parse_date(date1) j,=np.where(time<=date1) j=j[-1] else: j=len(time) if date0 or date1: for k in res: if k =='time': res[k]=res[k][i:j+1] else: res[k].data=res[k].data[i:j+1,...] return res
def ww3gb_2TPAR(datafolder, date0, date1, romsgrid, nseg=(10, 10), addxy=(0.001, 0.001), dspr=20, path='', name='TPAR'): '''dspr, directional spreading; see https://www.myroms.org/forum/viewtopic.php?f=14&t=2335 ''' g = roms.Grid(romsgrid) # loading data: xlim = g.lon.min() - 2, g.lon.max() + 2 ylim = g.lat.min() - 2, g.lat.max() + 2 lon, lat, Time, Res = WW3Data(datafolder).data(date0, date1, xlim, ylim) # calc spec points: xy, ij = ww3_specpoints(romsgrid, nseg, addxy) # interpolate data at initial point of each segment: x = xy[:, 0] y = xy[:, 1] nt = len(Time) nv = len(Res) nx = xy.shape[0] TPAR = np.zeros((nt, nv, nx), 'f') vnames = 'hs', 'tp', 'dp' # Significant_height_of_combined_wind_waves_and_swell # Primary_wave_mean_period # Primary_wave_direction for it in range(nt): if it % 10 == 0: print 'time %03d of %03d : %s' % (it, nt, Time[it].isoformat(' ')) for iv in range(nv): vname = vnames[iv] #print ' -- %s'%vname v = Res[vname][it, ...] # 1st extrap masked data: v = calc.mask_extrap(lon, lat, v) TPAR[it, iv, :] = calc.griddata(lon, lat, v, x, y) # create TPAR files: for i in range(nx): fname = name + '_seg%03d.txt' % i j = open(fname, 'w') j.write('TPAR\n') for it in range(nt): # time as YYYYMMDD.HHMMSS tiso = Time[it].strftime('%Y%m%d.%H%M%S') j.write( '%s %6.2f %6.2f %6.2f %6.2f\n' % (tiso, TPAR[it, 0, i], TPAR[it, 1, i], TPAR[it, 2, i], dspr)) j.close() print 'created tpar file %s' % fname x1 = xy[:, 2] y1 = xy[:, 3] # add to swan INPUT: # BOUND SHAPESPEC JONSWAP PEAK DSPR DEGREES # BOUNDSPEC SEGMENT XY -54.3906 33.1171 -55.5271 35.8094 VARIABLE FILE 0 './forcings/TPAR2.txt' print '\n' print 'BOUND SHAPESPEC JONSWAP PEAK DSPR DEGREES' for i in range(nx): fname = os.path.join(path, name + '_seg%03d.txt' % i) print 'BOUNDSPEC SEGMENT XY %8.4f %8.4f %8.4f %8.4f VARIABLE FILE 0 \'%s\'' % ( x[i], y[i], x1[i], y1[i], fname) print '\n' i0 = ij[:, 0] j0 = ij[:, 1] i1 = ij[:, 2] j1 = ij[:, 3] for i in range(nx): fname = os.path.join(path, name + '_seg%03d.txt' % i) print 'BOUNDSPEC SEGMENT IJ %3d %3d %3d %3d VARIABLE FILE 0 \'%s\'' % ( i0[i], j0[i], i1[i], j1[i], fname) print '\n'
def plt_grid(cf, grd, ifig=0): ''' Plot grid ''' if isinstance(grd, basestring): grd = roms.Grid(grd) # start figure figConf, err = opt.get_plconf(cf, 'FIGURE') fig_size = figConf['size'][ifig] fig_bgcolor = figConf['bgcolor'][ifig] fig_fontsize = figConf['def_fontsize'][ifig] fig_linewidth = figConf['def_linewidth'][ifig] fig = pl.figure(figsize=fig_size, facecolor=fig_bgcolor) pl.matplotlib.rcParams['font.size'] = fig_fontsize pl.matplotlib.rcParams['lines.linewidth'] = fig_linewidth # grid data: grdConf, err = opt.get_plconf(cf, 'GRID') lonlims = grdConf['lonlims'][ifig] latlims = grdConf['latlims'][ifig] proj = grdConf['proj'][ifig] resolution = grdConf['resolution'][ifig] # start projection: if lonlims == 'auto': lonlims = grd.lon.min(), grd.lon.max() if latlims == 'auto': latlims = grd.lat.min(), grd.lat.max() if proj == 'merc': m = Basemap(projection=proj, resolution=resolution, urcrnrlon=lonlims[1], urcrnrlat=latlims[1], llcrnrlon=lonlims[0], llcrnrlat=latlims[0]) else: pass # TODO # add axes: axData, err = opt.get_plconf(cf, 'AXES') axpos = axData['position'][ifig] axbg = axData['bgcolor'][ifig] ax = fig.add_axes(axpos, axisbg=axbg) # bathy contour and border: h = np.ma.masked_where(grd.mask == 0, grd.h) xb, yb = grd.border() x, y = m(grd.lon, grd.lat) xb, yb = m(xb, yb) Data, err = opt.get_plconf(cf, 'BATHY') add = Data['add'][ifig] color = Data['color'][ifig] width = Data['width'][ifig] levels = Data['levels'][ifig] if add: ax.contour(x, y, h, levels, colors=color, linewidths=width) ax.plot(xb, yb, linewidth=width, color=color) ax.axis([m.xmin, m.xmax, m.ymin, m.ymax]) # coastlines: clData, err = opt.get_plconf(cf, 'COAST') add = clData['add'][ifig] color = clData['color'][ifig] width = clData['width'][ifig] if add: m.drawcoastlines(linewidth=width, color=color) # land: Data, err = opt.get_plconf(cf, 'LAND') add = Data['add'][ifig] color = Data['color'][ifig] if add: m.fillcontinents(color=color) # countries: Data, err = opt.get_plconf(cf, 'COUNTRIES') add = Data['add'][ifig] color = Data['color'][ifig] width = Data['width'][ifig] if add: m.drawcountries(linewidth=width, color=color) # states: Data, err = opt.get_plconf(cf, 'STATES') add = Data['add'][ifig] color = Data['color'][ifig] width = Data['width'][ifig] if add: m.drawstates(linewidth=width, color=color) # rivers: Data, err = opt.get_plconf(cf, 'RIVERS') add = Data['add'][ifig] color = Data['color'][ifig] width = Data['width'][ifig] if add: m.drawrivers(linewidth=width, color=color) # paralels: Data, err = opt.get_plconf(cf, 'PARALELS') add = Data['add'][ifig] color = Data['color'][ifig] width = Data['width'][ifig] ticks = Data['ticks'][ifig] dashes = Data['dashes'][ifig] if add: m.drawparallels(ticks, labels=[1, 0, 0, 0], dashes=dashes, linewidth=width, color=color) # meridians: Data, err = opt.get_plconf(cf, 'MERIDIANS') add = Data['add'][ifig] color = Data['color'][ifig] width = Data['width'][ifig] ticks = Data['ticks'][ifig] dashes = Data['dashes'][ifig] if add: m.drawmeridians(ticks, labels=[0, 0, 0, 1], dashes=dashes, linewidth=width, color=color) return m, fig, ax