Пример #1
0
  def vars(self,ruvp='r',i=False,j=False):
    '''
    return lon, lat, h and mask at r, u, v or p
    i,j slices can also be used
    '''

    ruvp=ruvp[0]
    if ruvp=='u':
      x = self.lonu
      y = self.latu
      h = rt.rho2uvp(self.h,'u')
      m = self.masku
    elif ruvp=='v':
      x = self.lonv
      y = self.latv
      h = rt.rho2uvp(self.h,'v')
      m = self.maskv
    elif ruvp=='p':
      x = self.lonp
      y = self.latp
      h = rt.rho2uvp(self.h,'p')
      m = self.maskp
    else:
      x = self.lon
      y = self.lat
      h = self.h
      m = self.mask

    if j is False: j=slice(None)
    if i is False: i=slice(None)

    x,y,h,m=[i.data for i in [x,y,h,m] if np.ma.isMA(i)]

    return x[j,i],y[j,i],h[j,i],m[j,i]
Пример #2
0
  def vars(self,ruvp='r',i=False,j=False):
    '''
    return lon, lat, h and mask at r, u, v or p
    i,j slices can also be used
    '''

    ruvp=ruvp[0]
    if ruvp=='u':
      x = self.lonu
      y = self.latu
      h = rt.rho2uvp(self.h,'u')
      m = self.masku
    elif ruvp=='v':
      x = self.lonv
      y = self.latv
      h = rt.rho2uvp(self.h,'v')
      m = self.maskv
    elif ruvp=='p':
      x = self.lonp
      y = self.latp
      h = rt.rho2uvp(self.h,'p')
      m = self.maskp
    else:
      x = self.lon
      y = self.lat
      h = self.h
      m = self.mask

    if j is False: j=slice(None)
    if i is False: i=slice(None)

    #x,y,h,m=[i.data for i in [x,y,h,m] if np.ma.isMA(i)]
    x,y,h,m=[k.data if  np.ma.isMA(k) else k for k in [x,y,h,m]]

    return x[j,i],y[j,i],h[j,i],m[j,i]
Пример #3
0
def data2romsblk(data, grd, **kargs):
    quiet = True
    keepOriginal = 2  # if 2, will keep data only inside rt.grid_vicinity rectange
    # if 1, all original data is kept
    Margin = 4  # for griddata and for original data to keep

    for k in kargs.keys():
        if k == "quiet":
            quiet = kargs[k]
        elif k.lower().startswith("keepor"):
            keepOriginal = kargs[k]
        elif k == "margin":
            Margin = kargs[k]

    g = roms.Grid(grd)

    cond = False
    out = {}

    for vname in data.keys():
        if vname.startswith("INFO") or vname in "xy":
            continue
        # vnames starting with INFO are an info key, without data

        if not quiet:
            print "  interp %s" % vname

        if cond is False:
            cond, inds = rt.grid_vicinity(grd, data["x"], data["y"], margin=Margin, rect=True, retinds=True)
            i1, i2, j1, j2 = inds

        out[vname] = calc.griddata(data["x"][cond], data["y"][cond], data[vname][cond], g.lon, g.lat, extrap=True)

        if keepOriginal:
            # keep original data:
            if keepOriginal == 1:
                out[vname + "_original"] = data[vname]  # keep all original data
            elif keepOriginal == 2:
                out[vname + "_original"] = data[vname][j1:j2, i1:i2]  # keep data only inside vicinity rectangle

            if not out.has_key("x_original"):
                if keepOriginal == 1:
                    out["x_original"] = data["x"]
                    out["y_original"] = data["y"]
                elif keepOriginal == 2:
                    out["x_original"] = data["x"][j1:j2, i1:i2]
                    out["y_original"] = data["y"][j1:j2, i1:i2]

    # about wind:
    if not quiet:
        print " --> rot U,V wind and U,V wind stress"
    angle = g.use("angle")
    out["uwnd"], out["vwnd"] = calc.rot2d(out["uwnd"], out["vwnd"], angle)
    out["sustr"], out["svstr"] = calc.rot2d(out["sustr"], out["svstr"], angle)

    out["sustr"] = rt.rho2uvp(out["sustr"], "u")
    out["svstr"] = rt.rho2uvp(out["svstr"], "v")

    return out
