示例#1
0
文件: roms.py 项目: bssrdf/okean
  def load(self):
    # time:
    vars={'time':('bulk_time','time','scrum_time','ocean_time')},

    self.load_vars(vars)

    # netcdf time:
    try:
      # units must have the format <units> since <date>
      self.time=netcdf.num2date(self.time,self.var_as['time']['units'])
    except: pass
示例#2
0
文件: roms.py 项目: AndreLobato/okean
  def load(self):
    # time:
    vars={'time':('bulk_time','time','scrum_time','ocean_time')},

    self.load_vars(vars)

    # netcdf time:
    try:
      # units must have the format <units> since <date>
      self.time=netcdf.num2date(self.time,self.var_as['time']['units'])
    except: pass
示例#3
0
  def load(self):
    # time:
    vars={'time':('time','ocean_time','scrum_time','clim_time')},
    self.load_vars(vars)

    # time:
    try:
      # units must have the format <units> since <date>
      self.time=netcdf.num2date(self.time,self.var_as['time']['units'])
    except: pass

    # s params:
    self.s_params=rt.s_params(self.nc)
示例#4
0
文件: roms.py 项目: AndreLobato/okean
  def load(self):
    # time:
    vars={'time':('time','ocean_time','scrum_time','clim_time')},
    self.load_vars(vars)

    # time:
    try:
      # units must have the format <units> since <date>
      self.time=netcdf.num2date(self.time,self.var_as['time']['units'])
    except: pass

    # s params:
    self.s_params=rt.s_params(self.nc)
示例#5
0
def frc2gnome(fname, frc, grd, xylim=False, dates=False, ij=(1, 1), **kargs):
    '''
  Creates GNOME wind file
  kargs:
    t[u,v]var
    t[u,v]dim
    x[y,ang]var

  Ex:
    .frc2gnome(out,frc,grd,ij=(10,10),dates=dates,**{'tdim':'Time'})
  '''

    deta, dxi = ij

    tvar = 'time'
    uvar = 'Uwind'
    vvar = 'Vwind'
    #tvar='bulk_time'
    #uvar='uwnd'
    #vvar='vwnd'

    tdim = 'time'
    #tdim='bulk_time'
    xdim = 'xi_rho'
    ydim = 'eta_rho'

    xvar = 'lon_rho'
    yvar = 'lat_rho'
    angvar = 'angle'

    if 'tvar' in kargs.keys(): tvar = kargs['tvar']
    if 'uvar' in kargs.keys(): uvar = kargs['uvar']
    if 'vvar' in kargs.keys(): vvar = kargs['vvar']

    if 'tdim' in kargs.keys(): tdim = kargs['tdim']
    if 'xdim' in kargs.keys(): xdim = kargs['xdim']
    if 'ydim' in kargs.keys(): ydim = kargs['ydim']

    if 'xvar' in kargs.keys(): xvar = kargs['xvar']
    if 'yvar' in kargs.keys(): yvar = kargs['yvar']
    if 'angvar' in kargs.keys(): angvar = kargs['angvar']

    dims = netcdf.fdim(grd)
    xi, eta = dims[xdim], dims[ydim]
    xi0, eta0 = xi, eta

    ncg = netcdf.ncopen(grd)

    nc0 = netcdf.ncopen(frc)
    try:
        t = netcdf.nctime(nc0, tvar)
    except:
        t = netcdf.use(nc0, tvar)
        t = netcdf.num2date(t, 'days since %d-01-01' % year0)

    time = netcdf.date2num(t, tunits)

    x0 = netcdf.use(grd, xvar)
    y0 = netcdf.use(grd, yvar)
    if x0.ndim == 1: x0, y0 = np.meshgrid(x0, y0)

    if angvar:
        ang = netcdf.use(grd, angvar)

    if not xylim is False:
        xlim = xylim[:2]
        ylim = xylim[2:]
        i1, i2, j1, j2 = calc.ij_limits(x0, y0, xlim, ylim)
        xi = i2 - i1
        eta = j2 - j1
    else:
        i1, i2 = 0, xi
        j1, j2 = 0, eta

    XI = '%d:%d:%d' % (i1, i2, dxi)
    ETA = '%d:%d:%d' % (j1, j2, deta)

    xi = len(range(i1, i2, dxi))
    eta = len(range(j1, j2, deta))

    # create file:
    create_wind(fname, xi, eta)

    nc = netcdf.ncopen(fname, 'a')

    x = x0[j1:j2:deta, i1:i2:dxi]
    y = y0[j1:j2:deta, i1:i2:dxi]

    nc.vars['lon'][:] = x
    nc.vars['lat'][:] = y
    if angvar: ang = ang[j1:j2:deta, i1:i2:dxi]

    n = -1
    for it in range(len(time)):

        if not dates is False:
            d0, d1 = dates
            if t[it] < d0 or t[it] >= d1: continue

        n += 1
        u = netcdf.use(nc0, uvar, **{xdim: XI, ydim: ETA, tdim: it})
        v = netcdf.use(nc0, vvar, **{xdim: XI, ydim: ETA, tdim: it})

        # rotate uv:
        if angvar:
            print('rotating ...')
            u, v = calc.rot2d(u, v, -ang)

        nc.vars['time'][n] = time[it]
        print('filling uv', n, t[it])
        nc.vars['air_u'][n, ...] = u
        nc.vars['air_v'][n, ...] = v

    nc.close()
    nc0.close()
    ncg.close()