Пример #4
0
def data2romsblk(data,grd,**kargs):
  quiet        = True
  keepOriginal = 2 # if 2, will keep data only inside rt.grid_vicinity rectange
                   # if 1, all original data is kept
  Margin       = 4 # for griddata and for original data to keep

  for k in kargs.keys():
    if k=='quiet': quiet=kargs[k]
    elif k.lower().startswith('keepor'): keepOriginal=kargs[k]
    elif k=='margin': Margin=kargs[k]


  g=roms.Grid(grd)

  cond=False
  out={}

  for vname in data.keys():
    if vname.startswith('INFO') or vname in 'xy': continue
    # vnames starting with INFO are an info key, without data

    if not quiet: print '  interp %s' % vname

    if cond is False:
      cond,inds=rt.grid_vicinity(grd,data['x'],data['y'],
                                 margin=Margin,rect=True,retinds=True)
      i1,i2,j1,j2=inds

    out[vname]=calc.griddata(data['x'][cond],data['y'][cond],
                           data[vname][cond],g.lon,g.lat,extrap=True)

    if keepOriginal:
      # keep original data:
      if keepOriginal==1:
        out[vname+'_original']=data[vname] # kepp all original data
      elif keepOriginal==2:
        out[vname+'_original']=data[vname][j1:j2,i1:i2] # keep data only inside vicinity rectangle

      if not out.has_key('x_original'):
        if keepOriginal==1:
          out['x_original']=data['x']
          out['y_original']=data['y']
        elif keepOriginal==2:
          out['x_original']=data['x'][j1:j2,i1:i2]
          out['y_original']=data['y'][j1:j2,i1:i2]

  # about wind:
  if not quiet: print ' --> rot U,V wind and U,V wind stress'
  angle=g.use('angle')
  out['uwnd'],out['vwnd']=calc.rot2d(out['uwnd'],out['vwnd'],angle)
  out['sustr'],out['svstr']=calc.rot2d(out['sustr'],out['svstr'],angle)

  out['sustr']=rt.rho2uvp(out['sustr'],'u')
  out['svstr']=rt.rho2uvp(out['svstr'],'v')


  return out
Пример #5
0
  def load_uvp(self):
    '''
    Set uvp lon, lat and mask based on variables at rho, instead of
    loading them from file
    '''
    [setattr(self,'lon'+i,rt.rho2uvp(self.lon,i)) for i in 'uvp']
    [setattr(self,'lat'+i,rt.rho2uvp(self.lat,i)) for i in 'uvp']
    self.masku,self.maskv,self.maskp=rt.uvp_mask(self.mask)

    if not hasattr(self,'XI_U'):  self.XI_U  = self.XI_RHO-1
    if not hasattr(self,'XI_V'):  self.XI_V  = self.XI_RHO
    if not hasattr(self,'ETA_U'): self.ETA_U = self.ETA_RHO
    if not hasattr(self,'ETA_V'): self.ETA_V = self.ETA_RHO-1
Пример #6
0
  def load_uvp(self):
    '''
    Set uvp lon, lat and mask based on variables at rho, instead of
    loading them from file
    '''
    [setattr(self,'lon'+i,rt.rho2uvp(self.lon,i)) for i in 'uvp']
    [setattr(self,'lat'+i,rt.rho2uvp(self.lat,i)) for i in 'uvp']
    self.masku,self.maskv,self.maskp=rt.uvp_mask(self.mask)

    if not hasattr(self,'XI_U'):  self.XI_U  = self.XI_RHO-1
    if not hasattr(self,'XI_V'):  self.XI_V  = self.XI_RHO
    if not hasattr(self,'ETA_U'): self.ETA_U = self.ETA_RHO
    if not hasattr(self,'ETA_V'): self.ETA_V = self.ETA_RHO-1
Пример #7
0
  def sliceuv(self,ind,time=0,**opts):#plot=False,**opts):
    coords=opts.get('coords',self._default_coords('sliceuv')).split(',')

    if ind=='bar':
      slc,uname,vname,ind = self.slicek, 'ubar','vbar', 9999
    elif ind in ('s','surf','surface'):
      slc,uname,vname,ind = self.slicek,  'u','v', -1
    elif ind>=0:
      slc,uname,vname,ind = self.slicek,  'u','v', ind
    elif ind <0:
      slc,uname,vname,ind = self.slicez, 'u','v', ind

    outu=slc(uname,ind,time,**opts)
    outv=slc(vname,ind,time,**opts)

    if   outu.msg: return outu
    elif outv.msg: return outv

    # at psi:
    u,v=outu.v,outv.v
    u=( u[1:,:]+ u[:-1,:])/2.
    v=( v[:,1:]+ v[:,:-1])/2.

    # rotate uv:
    if 0:
      ang=rt.rho2uvp(self.grid.angle,'p')
    else:
      ang=np.cos(self.grid.angle)+1j*np.sin(self.grid.angle)
      ang=np.angle(rt.rho2uvp(ang,'p'))

    u,v=calc.rot2d(u,v,-ang)

    out=outu
    out.label=out.label+'_uv'
    out.v=u+1j*v
    out.info['v']['name']=uname+vname

    if 'z' in coords: out.z=(out.z[1:,:]+out.z[:-1,:])/2.
    if 'x' in coords: out.x=(out.x[1:,:]+out.x[:-1,:])/2.
    if 'y' in coords: out.y=(out.y[1:,:]+out.y[:-1,:])/2.

    out.coordsReq=','.join(sorted(coords))
    return out
Пример #8
0
  def sliceuv(self,ind,time=0,**opts):#plot=False,**opts):
    coords=opts.get('coords',self._default_coords('sliceuv')).split(',')

    if ind=='bar':
      slc,uname,vname,ind = self.slicek, 'ubar','vbar', 9999
    elif ind in ('s','surf','surface'):
      slc,uname,vname,ind = self.slicek,  'u','v', -1
    elif ind>=0:
      slc,uname,vname,ind = self.slicek,  'u','v', ind
    elif ind <0:
      slc,uname,vname,ind = self.slicez, 'u','v', ind

    outu=slc(uname,ind,time,**opts)
    outv=slc(vname,ind,time,**opts)

    if   outu.msg: return outu
    elif outv.msg: return outv

    # at psi:
    u,v=outu.v,outv.v
    u=( u[1:,:]+ u[:-1,:])/2.
    v=( v[:,1:]+ v[:,:-1])/2.

    # rotate uv:
    if 0:
      ang=rt.rho2uvp(self.grid.angle,'p')
    else:
      ang=np.cos(self.grid.angle)+1j*np.sin(self.grid.angle)
      ang=np.angle(rt.rho2uvp(ang,'p'))

    u,v=calc.rot2d(u,v,-ang)

    out=outu
    out.label=out.label+'_uv'
    out.v=u+1j*v
    out.info['v']['name']=uname+vname

    if 'z' in coords: out.z=(out.z[1:,:]+out.z[:-1,:])/2.
    if 'x' in coords: out.x=(out.x[1:,:]+out.x[:-1,:])/2.
    if 'y' in coords: out.y=(out.y[1:,:]+out.y[:-1,:])/2.

    out.coordsReq=','.join(sorted(coords))
    return out
Пример #9
0
  def s_levels(self,sparams,zeta=0,h=False,loc='rr',i=False,j=False,k=False):
    hLoc,vLoc=loc
    if h is False: h=self.h

    try:
      zeta.shape==h.shape
    except:
      zeta=np.tile(zeta,h.shape).astype(h.dtype)

    if h.ndim==2:
      h=rt.rho2uvp(h,hLoc)
      zeta=rt.rho2uvp(zeta,hLoc)

    z=rt.s_levels(h,zeta,sparams,rw=vLoc)

    if k is False: k=slice(None)
    if j is False: j=slice(None)
    if i is False: i=slice(None)

########################    return np.squeeze(z[k,j,i])
    return z[k,j,i]
Пример #10
0
  def s_levels(self,sparams,zeta=0,h=False,loc='rr',i=False,j=False,k=False):
    hLoc,vLoc=loc
    if h is False: h=self.h

    try:
      zeta.shape==h.shape
    except:
      zeta=np.tile(zeta,h.shape).astype(h.dtype)

    if h.ndim==2:
      h=rt.rho2uvp(h,hLoc)
      zeta=rt.rho2uvp(zeta,hLoc)

    z=rt.s_levels(h,zeta,sparams,rw=vLoc)

    if k is False: k=slice(None)
    if j is False: j=slice(None)
    if i is False: i=slice(None)

########################    return np.squeeze(z[k,j,i])
    return z[k,j,i]
Пример #11
0
  def s_levels(self,time,loc='rr',i=False,j=False,k=False,extrapZeta=False):
    try:
      hLoc,vLoc=loc
    except:
      hLoc,vLoc=loc,'r'

    h=self.grid.h
    zeta=self.use('zeta',SEARCHtime=time)

    if extrapZeta:
      #if not calc.ismarray(zeta): zeta=np.ma.masked_where(self.grid.mask==0,zeta)
      if not np.ma.is_masked(zeta): zeta=np.ma.masked_where(self.grid.mask==0,zeta)
      zeta=calc.mask_extrap(self.grid.lon,self.grid.lat,zeta)

    h=rt.rho2uvp(h,hLoc)
    zeta=rt.rho2uvp(zeta,hLoc)
    z=rt.s_levels(h,zeta,self.s_params,rw=vLoc)

    if k is False: k=slice(None)
    if j is False: j=slice(None)
    if i is False: i=slice(None)

    return z[k,j,i]
Пример #12
0
  def s_levels(self,time,loc='rr',i=False,j=False,k=False,extrapZeta=False):
    try:
      hLoc,vLoc=loc
    except:
      hLoc,vLoc=loc,'r'

    h=self.grid.h
    zeta=self.use('zeta',SEARCHtime=time)

    if extrapZeta:
      #if not calc.ismarray(zeta): zeta=np.ma.masked_where(self.grid.mask==0,zeta)
      if not np.ma.is_masked(zeta): zeta=np.ma.masked_where(self.grid.mask==0,zeta)
      zeta=calc.mask_extrap(self.grid.lon,self.grid.lat,zeta)

    h=rt.rho2uvp(h,hLoc)
    zeta=rt.rho2uvp(zeta,hLoc)
    z=rt.s_levels(h,zeta,self.s_params,rw=vLoc)

    if k is False: k=slice(None)
    if j is False: j=slice(None)
    if i is False: i=slice(None)

    return z[k,j,i]