示例#6
0
def load_data(f,quiet=0,**kargs):
  '''
  Loads prognostic variables (temp,salt,u,v,ubar,vbar,zeta) from
  netcdf file or opendap server. Also loads lon,lat, depth, and time.

  If f is a file, it must include the 1d variables lon,lat and depth;
  the 2d variable ssh (zeta) and the 3d variables temp, salt, u and v;
  ie, each file must contain data for a simgle time. The file must also
  contain the variable time.

  If f is a opendap address, it must contain also all these variables
  or the ones defined in the input karg settings (DataAccess object)

  To deal with variables in different files/opendap addresses, f can
  also be a dictionary with keys the variables and values the files
  or opendap addresses. In this case, the keys must be:
    - temp
    - salt
    - u
    - v
    - ssh
    - misc, for lon, lat, depth, time and dimensions
      or xy for lon,lat and x,ydim; z for depth and zdim, time for time

  The output data (dict) is suitable to be used by data2roms, which
  interpolates the data to ROMS 3d grid.
  Also outputs an error/status string.

  kargs:
    inds, dict with dimension names/values (where time dim can be integer
          or datetime)
    settings, DataAccess object
    extra, extra misc vars to load [(outKey0,fileVar0),...]
    t_units, units of variable time, by default the att  units is used
  '''

  sett    = kargs.get('settings',DataAccess())
  inds    = kargs.get('inds',{})
  extra   = kargs.get('extra',[])
  t_units = kargs.get('t_units',[])

  res={}
  msg=''

  if not isinstance(f,dict) and not f.startswith('http') and not isfile(f):
    msg='file not found %s' % f
    if not quiet: print(msg)
    return res, msg

  # load nc files:
  if not isinstance(f,dict):
    f={'temp':f,'salt':f,'u':f,'v':f,'ssh':f,'misc':f}

  if 'xy'   not in f: f['xy']   = f['misc']
  if 'z'    not in f: f['z']    = f['misc']
  if 'time' not in f: f['time'] = f['misc']

  filesUsed=[]
  ncUsed=[]
  for i in f.keys():
    if not quiet: print('(%s) loading from %s' % (i.ljust(5),f[i]))

    if i=='temp':
      if f[i] in filesUsed: ncTemp=ncUsed[filesUsed.index(f[i])]
      else:
        ncTemp=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncTemp]

    elif i=='salt':
      if f[i] in filesUsed: ncSalt=ncUsed[filesUsed.index(f[i])]
      else:
        ncSalt=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncSalt]

    elif i=='u':
      if f[i] in filesUsed: ncU=ncUsed[filesUsed.index(f[i])]
      else:
        ncU=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncU]

    elif i=='v':
      if f[i] in filesUsed: ncV=ncUsed[filesUsed.index(f[i])]
      else:
        ncV=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncV]

    elif i=='ssh':
      if f[i] in filesUsed: ncSsh=ncUsed[filesUsed.index(f[i])]
      else:
        ncSsh=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncSsh]

    elif i=='xy':
      if f[i] in filesUsed: ncXy=ncUsed[filesUsed.index(f[i])]
      else:
        ncXy=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncXy]

    elif i=='z':
      if f[i] in filesUsed: ncZ=ncUsed[filesUsed.index(f[i])]
      else:
        ncZ=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncZ]

    elif i=='time':
      if f[i] in filesUsed: ncTime=ncUsed[filesUsed.index(f[i])]
      else:
        ncTime=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncTime]

    elif i=='misc':
      if f[i] in filesUsed: ncMisc=ncUsed[filesUsed.index(f[i])]
      else:
        ncMisc=netcdf.ncopen(f[i])
        filesUsed+=[f[i]]
        ncUsed+=[ncMisc]


  # load dims:
  if not quiet: print('  loading dims...')
  dimsXy=netcdf.fdim(ncXy)
  dimsZ =netcdf.fdim(ncZ)

  res['NX']=dimsXy[sett.xdim]
  res['NY']=dimsXy[sett.ydim]
  if sett.zdim:
    res['NZ']=dimsZ[sett.zdim]
  else:
    res['NZ']=1

  # about horizontal inds:
  if sett.xdim in inds and len(inds[sett.xdim])==2 and not isinstance(inds[sett.xdim],basestring):
    if not quiet: print('  calc horizontal inds...')
    xlim=inds[sett.xdim]
    ylim=inds[sett.ydim]

    inds.pop(sett.xdim)
    inds.pop(sett.ydim)

    lon=netcdf.use(ncXy,sett.x_name,**inds)
    if np.any(lon>360): lon=np.mod(lon,360.)
    lat=netcdf.use(ncXy,sett.y_name,**inds)
    i0,i1,j0,j1=calc.ij_limits(lon,lat,xlim,ylim,margin=3)
    inds[sett.xdim]='%d:%d' % (i0,i1)
    inds[sett.ydim]='%d:%d' % (j0,j1)


  # about time dim:
  # file may have one or several times. If several, time dim must be given
  # with kargs inds!
  # but file may also have no time dim or time name !
  if sett.time_name:
    if not quiet: print('  loading time...')
    if t_units:
      times=netcdf.use(ncTime,sett.time_name)
      times=netcdf.num2date(times,t_units)
    else:
      times=netcdf.nctime(ncTime,sett.time_name)

    if sett.tdim in inds:
      try: tind=dateu.parse_date(inds[sett.tdim])
      except: tind=inds[sett.tdim] # is an integer, for instance

      if isinstance(tind,datetime.datetime):
        tind,=np.where(times==tind)
        if tind.size:
          tind=tind[0]
          inds[sett.tdim]=tind # update inds to extract other variables
        else:
          Msg='date not found'
          msg+='\n'+Msg
          return res,msg+' ERROR'

      date=times[tind]
      try:
        len(date)
        ndates=True
      except: ndates=False

      if ndates:
        if not quiet: print('    tind, date= len=%d: %d to %d, %s to %s' % (len(date),tind[0],tind[-1],date[0].isoformat(' '),date[-1].isoformat(' ')))
      else:
        if not quiet: print('    tind, date= %d %s' % (tind,date.isoformat(' ')))

    elif times.size==1:
      date=times[0]
      if not quiet: print('    date= %s' % date.isoformat(' '))
    else: # must provide tind as input!!
      Msg='several dates in file... provide tind!'
      msg+='\n'+Msg
      return res,msg+' ERROR'

    res['date'] = date
  else:
    if not quiet: print('    warning: not using time !!')
    res['date']=0


  # load lon,lat, depth:
  if not quiet: print('  loading lon, lat, depth...')
  res['lon']  = netcdf.use(ncXy,sett.x_name,**inds)
  if np.any(res['lon']>360): res['lon']=np.mod(res['lon'],360.)
  res['lat']  = netcdf.use(ncXy,sett.y_name,**inds)
  if sett.z_name:
    res['depth'] = -netcdf.use(ncZ,sett.z_name,**inds)
  else: res['depth']=False

  if res['lon'].size!=res['lat'].size:
    res['lon'],res['lat']=np.meshgrid(res['lon'],res['lat'])
    # needed for griddata, later

  # update nx,ny:
  if sett.xdim in inds:
    res['NY'],res['NX']=res['lon'].shape

  # load surface variables as extra (from misc file) for now.
  # (this should be basically never used!)
  if sett.ss_temp_name: extra+=[['ss_temp',sett.ss_temp_name]]
  if sett.ss_salt_name: extra+=[['ss_salt',sett.ss_salt_name]]
  if sett.ss_u_name:    extra+=[['ss_u',   sett.ss_u_name]]
  if sett.ss_v_name:    extra+=[['ss_v',   sett.ss_v_name]]

  # extra misc vars:
  if len(extra):
    for outKey,fileVar in extra:
      if not quiet: print('  loading extra misc... %s %s' % (outKey,fileVar))
      res[outKey]=netcdf.use(ncMisc,fileVar,**inds)



  empty3d=np.zeros([res['NZ'],res['NY'],res['NX']])
  empty2d=np.zeros([res['NY'],res['NX']])

  if 'temp' in f.keys():
    if not quiet: print('  loading temp...')
    if sett.temp_name in ncTemp.varnames: res['temp'] = netcdf.use(ncTemp,sett.temp_name,**inds)
    else:
      Msg='var %s not found' % 'temp'
      msg+='\n'+Msg
      if not quiet: print(Msg)
      res['temp']=empty3d

  if 'salt' in f.keys():
    if not quiet: print('  loading salt...')
    if sett.salt_name in ncSalt.varnames: res['salt'] = netcdf.use(ncSalt,sett.salt_name,**inds)
    else:
      Msg='var %s not found' % 'salt'
      msg+='\n'+Msg
      if not quiet: print(Msg)
      res['salt']=empty3d

  if 'u' in f.keys():
    if not quiet: print('  loading u...')
    if sett.u_name in ncU.varnames: res['u']    = netcdf.use(ncU,sett.u_name,**inds)
    else:
      Msg='var %s not found' % 'u'
      msg+='\n'+Msg
      if not quiet: print(Msg)
      res['u']=empty3d

  if 'v' in f.keys():
    if not quiet: print('  loading v...')
    if sett.v_name in ncV.varnames: res['v']    = netcdf.use(ncV,sett.v_name,**inds)
    else:
      Msg='var %s not found' % 'v'
      msg+='\n'+Msg
      if not quiet: print(Msg)
      res['v']=empty3d

  if 'ssh' in f.keys():
    if not quiet: print('  loading ssh...')
    if sett.ssh_name in ncSsh.varnames: res['ssh']  = netcdf.use(ncSsh,sett.ssh_name,**inds)
    else:
      Msg='var %s not found' % 'ssh'
      msg+='\n'+Msg
      if not quiet: print(Msg)
      res['ssh']=empty2d

  for nc in ncUsed:
    try:  nc.close()
    except: pass

  return res, msg