Пример #13
0
  def slicez(self,varname,ind,time=0,**opts):
    surf_mask=opts.get('surf_mask',True)
    spline=opts.get('spline',True)
    coords=opts.get('coords',self._default_coords('slicez')).split(',')

    out=vis.Data()
    out.label='slicez'
    out.msg=self.check_slice(varname,t=time)
    if out.msg: return out

    if not 'z' in self.vaxes(varname):
      return self.slicek(varname,ind,time,**opts)

    v=self.use(varname,SEARCHtime=time)
###    x,y,h,m=self.grid.vars(ruvp=self.var_at(varname)[0])
    x,y,h,m=self.grid.vars(ruvp=self.vloc(varname)[0])
    zeta=self.use('zeta',SEARCHtime=time)
    zeta=rt.rho2uvp(zeta,varname)

    out.v=rt.slicez(v,m,h,zeta,self.s_params,ind,surf_mask,spline)

    out.info['v']['name']=varname
    if calc.isarray(ind):
      out.info['v']['slice']='z= array %.2f to %.2f'%(ind.min(),ind.max())
    else:
      out.info['v']['slice']='z=%d'%ind
    try: out.info['v']['units']=netcdf.vatt(self.nc,varname,'units')
    except: pass


    # coords:
    if 'x' in coords:
       if self.grid.spherical:
         out.x=x
         out.info['x']=dict(name='Longitude',units=r'$\^o$E')
       else:
         out.x=x/1000.
         out.info['x']=dict(name='Distance',units='km')

    if 'y' in coords:
       if self.grid.spherical:
         out.y=y
         out.info['y']=dict(name='Latitude',units=r'$\^o$N')
       else:
         out.y=y/1000.
         out.info['y']=dict(name='Distance',units='km')

    if 'z' in coords:
      out.z=ind+np.zeros(out.v.shape)
      out.info['z']=dict(name='Depth',units='m')

    if 't' in coords and 't' in self.vaxes(varname): out.t=self.time[time]

    if out.v.ndim==2:
      out.extra=[vis.Data()]
      if 'x' in coords: out.extra[0].x=out.x
      if 'y' in coords: out.extra[0].y=out.y
      out.extra[0].v=h
      if h.max()>1000: cvals=200.,1000.
      elif h.max()>200: cvals=50.,100.,200.
      else: cvals=3
      out.extra[0].config['field.plot']='contour'
      out.extra[0].config['field.cvals']=cvals
      out.extra[0].config['field.cmap']='k'
      out.extra[0].label='bathy'


    out.coordsReq=','.join(sorted(coords))

    # about projection:
    out.set_projection(self.grid.proj_info['basemap_opts'])

    return out
Пример #14
0
def update_wind(fname,data,new_wind_info,**kargs):
  '''
  new_wind_info will be added to fname as global attribute
  (ex: 'new wind from database xxx')

  '''
  quiet  = False
  Margin = 4 # for griddata and for original data to keep
  grd    = False
  keepOriginal = 2

  for k in kargs.keys():
    if   k=='quiet':  quiet=kargs[k]
    elif k=='margin': Margin=kargs[k]
    elif k=='grid':   grd=kargs[k]
    elif k.lower().startswith('keepor'): keepOriginal=kargs[k]

  if not grd: grd=netcdf.fatt(fname,'grd_file')
  g=roms.Grid(grd)

  x0=data['x']
  y0=data['y']
  if x0.ndim==1: x0,y0=np.meshgrid(x0,y0)
  dates=data.keys()[:]
  dates.remove('x')
  dates.remove('y')
  dates=np.array(dates)


  # interp in time:
  time=netcdf.nctime(fname,'time')
  cond=False
  tind=-1
  fob=gennc.GenBlk(fname,grd)
  for t in time:
    newWind={}
    tind+=1

    I,=np.where(dates==t)
    if I.size:
      I=I[0]
      uv=data[dates[I]]
      if not quiet: print(t,dates[I])
    else:
      i1,=np.where(dates>t)
      i0,=np.where(dates<t)
      if i0.size and i1.size:
        i1=i1[0]
        i0=i0[-1]
        d0=t-dates[i0]
        d1=dates[i1]-t
        d0=d0.days+d0.seconds/86400.
        d1=d1.days+d1.seconds/86400.
        uv=(data[dates[i0]]*d1+data[dates[i1]]*d0)/(d0+d1)
        if not quiet: print(t,dates[i0],dates[i1], d0,d1)
      elif not i1.size:
        uv=data[dates[-1]]
        if not quiet: print(t,dates[-1])
      elif not i0.size:
        uv=data[dates[0]]
        if not quiet: print(t,dates[0])

    # interp to grid:
    if cond is False:
      cond,inds=rt.grid_vicinity(grd,x0,y0,margin=Margin,rect=True,retinds=True)
      i1,i2,j1,j2=inds

    if not quiet: print(' --> inter uv %s' % t.isoformat(' '))
    u=calc.griddata(x0[cond],y0[cond],uv.real[cond],g.lon,g.lat,extrap=True)
    v=calc.griddata(x0[cond],y0[cond],uv.imag[cond],g.lon,g.lat,extrap=True)


    # rotate wind, calc stress:
    if not quiet: print(' --> rot U,V wind and U,V wind stress')
    wspd=np.sqrt(u**2+v**2)
    sustr,svstr=air_sea.wind_stress(u,v)
    angle=g.use('angle')
    uwnd,vwnd=calc.rot2d(u,v,angle)
    sustr,svstr=calc.rot2d(sustr,svstr,angle)
    sustr=rt.rho2uvp(sustr,'u')
    svstr=rt.rho2uvp(svstr,'v')

    # update wind data:
    newWind['date']  = t
    newWind['uwnd']  = uwnd
    newWind['vwnd']  = vwnd
    newWind['sustr'] = sustr
    newWind['svstr'] = svstr
    newWind['wspd']  = wspd
    # original xy:
    if tind==0:
      newWind['attr']={'new_wind_info':new_wind_info}
      if not quiet: print(' --> original xy')
      if keepOriginal==1:
        newWind['x_wind']=x0
        newWind['y_wind']=y0
      elif keepOriginal==2:
        newWind['x_wind']=x0[j1:j2,i1:i2]
        newWind['y_wind']=y0[j1:j2,i1:i2]


    # add to file:
    if not quiet: print(' --> adding to file')
    fob.update_wind(newWind,quiet=quiet)
    if not quiet: print('')
Пример #15
0
def data2romsblk(data,grd,**kargs):
  quiet=kargs.get('quiet',True)
  Margin=kargs.get('margin',4) # for griddata and for original data to keep
                               # if margin is 'no calc', no extraction of
                               # a domain portion is done

  # about projection:
  # - if auto will use grid default projection
  # - if False, no projection is used
  # - any Basemap projection can be used
  proj=kargs.get('proj','auto')

  # about origina data to keep:
  # - if 2, will keep data only inside rt.grid_vicinity rectange
  # - if 1, all original data is kept
  keepOriginal = 2
  for k in kargs:
    if k.lower().startswith('keepor'): keepOriginal=kargs[k]

  if cb.isstr(grd): g=roms.Grid(grd)
  else: g=grd

  if proj=='auto': proj=g.get_projection()

  if proj:
    data_x,data_y=proj(data['x'],data['y'])
    grd_x,grd_y=proj(g.lon,g.lat)
  else:
    data_x,data_y=data['x'],data['y']
    grd_x,grd_y=g.lon,g.lat

  cond=False
  out={}

  for vname in data:
    if vname.startswith('INFO') or vname in 'xy': continue
    # vnames starting with INFO are an info key, without data

    if not quiet: print('  interp %s' % vname)

    if cond is False:
      if Margin=='no calc':
        cond=np.ones_like(data['x'],'bool')
        i1,i1=0,0
        j2,i2=data['x'].shape
      else:
        cond,inds=rt.grid_vicinity(grd,data['x'],data['y'],
                                   margin=Margin,rect=True,retinds=True)
        i1,i2,j1,j2=inds

    out[vname]=calc.griddata(data_x[cond],data_y[cond],
                           data[vname][cond],grd_x,grd_y,extrap=True)

    if keepOriginal:
      # keep original data:
      if keepOriginal==1:
        out[vname+'_original']=data[vname] # keep all original data
      elif keepOriginal==2:
        out[vname+'_original']=data[vname][j1:j2,i1:i2] # keep data only inside vicinity rectangle

      if 'x_original' not in out:
        if keepOriginal==1:
          out['x_original']=data['x']
          out['y_original']=data['y']
        elif keepOriginal==2:
          out['x_original']=data['x'][j1:j2,i1:i2]
          out['y_original']=data['y'][j1:j2,i1:i2]

  # about wind:
  if not quiet: print(' --> rot U,V wind and U,V wind stress')
  out['uwnd'],out['vwnd']=calc.rot2d(out['uwnd'],out['vwnd'],g.angle)
  out['sustr'],out['svstr']=calc.rot2d(out['sustr'],out['svstr'],g.angle)

  out['sustr']=rt.rho2uvp(out['sustr'],'u')
  out['svstr']=rt.rho2uvp(out['svstr'],'v')

  return out