示例#7
0
文件: gnome.py 项目: jcmt/okean
def frc2gnome(fname,frc,grd,xylim=False,dates=False,ij=(1,1),**kargs):
  '''
  Creates GNOME wind file
  kargs:
    t[u,v]var
    t[u,v]dim
    x[y,ang]var

  Ex:
    .frc2gnome(out,frc,grd,ij=(10,10),dates=dates,**{'tdim':'Time'})
  '''

  deta,dxi=ij

  tvar='time'
  uvar='Uwind'
  vvar='Vwind'
  #tvar='bulk_time'
  #uvar='uwnd'
  #vvar='vwnd'

  tdim='time'
  #tdim='bulk_time'
  xdim='xi_rho'
  ydim='eta_rho'

  xvar='lon_rho'
  yvar='lat_rho'
  angvar='angle'

  if 'tvar' in kargs.keys(): tvar=kargs['tvar']
  if 'uvar' in kargs.keys(): uvar=kargs['uvar']
  if 'vvar' in kargs.keys(): vvar=kargs['vvar']

  if 'tdim' in kargs.keys(): tdim=kargs['tdim']
  if 'xdim' in kargs.keys(): xdim=kargs['xdim']
  if 'ydim' in kargs.keys(): ydim=kargs['ydim']

  if 'xvar' in kargs.keys(): xvar=kargs['xvar']
  if 'yvar' in kargs.keys(): yvar=kargs['yvar']
  if 'angvar' in kargs.keys(): angvar=kargs['angvar']


  dims=netcdf.fdim(grd)
  xi,eta=dims[xdim],dims[ydim]
  xi0,eta0=xi,eta

  ncg=netcdf.ncopen(grd)

  nc0=netcdf.ncopen(frc)
  try:
   t=netcdf.nctime(nc0,tvar)
  except:
    t=netcdf.use(nc0,tvar)
    t=netcdf.num2date(t,'days since %d-01-01' % year0)

  time=netcdf.date2num(t,tunits)

  x0=netcdf.use(grd,xvar)
  y0=netcdf.use(grd,yvar)
  if x0.ndim==1: x0,y0=np.meshgrid(x0,y0)

  if angvar:
    ang=netcdf.use(grd,angvar)

  if not xylim is False:
    xlim=xylim[:2]
    ylim=xylim[2:]
    i1,i2,j1,j2=calc.ij_limits(x0,y0,xlim,ylim)
    xi=i2-i1
    eta=j2-j1
  else:
    i1,i2=0,xi
    j1,j2=0,eta

  XI  ='%d:%d:%d' %(i1,i2,dxi)
  ETA ='%d:%d:%d' %(j1,j2,deta)

  xi=len(range(i1,i2,dxi))
  eta=len(range(j1,j2,deta))

  # create file:
  create_wind(fname,xi,eta)

  nc=netcdf.ncopen(fname,'a')

  x=x0[j1:j2:deta,i1:i2:dxi]
  y=y0[j1:j2:deta,i1:i2:dxi]

  nc.vars['lon'][:]=x
  nc.vars['lat'][:]=y
  if angvar: ang=ang[j1:j2:deta,i1:i2:dxi]

  n=-1
  for it in range(len(time)):

    if not dates is False:
      d0,d1=dates
      if t[it]<d0 or t[it]>=d1: continue

    n+=1
    u=netcdf.use(nc0,uvar,**{xdim:XI,ydim:ETA,tdim:it})
    v=netcdf.use(nc0,vvar,**{xdim:XI,ydim:ETA,tdim:it})

    # rotate uv:
    if angvar:
      print 'rotating ...'
      u,v=calc.rot2d(u,v,-ang)


    nc.vars['time'][n]=time[it]
    print 'filling uv',n,t[it]
    nc.vars['air_u'][n,...]=u
    nc.vars['air_v'][n,...]=v


  nc.close()
  nc0.close()
  ncg.close()