Пример #16
0
def data2romsblk(data, grd, **kargs):
    quiet = True
    keepOriginal = 2  # if 2, will keep data only inside rt.grid_vicinity rectange
    # if 1, all original data is kept
    Margin = 4  # for griddata and for original data to keep

    for k in kargs.keys():
        if k == 'quiet': quiet = kargs[k]
        elif k.lower().startswith('keepor'): keepOriginal = kargs[k]
        elif k == 'margin': Margin = kargs[k]

    g = roms.Grid(grd)

    cond = False
    out = {}

    for vname in data.keys():
        if vname.startswith('INFO') or vname in 'xy': continue
        # vnames starting with INFO are an info key, without data

        if not quiet: print('  interp %s' % vname)

        if cond is False:
            cond, inds = rt.grid_vicinity(grd,
                                          data['x'],
                                          data['y'],
                                          margin=Margin,
                                          rect=True,
                                          retinds=True)
            i1, i2, j1, j2 = inds

        out[vname] = calc.griddata(data['x'][cond],
                                   data['y'][cond],
                                   data[vname][cond],
                                   g.lon,
                                   g.lat,
                                   extrap=True)

        if keepOriginal:
            # keep original data:
            if keepOriginal == 1:
                out[vname +
                    '_original'] = data[vname]  # keep all original data
            elif keepOriginal == 2:
                out[vname + '_original'] = data[vname][
                    j1:j2, i1:i2]  # keep data only inside vicinity rectangle

            if not out.has_key('x_original'):
                if keepOriginal == 1:
                    out['x_original'] = data['x']
                    out['y_original'] = data['y']
                elif keepOriginal == 2:
                    out['x_original'] = data['x'][j1:j2, i1:i2]
                    out['y_original'] = data['y'][j1:j2, i1:i2]

    # about wind:
    if not quiet: print(' --> rot U,V wind and U,V wind stress')
    angle = g.use('angle')
    out['uwnd'], out['vwnd'] = calc.rot2d(out['uwnd'], out['vwnd'], angle)
    out['sustr'], out['svstr'] = calc.rot2d(out['sustr'], out['svstr'], angle)

    out['sustr'] = rt.rho2uvp(out['sustr'], 'u')
    out['svstr'] = rt.rho2uvp(out['svstr'], 'v')

    return out
Пример #17
0
def update_wind(fname, data, new_wind_info, **kargs):
    """
  new_wind_info will be added to fname as global attribute
  (ex: 'new wind from database xxx')

  """
    quiet = False
    Margin = 4  # for griddata and for original data to keep
    grd = False
    keepOriginal = 2

    for k in kargs.keys():
        if k == "quiet":
            quiet = kargs[k]
        elif k == "margin":
            Margin = kargs[k]
        elif k == "grid":
            grd = kargs[k]
        elif k.lower().startswith("keepor"):
            keepOriginal = kargs[k]

    if not grd:
        grd = netcdf.fatt(fname, "grd_file")
    g = roms.Grid(grd)

    x0 = data["x"]
    y0 = data["y"]
    if x0.ndim == 1:
        x0, y0 = np.meshgrid(x0, y0)
    dates = data.keys()[:]
    dates.remove("x")
    dates.remove("y")
    dates = np.array(dates)

    # interp in time:
    time = netcdf.nctime(fname, "time")
    cond = False
    tind = -1
    fob = gennc.GenBlk(fname, grd)
    for t in time:
        newWind = {}
        tind += 1

        I, = np.where(dates == t)
        if I.size:
            I = I[0]
            uv = data[dates[I]]
            if not quiet:
                print t, dates[I]
        else:
            i1, = np.where(dates > t)
            i0, = np.where(dates < t)
            if i0.size and i1.size:
                i1 = i1[0]
                i0 = i0[-1]
                d0 = t - dates[i0]
                d1 = dates[i1] - t
                d0 = d0.days + d0.seconds / 86400.0
                d1 = d1.days + d1.seconds / 86400.0
                uv = (data[dates[i0]] * d1 + data[dates[i1]] * d0) / (d0 + d1)
                if not quiet:
                    print t, dates[i0], dates[i1], d0, d1
            elif not i1.size:
                uv = data[dates[-1]]
                if not quiet:
                    print t, dates[-1]
            elif not i0.size:
                uv = data[dates[0]]
                if not quiet:
                    print t, dates[0]

        # interp to grid:
        if cond is False:
            cond, inds = rt.grid_vicinity(grd, x0, y0, margin=Margin, rect=True, retinds=True)
            i1, i2, j1, j2 = inds

        if not quiet:
            print " --> inter uv %s" % t.isoformat(" ")
        u = calc.griddata(x0[cond], y0[cond], uv.real[cond], g.lon, g.lat, extrap=True)
        v = calc.griddata(x0[cond], y0[cond], uv.imag[cond], g.lon, g.lat, extrap=True)

        # rotate wind, calc stress:
        if not quiet:
            print " --> rot U,V wind and U,V wind stress"
        wspd = np.sqrt(u ** 2 + v ** 2)
        sustr, svstr = air_sea.wind_stress(u, v)
        angle = g.use("angle")
        uwnd, vwnd = calc.rot2d(u, v, angle)
        sustr, svstr = calc.rot2d(sustr, svstr, angle)
        sustr = rt.rho2uvp(sustr, "u")
        svstr = rt.rho2uvp(svstr, "v")

        # update wind data:
        newWind["date"] = t
        newWind["uwnd"] = uwnd
        newWind["vwnd"] = vwnd
        newWind["sustr"] = sustr
        newWind["svstr"] = svstr
        newWind["wspd"] = wspd
        # original xy:
        if tind == 0:
            newWind["attr"] = {"new_wind_info": new_wind_info}
            if not quiet:
                print " --> original xy"
            if keepOriginal == 1:
                newWind["x_wind"] = x0
                newWind["y_wind"] = y0
            elif keepOriginal == 2:
                newWind["x_wind"] = x0[j1:j2, i1:i2]
                newWind["y_wind"] = y0[j1:j2, i1:i2]

        # add to file:
        if not quiet:
            print " --> adding to file"
        fob.update_wind(newWind, quiet=quiet)
        if not quiet:
            print ""
Пример #18
0
  def slicez(self,varname,ind,time=0,**opts):
    surf_mask=opts.get('surf_mask',True)
    spline=opts.get('spline',True)
    coords=opts.get('coords',self._default_coords('slicez')).split(',')

    out=vis.Data()
    out.label='slicez'
    out.msg=self.check_slice(varname,t=time)
    if out.msg: return out

    if not 'z' in self.vaxes(varname):
      return self.slicek(varname,ind,time,**opts)

    v=self.use(varname,SEARCHtime=time)
###    x,y,h,m=self.grid.vars(ruvp=self.var_at(varname)[0])
    x,y,h,m=self.grid.vars(ruvp=self.vloc(varname)[0])
    zeta=self.use('zeta',SEARCHtime=time)
    zeta=rt.rho2uvp(zeta,varname)

    out.v=rt.slicez(v,m,h,zeta,self.s_params,ind,surf_mask,spline)

    out.info['v']['name']=varname
    if calc.isarray(ind):
      out.info['v']['slice']='z= array %.2f to %.2f'%(ind.min(),ind.max())
    else:
      out.info['v']['slice']='z=%d'%ind
    try: out.info['v']['units']=netcdf.vatt(self.nc,varname,'units')
    except: pass


    # coords:
    if 'x' in coords:
       if self.grid.spherical:
         out.x=x
         out.info['x']=dict(name='Longitude',units=r'$\^o$E')
       else:
         out.x=x/1000.
         out.info['x']=dict(name='Distance',units='km')

    if 'y' in coords:
       if self.grid.spherical:
         out.y=y
         out.info['y']=dict(name='Latitude',units=r'$\^o$N')
       else:
         out.y=y/1000.
         out.info['y']=dict(name='Distance',units='km')

    if 'z' in coords:
      out.z=ind+np.zeros(out.v.shape)
      out.info['z']=dict(name='Depth',units='m')

    if 't' in coords and 't' in self.vaxes(varname): out.t=self.time[time]

    if out.v.ndim==2:
      out.extra=[vis.Data()]
      if 'x' in coords: out.extra[0].x=out.x
      if 'y' in coords: out.extra[0].y=out.y
      out.extra[0].v=h
      if h.max()>1000: cvals=200.,1000.
      elif h.max()>200: cvals=50.,100.,200.
      else: cvals=3
      out.extra[0].config['field.plot']='contour'
      out.extra[0].config['field.cvals']=cvals
      out.extra[0].config['field.cmap']='k'
      out.extra[0].label='bathy'


    out.coordsReq=','.join(sorted(coords))

    # about projection:
    out.set_projection(self.grid.proj_info['basemap_opts'])

    return out