示例#8
0
def load_data(f, quiet=0, **kargs):
    '''
  Loads prognostic variables (temp,salt,u,v,ubar,vbar,zeta) from
  netcdf file or opendap server. Also loads lon,lat, depth, and time.

  If f is a file, it must include the 1d variables lon,lat and depth;
  the 2d variable ssh (zeta) and the 3d variables temp, salt, u and v;
  ie, each file must contain data for a simgle time. The file must also
  contain the variable time.

  If f is a opendap address, it must contain also all these variables
  or the ones defined in the input karg settings (DataAccess object)

  To deal with the case of variables in different files/opendap addresses,
  f can also be a dictionary with keys the variables and values the files
  or opendap addresses. In this case, the keys must be:
    - temp
    - salt
    - u
    - v
    - ssh
    - misc, for lon, lat, depth, time and dimensions
      or xy for lon,lat and x,ydim; z for depth and zdim, time for time

  The output data (dict) is suitable to be used by data2roms, which
  interpolates the data to ROMS 3d grid.
  Also outputs an error/status string.

  kargs:
    inds, dict with dimension names/values (where time dim can be integer
          or datetime)
    settings, DataAccess object
    extra, extra misc vars to load [(outKey0,fileVar0),...]
    t_units, units of variable time, by default the att  units is used
  '''

    sett = DataAccess()
    inds = {}
    extra = []
    t_units = []
    if 'settings' in kargs.keys(): sett = kargs['settings']
    if 'inds' in kargs.keys(): inds = kargs['inds']
    if 'extra' in kargs.keys(): extra = kargs['extra']
    if 't_units' in kargs.keys(): t_units = kargs['t_units']

    res = {}
    msg = ''

    if not isinstance(f, dict) and not f.startswith('http') and not isfile(f):
        msg = 'file not found %s' % f
        if not quiet: print msg
        return res, msg

    # load nc files:
    if not isinstance(f, dict):
        f = {'temp': f, 'salt': f, 'u': f, 'v': f, 'ssh': f, 'misc': f}

    if not f.has_key('xy'): f['xy'] = f['misc']
    if not f.has_key('z'): f['z'] = f['misc']
    if not f.has_key('time'): f['time'] = f['misc']

    filesUsed = []
    ncUsed = []
    for i in f.keys():
        if not quiet: print '(%s) loading from %s' % (i.ljust(5), f[i])

        if i == 'temp':
            if f[i] in filesUsed: ncTemp = ncUsed[filesUsed.index(f[i])]
            else:
                ncTemp = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncTemp]

        elif i == 'salt':
            if f[i] in filesUsed: ncSalt = ncUsed[filesUsed.index(f[i])]
            else:
                ncSalt = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncSalt]

        elif i == 'u':
            if f[i] in filesUsed: ncU = ncUsed[filesUsed.index(f[i])]
            else:
                ncU = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncU]

        elif i == 'v':
            if f[i] in filesUsed: ncV = ncUsed[filesUsed.index(f[i])]
            else:
                ncV = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncV]

        elif i == 'ssh':
            if f[i] in filesUsed: ncSsh = ncUsed[filesUsed.index(f[i])]
            else:
                ncSsh = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncSsh]

        elif i == 'xy':
            if f[i] in filesUsed: ncXy = ncUsed[filesUsed.index(f[i])]
            else:
                ncXy = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncXy]

        elif i == 'z':
            if f[i] in filesUsed: ncZ = ncUsed[filesUsed.index(f[i])]
            else:
                ncZ = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncZ]

        elif i == 'time':
            if f[i] in filesUsed: ncTime = ncUsed[filesUsed.index(f[i])]
            else:
                ncTime = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncTime]

        elif i == 'misc':
            if f[i] in filesUsed: ncMisc = ncUsed[filesUsed.index(f[i])]
            else:
                ncMisc = netcdf.ncopen(f[i])
                filesUsed += [f[i]]
                ncUsed += [ncMisc]

    # load dims:
    if not quiet: print '  loading dims...'
    dimsXy = netcdf.fdim(ncXy)
    dimsZ = netcdf.fdim(ncZ)

    res['NX'] = dimsXy[sett.xdim]
    res['NY'] = dimsXy[sett.ydim]
    ###if sett.z_name:
    if sett.zdim:
        res['NZ'] = dimsZ[sett.zdim]
    else:
        res['NZ'] = 1

    # about horizontal inds:
    if inds.has_key(
            sett.xdim) and len(inds[sett.xdim]) == 2 and not isinstance(
                inds[sett.xdim], basestring):
        if not quiet: print '  calc horizontal inds...'
        xlim = inds[sett.xdim]
        ylim = inds[sett.ydim]

        inds.pop(sett.xdim)
        inds.pop(sett.ydim)

        lon = netcdf.use(ncXy, sett.x_name, **inds)
        if np.any(lon > 360): lon = np.mod(lon, 360.)
        lat = netcdf.use(ncXy, sett.y_name, **inds)
        i0, i1, j0, j1 = calc.ij_limits(lon, lat, xlim, ylim, margin=3)
        inds[sett.xdim] = '%d:%d' % (i0, i1)
        inds[sett.ydim] = '%d:%d' % (j0, j1)

    if not quiet: print '  loading lon, lat, depth...'
    res['lon'] = netcdf.use(ncXy, sett.x_name, **inds)
    if np.any(res['lon'] > 360): res['lon'] = np.mod(res['lon'], 360.)
    res['lat'] = netcdf.use(ncXy, sett.y_name, **inds)
    if sett.z_name:
        res['depth'] = -netcdf.use(ncZ, sett.z_name, **inds)
    else:
        res['depth'] = False

    if res['lon'].size != res['lat'].size:
        res['lon'], res['lat'] = np.meshgrid(res['lon'], res['lat'])
        # needed for griddata, later

    # update nx,ny:
    if inds.has_key(sett.xdim):
        res['NY'], res['NX'] = res['lon'].shape

    # extra misc vars:
    if len(extra):
        for outKey, fileVar in extra:
            if not quiet:
                print '  loading extra misc... %s %s' % (outKey, fileVar)
            res[outKey] = netcdf.use(ncMisc, fileVar, **inds)

    # time:
    # file may have one or several times. If several, time dim must be given
    # with kargs inds!
    # but file may also have no time dim or time name !
    if sett.time_name:
        if not quiet: print '  loading time...'
        if t_units:
            times = netcdf.use(ncTime, sett.time_name)
            times = netcdf.num2date(times, t_units)
        else:
            times = netcdf.nctime(ncTime, sett.time_name)

        if inds.has_key(sett.tdim):
            try:
                tind = dts.parse_date(inds[sett.tdim])
            except:
                tind = inds[sett.tdim]  # is an integer, for instance

            if isinstance(tind, datetime.datetime):
                tind, = np.where(times == tind)
                if tind.size:
                    tind = tind[0]
                    inds[sett.
                         tdim] = tind  # update inds to extract other variables
                else:
                    Msg = 'date not found'
                    msg += '\n' + Msg
                    return res, msg + ' ERROR'

            date = times[tind]
            try:
                len(date)
                ndates = True
            except:
                ndates = False

            if ndates:
                if not quiet:
                    print '    tind, date= len=%d: %d to %d, %s to %s' % (
                        len(date), tind[0], tind[-1], date[0].isoformat(' '),
                        date[-1].isoformat(' '))
            else:
                if not quiet:
                    print '    tind, date= %d %s' % (tind, date.isoformat(' '))

        elif times.size == 1:
            date = times[0]
            if not quiet: print '    date= %s' % date.isoformat(' ')
        else:  # must provide tind as input!!
            Msg = 'several dates in file... provice tind!'
            msg += '\n' + Msg
            return res, msg + ' ERROR'

        res['date'] = date
    else:
        if not quiet: print '    warning: not using time !!'
        res['date'] = 0

    empty3d = np.zeros([res['NZ'], res['NY'], res['NX']])
    empty2d = np.zeros([res['NY'], res['NX']])

    if 'temp' in f.keys():
        if not quiet: print '  loading temp...'
        if sett.temp_name in ncTemp.varnames:
            res['temp'] = netcdf.use(ncTemp, sett.temp_name, **inds)
        else:
            Msg = 'var %s not found' % 'temp'
            msg += '\n' + Msg
            if not quiet: print Msg
            res['temp'] = empty3d

    if 'salt' in f.keys():
        if not quiet: print '  loading salt...'
        if sett.salt_name in ncSalt.varnames:
            res['salt'] = netcdf.use(ncSalt, sett.salt_name, **inds)
        else:
            Msg = 'var %s not found' % 'salt'
            msg += '\n' + Msg
            if not quiet: print Msg
            res['salt'] = empty3d

    if 'u' in f.keys():
        if not quiet: print '  loading u...'
        if sett.u_name in ncU.varnames:
            res['u'] = netcdf.use(ncU, sett.u_name, **inds)
        else:
            Msg = 'var %s not found' % 'u'
            msg += '\n' + Msg
            if not quiet: print Msg
            res['u'] = empty3d

    if 'v' in f.keys():
        if not quiet: print '  loading v...'
        if sett.v_name in ncV.varnames:
            res['v'] = netcdf.use(ncV, sett.v_name, **inds)
        else:
            Msg = 'var %s not found' % 'v'
            msg += '\n' + Msg
            if not quiet: print Msg
            res['v'] = empty3d

    if 'ssh' in f.keys():
        if not quiet: print '  loading ssh...'
        if sett.ssh_name in ncSsh.varnames:
            res['ssh'] = netcdf.use(ncSsh, sett.ssh_name, **inds)
        else:
            Msg = 'var %s not found' % 'ssh'
            msg += '\n' + Msg
            if not quiet: print Msg
            res['ssh'] = empty2d

    for nc in ncUsed:
        try:
            nc.close()
        except:
            pass

    return res, msg