Пример #19
0
def update_wind(fname, data, new_wind_info, **kargs):
    '''
  new_wind_info will be added to fname as global attribute
  (ex: 'new wind from database xxx')

  '''
    quiet = False
    Margin = 4  # for griddata and for original data to keep
    grd = False
    keepOriginal = 2

    for k in kargs.keys():
        if k == 'quiet': quiet = kargs[k]
        elif k == 'margin': Margin = kargs[k]
        elif k == 'grid': grd = kargs[k]
        elif k.lower().startswith('keepor'): keepOriginal = kargs[k]

    if not grd: grd = netcdf.fatt(fname, 'grd_file')
    g = roms.Grid(grd)

    x0 = data['x']
    y0 = data['y']
    if x0.ndim == 1: x0, y0 = np.meshgrid(x0, y0)
    dates = data.keys()[:]
    dates.remove('x')
    dates.remove('y')
    dates = np.array(dates)

    # interp in time:
    time = netcdf.nctime(fname, 'time')
    cond = False
    tind = -1
    fob = gennc.GenBlk(fname, grd)
    for t in time:
        newWind = {}
        tind += 1

        I, = np.where(dates == t)
        if I.size:
            I = I[0]
            uv = data[dates[I]]
            if not quiet: print(t, dates[I])
        else:
            i1, = np.where(dates > t)
            i0, = np.where(dates < t)
            if i0.size and i1.size:
                i1 = i1[0]
                i0 = i0[-1]
                d0 = t - dates[i0]
                d1 = dates[i1] - t
                d0 = d0.days + d0.seconds / 86400.
                d1 = d1.days + d1.seconds / 86400.
                uv = (data[dates[i0]] * d1 + data[dates[i1]] * d0) / (d0 + d1)
                if not quiet: print(t, dates[i0], dates[i1], d0, d1)
            elif not i1.size:
                uv = data[dates[-1]]
                if not quiet: print(t, dates[-1])
            elif not i0.size:
                uv = data[dates[0]]
                if not quiet: print(t, dates[0])

        # interp to grid:
        if cond is False:
            cond, inds = rt.grid_vicinity(grd,
                                          x0,
                                          y0,
                                          margin=Margin,
                                          rect=True,
                                          retinds=True)
            i1, i2, j1, j2 = inds

        if not quiet: print(' --> inter uv %s' % t.isoformat(' '))
        u = calc.griddata(x0[cond],
                          y0[cond],
                          uv.real[cond],
                          g.lon,
                          g.lat,
                          extrap=True)
        v = calc.griddata(x0[cond],
                          y0[cond],
                          uv.imag[cond],
                          g.lon,
                          g.lat,
                          extrap=True)

        # rotate wind, calc stress:
        if not quiet: print(' --> rot U,V wind and U,V wind stress')
        wspd = np.sqrt(u**2 + v**2)
        sustr, svstr = air_sea.wind_stress(u, v)
        angle = g.use('angle')
        uwnd, vwnd = calc.rot2d(u, v, angle)
        sustr, svstr = calc.rot2d(sustr, svstr, angle)
        sustr = rt.rho2uvp(sustr, 'u')
        svstr = rt.rho2uvp(svstr, 'v')

        # update wind data:
        newWind['date'] = t
        newWind['uwnd'] = uwnd
        newWind['vwnd'] = vwnd
        newWind['sustr'] = sustr
        newWind['svstr'] = svstr
        newWind['wspd'] = wspd
        # original xy:
        if tind == 0:
            newWind['attr'] = {'new_wind_info': new_wind_info}
            if not quiet: print(' --> original xy')
            if keepOriginal == 1:
                newWind['x_wind'] = x0
                newWind['y_wind'] = y0
            elif keepOriginal == 2:
                newWind['x_wind'] = x0[j1:j2, i1:i2]
                newWind['y_wind'] = y0[j1:j2, i1:i2]

        # add to file:
        if not quiet: print(' --> adding to file')
        fob.update_wind(newWind, quiet=quiet)
        if not quiet: print('')
Пример #20
0
def data2romsblk(data, grd, **kargs):
    quiet = kargs.get('quiet', True)
    Margin = kargs.get('margin',
                       4)  # for griddata and for original data to keep
    # if margin is 'no calc', no extraction of
    # a domain portion is done

    # about projection:
    # - if auto will use grid default projection
    # - if False, no projection is used
    # - any Basemap projection can be used
    proj = kargs.get('proj', 'auto')

    # about origina data to keep:
    # - if 2, will keep data only inside rt.grid_vicinity rectange
    # - if 1, all original data is kept
    keepOriginal = 2
    for k in kargs:
        if k.lower().startswith('keepor'): keepOriginal = kargs[k]

    if cb.isstr(grd): g = roms.Grid(grd)
    else: g = grd

    if proj == 'auto': proj = g.get_projection()

    if proj:
        data_x, data_y = proj(data['x'], data['y'])
        grd_x, grd_y = proj(g.lon, g.lat)
    else:
        data_x, data_y = data['x'], data['y']
        grd_x, grd_y = g.lon, g.lat

    cond = False
    out = {}

    for vname in data:
        if vname.startswith('INFO') or vname in 'xy': continue
        # vnames starting with INFO are an info key, without data

        if not quiet: print('  interp %s' % vname)

        if cond is False:
            if Margin == 'no calc':
                cond = np.ones_like(data['x'], 'bool')
                i1, i1 = 0, 0
                j2, i2 = data['x'].shape
            else:
                cond, inds = rt.grid_vicinity(grd,
                                              data['x'],
                                              data['y'],
                                              margin=Margin,
                                              rect=True,
                                              retinds=True)
                i1, i2, j1, j2 = inds

        out[vname] = calc.griddata(data_x[cond],
                                   data_y[cond],
                                   data[vname][cond],
                                   grd_x,
                                   grd_y,
                                   extrap=True)

        if keepOriginal:
            # keep original data:
            if keepOriginal == 1:
                out[vname +
                    '_original'] = data[vname]  # keep all original data
            elif keepOriginal == 2:
                out[vname + '_original'] = data[vname][
                    j1:j2, i1:i2]  # keep data only inside vicinity rectangle

            if 'x_original' not in out:
                if keepOriginal == 1:
                    out['x_original'] = data['x']
                    out['y_original'] = data['y']
                elif keepOriginal == 2:
                    out['x_original'] = data['x'][j1:j2, i1:i2]
                    out['y_original'] = data['y'][j1:j2, i1:i2]

    # about wind:
    if not quiet: print(' --> rot U,V wind and U,V wind stress')
    out['uwnd'], out['vwnd'] = calc.rot2d(out['uwnd'], out['vwnd'], g.angle)
    out['sustr'], out['svstr'] = calc.rot2d(out['sustr'], out['svstr'],
                                            g.angle)

    out['sustr'] = rt.rho2uvp(out['sustr'], 'u')
    out['svstr'] = rt.rho2uvp(out['svstr'], 'v')

    return out