Ejemplo n.º 1
0
def main(cmdLineArgs,stream=None):
  numpy.seterr(divide='ignore', invalid='ignore', over='ignore') # To avoid warnings

  if not os.path.exists(cmdLineArgs.gridspec): raise ValueError('Specified gridspec directory/tar file does not exist.')
  if os.path.isdir(cmdLineArgs.gridspec):
    x = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['x'][::2,::2]
    xcenter = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['x'][1::2,1::2]
    y = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['y'][::2,::2]
    ycenter = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['y'][1::2,1::2]
    msk = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_mask.nc').variables['mask'][:]
    area = msk*netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['area'][:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
    depth = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_topog.nc').variables['depth'][:]
  elif os.path.isfile(cmdLineArgs.gridspec):
    x = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','x')[::2,::2]
    xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','x')[1::2,1::2]
    y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','y')[::2,::2]
    ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','y')[1::2,1::2]
    msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_mask.nc','mask')[:]
    area = msk*m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','area')[:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
    depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_topog.nc','depth')[:]
  else:
    raise ValueError('Unable to extract grid information from gridspec directory/tar file.') 
  
  
  Sobs = netCDF4.Dataset( cmdLineArgs.woa ).variables['salt']
  if len(Sobs.shape)==3: Sobs = Sobs[0]
  else: Sobs = Sobs[:,0].mean(axis=0)

  rootGroup = netCDF4.MFDataset( cmdLineArgs.annual_file )
  if 'salt' in rootGroup.variables: varName = 'salt'
  elif 'so' in rootGroup.variables: varName = 'so'
  else: raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.annual_file))
  if rootGroup.variables[varName].shape[0]>1: Smod = rootGroup.variables[varName][:,0].mean(axis=0)
  else: Smod = rootGroup.variables[varName][0,0]
  
  if cmdLineArgs.suptitle != '':  suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
  else: suptitle = rootGroup.title + ' ' + cmdLineArgs.label

  ci=m6plot.pmCI(0.125,2.25,.25)
  if stream is None: stream = cmdLineArgs.outdir+'/SSS_bias_WOA05.png'
  m6plot.xyplot( Smod - Sobs , x, y, area=area,
      suptitle=suptitle, title='SSS bias (w.r.t. WOA\'05) [ppt]',
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=stream)
  
  m6plot.xycompare( Smod, Sobs , x, y, area=area,
      suptitle=suptitle,
      title1='SSS [ppt]',
      title2='WOA\'05 SSS [ppt]',
      clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
      dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
      save=cmdLineArgs.outdir+'/SSS_bias_WOA05.3_panel.png')
Ejemplo n.º 2
0
def main(cmdLineArgs, stream=False):
    numpy.seterr(divide='ignore', invalid='ignore',
                 over='ignore')  # To avoid warnings

    if not os.path.exists(cmdLineArgs.gridspec):
        raise ValueError(
            'Specified gridspec directory/tar file does not exist.')
    if os.path.isdir(cmdLineArgs.gridspec):
        x = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['x'][::2, ::2]
        xcenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['x'][1::2, 1::2]
        y = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['y'][::2, ::2]
        ycenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['y'][1::2, 1::2]
        msk = netCDF4.Dataset(cmdLineArgs.gridspec +
                              '/ocean_mask.nc').variables['mask'][:]
        area = msk * netCDF4.Dataset(
            cmdLineArgs.gridspec +
            '/ocean_hgrid.nc').variables['area'][:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = netCDF4.Dataset(cmdLineArgs.gridspec +
                                '/ocean_topog.nc').variables['depth'][:]
    elif os.path.isfile(cmdLineArgs.gridspec):
        x = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'x')[::2, ::2]
        xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'x')[1::2, 1::2]
        y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'y')[::2, ::2]
        ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'y')[1::2, 1::2]
        msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_mask.nc',
                                      'mask')[:]
        area = msk * m6toolbox.readNCFromTar(
            cmdLineArgs.gridspec, 'ocean_hgrid.nc', 'area')[:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_topog.nc',
                                        'depth')[:]
    else:
        raise ValueError(
            'Unable to extract grid information from gridspec directory/tar file.'
        )

    Tobs = netCDF4.Dataset(cmdLineArgs.woa)
    if 'temp' in Tobs.variables: Tobs = Tobs.variables['temp']
    elif 'ptemp' in Tobs.variables: Tobs = Tobs.variables['ptemp']
    else:
        raise Exception('Could not find "temp" or "ptemp" in file "%s"' %
                        (cmdLineArgs.woa))
    if len(Tobs.shape) == 3: Tobs = Tobs[0]
    else: Tobs = Tobs[:, 0].mean(axis=0)

    rootGroup = netCDF4.MFDataset(cmdLineArgs.infile)
    if 'temp' in rootGroup.variables: varName = 'temp'
    elif 'ptemp' in rootGroup.variables: varName = 'ptemp'
    elif 'thetao' in rootGroup.variables: varName = 'thetao'
    else:
        raise Exception(
            'Could not find "temp", "ptemp" or "thetao" in file "%s"' %
            (cmdLineArgs.infile))
    if rootGroup.variables[varName].shape[0] > 1:
        Tmod = rootGroup.variables[varName][:, 0].mean(axis=0)
    else:
        Tmod = rootGroup.variables[varName][0, 0]

    if cmdLineArgs.suptitle != '':
        suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
    else:
        suptitle = rootGroup.title + ' ' + cmdLineArgs.label

    imgbufs = []
    ci = m6plot.pmCI(0.25, 4.5, .5)
    if stream is True: img = io.BytesIO()
    else: img = cmdLineArgs.outdir + '/SST_bias_WOA05.png'
    m6plot.xyplot(Tmod - Tobs,
                  x,
                  y,
                  area=area,
                  suptitle=suptitle,
                  title='SST bias (w.r.t. WOA\'05) [$\degree$C]',
                  clim=ci,
                  colormap='dunnePM',
                  centerlabels=True,
                  extend='both',
                  save=img)
    if stream is True: imgbufs.append(img)

    m6plot.xycompare(Tmod,
                     Tobs,
                     x,
                     y,
                     area=area,
                     suptitle=suptitle,
                     title1='SST [$\degree$C]',
                     title2='WOA\'05 SST [$\degree$C]',
                     clim=m6plot.linCI(-2, 29, .5),
                     colormap='dunneRainbow',
                     extend='max',
                     dlim=ci,
                     dcolormap='dunnePM',
                     dextend='both',
                     centerdlabels=True,
                     save=cmdLineArgs.outdir + '/SST_bias_WOA05.3_panel.png')

    if stream is True:
        return imgbufs
Ejemplo n.º 3
0
    Zref[k+1] = numpy.maximum( Zref[k] - abs(zw[k+1] - zw[k]), D)

rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'salt' in rootGroup.variables: varName = 'salt'
elif 'so' in rootGroup.variables: varName = 'so'
else: raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.annual_file))
if len(rootGroup.variables[varName].shape)==4: Smod = rootGroup.variables[varName][:].mean(axis=0)
else: Smod = rootGroup.variables[varName][:]
if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
else: Zmod = Zref

def zonalAverage(T, eta, area, mask=1.):
  vols = ( mask * area ) * ( eta[:-1] - eta[1:] ) # mask * area * level thicknesses
  return numpy.sum( vols * T, axis=-1 ) / numpy.sum( vols, axis=-1 ), (mask*eta).min(axis=-1)

ci=m6plot.pmCI(0.0125,.225,.025)
if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

# Global
sPlot, z = zonalAverage(Smod, Zmod, area)
sRefPlot, _ = zonalAverage(Sref, Zref, area)
m6plot.yzplot( sPlot - sRefPlot , y, z, splitscale=[0., -1000., -6500.],
      suptitle=title1+' - '+title2, title='''Global zonal-average salinity response [ppt] '''+cmdLineArgs.label,
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/S_global_xave_response.png')

m6plot.yzcompare( sPlot, sRefPlot , y, z, splitscale=[0., -1000., -6500.],
      suptitle='Global zonal-average salinity [ppt] '+cmdLineArgs.label,
Ejemplo n.º 4
0
MLDref = variable[:].reshape(shape[0]/12,12,shape[1],shape[2]).mean(axis=0)

rootGroup = netCDF4.Dataset( cmdLineArgs.monthly_file )
if 'MLD_003' not in rootGroup.variables: raise Exception('Could not find "MLD_003" in file "%s"'%(cmdLineArgs.monthly_file))
variable = rootGroup.variables['MLD_003']
shape = variable.shape
MLDmod = variable[:].reshape(shape[0]/12,12,shape[1],shape[2]).mean(axis=0)

if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

ciMin = m6plot.linCI(0,95,5)
ciMax = m6plot.linCI(0,680,20)
diMin = m6plot.pmCI(2.5,32.5,5)
diMax = m6plot.pmCI(0,20,5, 40,100,20)
diMax = numpy.array([-250,-200,-150,-100,-50,-20,-10,-3,3,10,20,50,100,150,200,250])

m6plot.xyplot( MLDmod.min(axis=0) - MLDref.min(axis=0), x, y, area=area,
      suptitle=title1+' - '+title2,
      title='MLD difference [m] '+cmdLineArgs.label,
      clim=diMin, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/MLD_minimum_difference.png')

m6plot.xycompare( MLDmod.min(axis=0), MLDref.min(axis=0), x, y, area=area,
      suptitle='MLD difference [m] '+cmdLineArgs.label,
      title1=title1, title2=title2,
      clim=ciMin, colormap='dunneRainbow', extend='max',
      dlim=diMin, dcolormap='dunnePM', dextend='both', centerdlabels=True,
      save=cmdLineArgs.outdir+'/MLD_minimum_difference.3_panel.png')
Ejemplo n.º 5
0
if 'salt' in rootGroup.variables: varName = 'salt'
elif 'so' in rootGroup.variables: varName = 'so'
else:
    raise Exception('Could not find "salt" or "so" in file "%s"' %
                    (cmdLineArgs.annual_file))
if len(rootGroup.variables[varName].shape) == 4:
    Smod = rootGroup.variables[varName][:, 0].mean(axis=0)
else:
    Smod = rootGroup.variables[varName][0]

if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

ci = m6plot.pmCI(0.025, 0.525, .05)
m6plot.xyplot(Smod - Sref,
              x,
              y,
              area=area,
              suptitle=title1 + ' - ' + title2,
              title='SSS difference [ppt] ' + cmdLineArgs.label,
              clim=ci,
              colormap='dunnePM',
              centerlabels=True,
              extend='both',
              save=cmdLineArgs.outdir + '/SSS_difference.png')

m6plot.xycompare(Smod,
                 Sref,
                 x,
Ejemplo n.º 6
0
msk = numpy.ma.array(msk, mask=(msk==0))

Tobs = netCDF4.Dataset( cmdLineArgs.woa )
if 'temp' in Tobs.variables: Tobs = Tobs.variables['temp']
elif 'ptemp' in Tobs.variables: Tobs = Tobs.variables['ptemp']
else: raise Exception('Could not find "temp" or "ptemp" in file "%s"'%(cmdLineArgs.woa))
if len(Tobs.shape)==3: Tobs = Tobs[0]
else: Tobs = Tobs[:,0].mean(axis=0)

rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'temp' in rootGroup.variables: varName = 'temp'
elif 'ptemp' in rootGroup.variables: varName = 'ptemp'
elif 'thetao' in rootGroup.variables: varName = 'thetao'
else: raise Exception('Could not find "temp", "ptemp" or "thetao" in file "%s"'%(cmdLineArgs.annual_file))
if rootGroup.variables[varName].shape[0]>1: salt = rootGroup.variables[varName][:,0].mean(axis=0)
else: Tmod = rootGroup.variables[varName][0,0]

ci=m6plot.pmCI(0.25,4.5,.5)
m6plot.xyplot( Tmod - Tobs , x, y, area=area,
      suptitle=rootGroup.title+' '+cmdLineArgs.label, title='SST bias (w.r.t. WOA\'05) [$\degree$C]',
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/SST_bias_WOA05.png')

m6plot.xycompare( Tmod, Tobs , x, y, area=area,
      suptitle=rootGroup.title+' '+cmdLineArgs.label,
      title1='SST [$\degree$C]',
      title2='WOA\'05 SST [$\degree$C]',
      clim=m6plot.linCI(-2,29,.5), colormap='dunneRainbow', extend='max',
      dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
      save=cmdLineArgs.outdir+'/SST_bias_WOA05.3_panel.png')
obsRootGroup = netCDF4.Dataset( cmdLineArgs.woa )
if 'temp' in obsRootGroup.variables: OTvar = 'temp'
else: OTvar = 'ptemp'
Zobs = netCDF4.Dataset( cmdLineArgs.woa ).variables['eta']

rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'temp' in rootGroup.variables: varName = 'temp'
elif 'ptemp' in rootGroup.variables: varName = 'ptemp'
elif 'thetao' in rootGroup.variables: varName = 'thetao'
else: raise Exception('Could not find "temp", "ptemp" or "thetao" in file "%s"'%(cmdLineArgs.annual_file))
if len(rootGroup.variables[varName].shape)==4: need_time_average = True
else: need_time_average = False
if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e']
else: Zmod = Zobs # Using model z-output

ci=m6plot.pmCI(0.1,0.5,.2, 1.0,4.5,1.)

# Pacific equator
j = numpy.abs( y[:,0] - 0. ).argmin()
i0 = numpy.abs( numpy.mod( x[j,:] - 117. + 360., 360. ) ).argmin()
i1 = numpy.abs( numpy.mod( x[j,:] + 78. + 360., 360. ) ).argmin()
tPlot = rootGroup.variables[varName][0,:,j,i0:i1]
tObsPlot = obsRootGroup.variables[OTvar][0,:,j,i0:i1]
zi = Zobs[:,j,i0:i1]; z = 0.5 * ( zi[:-1] + zi[1:] )
m6plot.yzplot( tPlot - tObsPlot , x[j,i0:i1][:], zi,
      ylabel='Longitude',
      suptitle=rootGroup.title+' '+cmdLineArgs.label, title=r'''Pacific equator $\theta$ bias (w.r.t. WOA'05) [$\degree$C]''',
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both')
cs1 = plt.contour( x[j,i0:i1][:] + 0*z, z, tObsPlot, levels=numpy.arange(0.,45,2.), colors='k' ); plt.clabel(cs1,fmt='%.0f')
cs2 = plt.contour( x[j,i0:i1][:] + 0*z, z, tPlot, levels=numpy.arange(0.,45,2.), colors='g' ); plt.clabel(cs2,fmt='%.0f')
plt.ylim(-1200,0)
Ejemplo n.º 8
0
def main(cmdLineArgs,stream=None):
  if not os.path.exists(cmdLineArgs.gridspec): raise ValueError('Specified gridspec directory/tar file does not exist.')
  if os.path.isdir(cmdLineArgs.gridspec):
    xcenter = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['x'][1::2,1::2]
    y = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['y'][1::2,1::2].max(axis=-1)
    ycenter = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['y'][1::2,1::2]
    msk = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_mask.nc').variables['mask'][:]
    area = msk*netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['area'][:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
    depth = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_topog.nc').variables['depth'][:]
    try: basin = netCDF4.Dataset(cmdLineArgs.gridspec+'/basin_codes.nc').variables['basin'][:]
    except: basin = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
  elif os.path.isfile(cmdLineArgs.gridspec):
    xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','x')[1::2,1::2]
    y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','y')[1::2,1::2].max(axis=-1)
    ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','y')[1::2,1::2]
    msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_mask.nc','mask')[:]
    area = msk*m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','area')[:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
    depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_topog.nc','depth')[:]
    try: basin = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'basin_codes.nc','basin')[:]
    except: basin = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
  else:
    raise ValueError('Unable to extract grid information from gridspec directory/tar file.') 

  if stream != None:
    if len(stream) != 4:
      raise ValueError('If specifying output streams, exactly four (4) streams are needed for this analysis')

  Sobs = netCDF4.Dataset( cmdLineArgs.woa ).variables['salt']
  if len(Sobs.shape)==3: Sobs = Sobs[:]
  else: Sobs = Sobs[:].mean(axis=0)
  Zobs = netCDF4.Dataset( cmdLineArgs.woa ).variables['eta'][:]

  rootGroup = netCDF4.MFDataset( cmdLineArgs.annual_file )
  if 'salt' in rootGroup.variables: varName = 'salt'
  elif 'so' in rootGroup.variables: varName = 'so'
  else:raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.annual_file))
  if len(rootGroup.variables[varName].shape)==4: Smod = rootGroup.variables[varName][:].mean(axis=0)
  else: Smod = rootGroup.variables[varName][:]
  if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
  else: Zmod = Zobs # Using model z-output
  
  def zonalAverage(S, eta, area, mask=1.):
    vols = ( mask * area ) * ( eta[:-1] - eta[1:] ) # mask * area * level thicknesses
    return numpy.sum( vols * S, axis=-1 ) / numpy.sum( vols, axis=-1 ), (mask*eta).min(axis=-1)
  
  ci=m6plot.pmCI(0.125,2.25,.25)

  if cmdLineArgs.suptitle != '':  suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
  else: suptitle = rootGroup.title + ' ' + cmdLineArgs.label
  
  # Global
  sPlot, z = zonalAverage(Smod, Zmod, area)
  sObsPlot, _ = zonalAverage(Sobs, Zobs, area)
  if stream != None: objOut = stream[0]
  else: objOut = cmdLineArgs.outdir+'/S_global_xave_bias_WOA05.png'
  m6plot.yzplot( sPlot - sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle, title='''Global zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
        save=objOut)
  
  if stream is None:
    m6plot.yzcompare( sPlot, sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title1='Global zonal-average salinity [ppt]',
        title2='''WOA'05 salinity [ppt]''',
        clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
        dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
        save=cmdLineArgs.outdir+'/S_global_xave_bias_WOA05.3_panel.png')
  
  # Atlantic + Arctic
  newMask = 1.*msk; newMask[ (basin!=2) & (basin!=4) ] = 0.
  sPlot, z = zonalAverage(Smod, Zmod, area, mask=newMask)
  sObsPlot, _ = zonalAverage(Sobs, Zobs, area, mask=newMask)
  if stream != None: objOut = stream[1]
  else: objOut = cmdLineArgs.outdir+'/S_Atlantic_xave_bias_WOA05.png'
  m6plot.yzplot( sPlot - sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle, title='''Atlantic zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
        save=objOut)
  
  if stream is None:
    m6plot.yzcompare( sPlot, sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title1='Atlantic zonal-average salinity [ppt]',
        title2='''WOA'05 salinity [ppt]''',
        clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
        dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
        save=cmdLineArgs.outdir+'/S_Atlantic_xave_bias_WOA05.3_panel.png')
  
  # Pacific
  newMask = 1.*msk; newMask[ (basin!=3) ] = 0.
  sPlot, z = zonalAverage(Smod, Zmod, area, mask=newMask)
  sObsPlot, _ = zonalAverage(Sobs, Zobs, area, mask=newMask)
  if stream != None: objOut = stream[2]
  else: objOut = cmdLineArgs.outdir+'/S_Pacific_xave_bias_WOA05.png'
  m6plot.yzplot( sPlot - sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle, title='''Pacific zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
        save=objOut)
  
  if stream is None:
    m6plot.yzcompare( sPlot, sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title1='Pacific zonal-average salinity [ppt]',
        title2='''WOA'05 salinity [ppt]''',
        clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
        dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
        save=cmdLineArgs.outdir+'/S_Pacific_xave_bias_WOA05.3_panel.png')
  
  # Indian
  newMask = 1.*msk; newMask[ (basin!=5) ] = 0.
  sPlot, z = zonalAverage(Smod, Zmod, area, mask=newMask)
  sObsPlot, _ = zonalAverage(Sobs, Zobs, area, mask=newMask)
  if stream != None: objOut = stream[3]
  else: objOut = cmdLineArgs.outdir+'/S_Indian_xave_bias_WOA05.png'
  m6plot.yzplot( sPlot - sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle, title='''Indian zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
        save=objOut)
  
  if stream is None:
    m6plot.yzcompare( sPlot, sObsPlot , y, z, splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title1='Indian zonal-average salinity [ppt]',
        title2='''WOA'05 salinity [ppt]''',
        clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
        dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
        save=cmdLineArgs.outdir+'/S_Indian_xave_bias_WOA05.3_panel.png')
Ejemplo n.º 9
0
def main(cmdLineArgs, stream=False):
    if not os.path.exists(cmdLineArgs.gridspec):
        raise ValueError(
            'Specified gridspec directory/tar file does not exist.')
    if os.path.isdir(cmdLineArgs.gridspec):
        x = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['x'][::2, ::2]
        xcenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['x'][1::2, 1::2]
        y = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['y'][::2, ::2]
        ycenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['y'][1::2, 1::2]
        msk = netCDF4.Dataset(cmdLineArgs.gridspec +
                              '/ocean_mask.nc').variables['mask'][:]
        area = msk * netCDF4.Dataset(
            cmdLineArgs.gridspec +
            '/ocean_hgrid.nc').variables['area'][:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = netCDF4.Dataset(cmdLineArgs.gridspec +
                                '/ocean_topog.nc').variables['depth'][:]
        try:
            basin_code = netCDF4.Dataset(
                cmdLineArgs.gridspec + '/basin_codes.nc').variables['basin'][:]
        except:
            basin_code = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
    elif os.path.isfile(cmdLineArgs.gridspec):
        x = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'x')[::2, ::2]
        xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'x')[1::2, 1::2]
        y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'y')[::2, ::2]
        ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'y')[1::2, 1::2]
        msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_mask.nc',
                                      'mask')[:]
        area = msk * m6toolbox.readNCFromTar(
            cmdLineArgs.gridspec, 'ocean_hgrid.nc', 'area')[:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_topog.nc',
                                        'depth')[:]
        try:
            basin_code = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                                 'basin_codes.nc', 'basin')[:]
        except:
            basin_code = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
    else:
        raise ValueError(
            'Unable to extract grid information from gridspec directory/tar file.'
        )

    rootGroup = netCDF4.MFDataset(cmdLineArgs.infile)
    if 'vmo' in rootGroup.variables:
        varName = 'vmo'
        conversion_factor = 1.e-9
    elif 'vh' in rootGroup.variables:
        varName = 'vh'
        conversion_factor = 1.e-6
        if 'zw' in rootGroup.variables:
            conversion_factor = 1.e-9  # Backwards compatible for when we had wrong units for 'vh'
    else:
        raise Exception('Could not find "vh" or "vmo" in file "%s"' %
                        (cmdLineArgs.infile))
    if len(rootGroup.variables[varName].shape) == 4:
        VHmod = rootGroup.variables[varName][:].mean(axis=0)
    else:
        VHmod = rootGroup.variables[varName][:]
    try:
        VHmod = VHmod.filled(0.)
    except:
        pass
    Zmod = m6toolbox.get_z(rootGroup, depth, varName)

    def MOCpsi(vh, vmsk=None):
        """Sums 'vh' zonally and cumulatively in the vertical to yield an overturning stream function, psi(y,z)."""
        shape = list(vh.shape)
        shape[-3] += 1
        psi = numpy.zeros(shape[:-1])
        if len(shape) == 3:
            for k in range(shape[-3] - 1, 0, -1):
                if vmsk is None:
                    psi[k - 1, :] = psi[k, :] - vh[k - 1].sum(axis=-1)
                else:
                    psi[k - 1, :] = psi[k, :] - (vmsk * vh[k - 1]).sum(axis=-1)
        else:
            for n in range(shape[0]):
                for k in range(shape[-3] - 1, 0, -1):
                    if vmsk is None:
                        psi[n, k -
                            1, :] = psi[n, k, :] - vh[n, k - 1].sum(axis=-1)
                    else:
                        psi[n, k -
                            1, :] = psi[n, k, :] - (vmsk *
                                                    vh[n, k - 1]).sum(axis=-1)
        return psi

    def plotPsi(y, z, psi, ci, title):
        cmap = plt.get_cmap('dunnePM')
        plt.contourf(y, z, psi, levels=ci, cmap=cmap, extend='both')
        cbar = plt.colorbar()
        plt.contour(y, z, psi, levels=ci, colors='k', hold='on')
        plt.gca().set_yscale('splitscale', zval=[0., -2000., -6500.])
        plt.title(title)
        cbar.set_label('[Sv]')
        plt.ylabel('Elevation [m]')

    def findExtrema(y,
                    z,
                    psi,
                    min_lat=-90.,
                    max_lat=90.,
                    min_depth=0.,
                    mult=1.):
        psiMax = mult * numpy.amax(
            mult * numpy.ma.array(psi)[(y >= min_lat) & (y <= max_lat) &
                                       (z < -min_depth)])
        idx = numpy.argmin(numpy.abs(psi - psiMax))
        (j, i) = numpy.unravel_index(idx, psi.shape)
        plt.plot(y[j, i], z[j, i], 'kx', hold=True)
        plt.text(y[j, i], z[j, i], '%.1f' % (psi[j, i]))

    if cmdLineArgs.suptitle != '':
        suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
    else:
        suptitle = rootGroup.title + ' ' + cmdLineArgs.label

    imgbufs = []

    # Global MOC
    m6plot.setFigureSize([16, 9], 576, debug=False)
    axis = plt.gca()
    cmap = plt.get_cmap('dunnePM')
    z = Zmod.min(axis=-1)
    psiPlot = MOCpsi(VHmod) * conversion_factor
    yy = y[1:, :].max(axis=-1) + 0 * z
    ci = m6plot.pmCI(0., 40., 5.)
    plotPsi(yy, z, psiPlot, ci, 'Global MOC [Sv]')
    plt.xlabel(r'Latitude [$\degree$N]')
    plt.suptitle(suptitle)
    findExtrema(yy, z, psiPlot, max_lat=-30.)
    findExtrema(yy, z, psiPlot, min_lat=25.)
    findExtrema(yy, z, psiPlot, min_depth=2000., mult=-1.)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/MOC_global.png'
    plt.savefig(objOut)
    if stream is True: imgbufs.append(objOut)

    # Atlantic MOC
    m6plot.setFigureSize([16, 9], 576, debug=False)
    cmap = plt.get_cmap('dunnePM')
    m = 0 * basin_code
    m[(basin_code == 2) | (basin_code == 4) | (basin_code == 6) |
      (basin_code == 7) | (basin_code == 8)] = 1
    ci = m6plot.pmCI(0., 22., 2.)
    z = (m * Zmod).min(axis=-1)
    psiPlot = MOCpsi(VHmod,
                     vmsk=m * numpy.roll(m, -1, axis=-2)) * conversion_factor
    yy = y[1:, :].max(axis=-1) + 0 * z
    plotPsi(yy, z, psiPlot, ci, 'Atlantic MOC [Sv]')
    plt.xlabel(r'Latitude [$\degree$N]')
    plt.suptitle(suptitle)
    findExtrema(yy, z, psiPlot, min_lat=26.5, max_lat=27.)  # RAPID
    findExtrema(yy, z, psiPlot, max_lat=-33.)
    findExtrema(yy, z, psiPlot)
    findExtrema(yy, z, psiPlot, min_lat=5.)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/MOC_Atlantic.png'
    plt.savefig(objOut, format='png')
    if stream is True: imgbufs.append(objOut)

    if stream is True:
        return imgbufs
Ejemplo n.º 10
0
  (j,i) = numpy.unravel_index(idx, psi.shape)
  plt.plot(y[j,i],z[j,i],'kx',hold=True)
  plt.text(y[j,i],z[j,i],'%.1f'%(psi[j,i]))

m6plot.setFigureSize(npanels=3)
if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

# Global MOC
z = Zmod.min(axis=-1)
yy = y[1:,:].max(axis=-1)+0*z
psiPlotM = MOCpsi(VHmod)/1e6
psiPlotR = MOCpsi(VHref)/1e6
ci=m6plot.pmCI(0.,40.,5.)
di=m6plot.pmCI(0.,5.,0.5)
plt.subplot(311)
plotPsi(yy, z, psiPlotM, ci, title1)
findExtrema(yy, z, psiPlotM, max_lat=-30.)
findExtrema(yy, z, psiPlotM, min_lat=25.)
findExtrema(yy, z, psiPlotM, min_depth=2000., mult=-1.)
plt.subplot(312)
plotPsi(yy, z, psiPlotR, ci, title2)
findExtrema(yy, z, psiPlotR, max_lat=-30.)
findExtrema(yy, z, psiPlotR, min_lat=25.)
findExtrema(yy, z, psiPlotR, min_depth=2000., mult=-1.)
plt.subplot(313)
plotPsi(yy, z, psiPlotM-psiPlotR, di, title1 + ' - ' + title2)
plt.xlabel(r'Latitude [$\degree$N]')
plt.suptitle('Global MOC')
Ejemplo n.º 11
0
def main(cmdLineArgs, stream=False):
    if not os.path.exists(cmdLineArgs.gridspec):
        raise ValueError(
            'Specified gridspec directory/tar file does not exist.')
    if os.path.isdir(cmdLineArgs.gridspec):
        xcenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['x'][1::2, 1::2]
        y = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['y'][1::2, 1::2].max(
                                axis=-1)
        ycenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['y'][1::2, 1::2]
        msk = netCDF4.Dataset(cmdLineArgs.gridspec +
                              '/ocean_mask.nc').variables['mask'][:]
        area = msk * netCDF4.Dataset(
            cmdLineArgs.gridspec +
            '/ocean_hgrid.nc').variables['area'][:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = netCDF4.Dataset(cmdLineArgs.gridspec +
                                '/ocean_topog.nc').variables['depth'][:]
        try:
            basin = netCDF4.Dataset(cmdLineArgs.gridspec +
                                    '/basin_codes.nc').variables['basin'][:]
        except:
            basin = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
    elif os.path.isfile(cmdLineArgs.gridspec):
        xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'x')[1::2, 1::2]
        y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'y')[1::2, 1::2].max(axis=-1)
        ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'y')[1::2, 1::2]
        msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_mask.nc',
                                      'mask')[:]
        area = msk * m6toolbox.readNCFromTar(
            cmdLineArgs.gridspec, 'ocean_hgrid.nc', 'area')[:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_topog.nc',
                                        'depth')[:]
        try:
            basin = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                            'basin_codes.nc', 'basin')[:]
        except:
            basin = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
    else:
        raise ValueError(
            'Unable to extract grid information from gridspec directory/tar file.'
        )

    Sobs = netCDF4.Dataset(cmdLineArgs.woa).variables['salt']
    if len(Sobs.shape) == 3: Sobs = Sobs[:]
    else: Sobs = Sobs[:].mean(axis=0)
    Zobs = netCDF4.Dataset(cmdLineArgs.woa).variables['eta'][:]

    rootGroup = netCDF4.MFDataset(cmdLineArgs.infile)
    if 'salt' in rootGroup.variables: varName = 'salt'
    elif 'so' in rootGroup.variables: varName = 'so'
    else:
        raise Exception('Could not find "salt" or "so" in file "%s"' %
                        (cmdLineArgs.infile))
    if len(rootGroup.variables[varName].shape) == 4:
        Smod = rootGroup.variables[varName][:].mean(axis=0)
    else:
        Smod = rootGroup.variables[varName][:]
    if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
    else: Zmod = Zobs  # Using model z-output

    def zonalAverage(S, eta, area, mask=1.):
        vols = (mask * area) * (eta[:-1] - eta[1:]
                                )  # mask * area * level thicknesses
        return numpy.sum(vols * S, axis=-1) / numpy.sum(vols, axis=-1), (
            mask * eta).min(axis=-1)

    ci = m6plot.pmCI(0.125, 2.25, .25)

    if cmdLineArgs.suptitle != '':
        suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
    else:
        suptitle = rootGroup.title + ' ' + cmdLineArgs.label

    imgbufs = []

    # Global
    sPlot, z = zonalAverage(Smod, Zmod, area)
    sObsPlot, _ = zonalAverage(Sobs, Zobs, area)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/S_global_xave_bias_WOA05.png'
    m6plot.yzplot(
        sPlot - sObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title='''Global zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)
    if stream is True: imgbufs.append(objOut)

    if stream is None:
        m6plot.yzcompare(sPlot,
                         sObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1='Global zonal-average salinity [ppt]',
                         title2='''WOA'05 salinity [ppt]''',
                         clim=m6plot.linCI(20, 30, 10, 31, 39, .5),
                         colormap='dunneRainbow',
                         extend='both',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/S_global_xave_bias_WOA05.3_panel.png')

    # Atlantic + Arctic
    newMask = 1. * msk
    newMask[(basin != 2) & (basin != 4)] = 0.
    sPlot, z = zonalAverage(Smod, Zmod, area, mask=newMask)
    sObsPlot, _ = zonalAverage(Sobs, Zobs, area, mask=newMask)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/S_Atlantic_xave_bias_WOA05.png'
    m6plot.yzplot(
        sPlot - sObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title='''Atlantic zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)
    if stream is True: imgbufs.append(objOut)

    if stream is None:
        m6plot.yzcompare(sPlot,
                         sObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1='Atlantic zonal-average salinity [ppt]',
                         title2='''WOA'05 salinity [ppt]''',
                         clim=m6plot.linCI(20, 30, 10, 31, 39, .5),
                         colormap='dunneRainbow',
                         extend='both',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/S_Atlantic_xave_bias_WOA05.3_panel.png')

    # Pacific
    newMask = 1. * msk
    newMask[(basin != 3)] = 0.
    sPlot, z = zonalAverage(Smod, Zmod, area, mask=newMask)
    sObsPlot, _ = zonalAverage(Sobs, Zobs, area, mask=newMask)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/S_Pacific_xave_bias_WOA05.png'
    m6plot.yzplot(
        sPlot - sObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title='''Pacific zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)
    if stream is True: imgbufs.append(objOut)

    if stream is None:
        m6plot.yzcompare(sPlot,
                         sObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1='Pacific zonal-average salinity [ppt]',
                         title2='''WOA'05 salinity [ppt]''',
                         clim=m6plot.linCI(20, 30, 10, 31, 39, .5),
                         colormap='dunneRainbow',
                         extend='both',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/S_Pacific_xave_bias_WOA05.3_panel.png')

    # Indian
    newMask = 1. * msk
    newMask[(basin != 5)] = 0.
    sPlot, z = zonalAverage(Smod, Zmod, area, mask=newMask)
    sObsPlot, _ = zonalAverage(Sobs, Zobs, area, mask=newMask)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/S_Indian_xave_bias_WOA05.png'
    m6plot.yzplot(
        sPlot - sObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title='''Indian zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)
    if stream is True: imgbufs.append(objOut)

    if stream is None:
        m6plot.yzcompare(sPlot,
                         sObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1='Indian zonal-average salinity [ppt]',
                         title2='''WOA'05 salinity [ppt]''',
                         clim=m6plot.linCI(20, 30, 10, 31, 39, .5),
                         colormap='dunneRainbow',
                         extend='both',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/S_Indian_xave_bias_WOA05.3_panel.png')

    if stream is True:
        return imgbufs
Ejemplo n.º 12
0
if len(rootGroup.variables[varName].shape) == 4:
    Tmod = rootGroup.variables[varName][:].mean(axis=0)
else:
    Tmod = rootGroup.variables[varName][:]
if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
else: Zmod = Zref


def zonalAverage(T, eta, area, mask=1.):
    vols = (mask * area) * (eta[:-1] - eta[1:]
                            )  # mask * area * level thicknesses
    return numpy.sum(vols * T, axis=-1) / numpy.sum(vols, axis=-1), (
        mask * eta).min(axis=-1)


ci = m6plot.pmCI(0.025, .45, .05)
if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

# Global
tPlot, z = zonalAverage(Tmod, Zmod, area)
tRefPlot, _ = zonalAverage(Tref, Zref, area)
m6plot.yzplot(
    tPlot - tRefPlot,
    y,
    z,
    splitscale=[0., -1000., -6500.],
    suptitle=title1 + ' - ' + title2,
    title=r'''Global zonal-average $\theta$ response [$\degree$C] ''' +
Ejemplo n.º 13
0
rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'temp' in rootGroup.variables: varName = 'temp'
elif 'ptemp' in rootGroup.variables: varName = 'ptemp'
elif 'thetao' in rootGroup.variables: varName = 'thetao'
else: raise Exception('Could not find "temp", "ptemp" or "thetao" in file "%s"'%(cmdLineArgs.annual_file))
if len(rootGroup.variables[varName].shape)==4: Tmod = rootGroup.variables[varName][:].mean(axis=0)
else: Tmod = rootGroup.variables[varName][:]
if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
else: Zmod = Zref

def zonalAverage(T, eta, area, mask=1.):
  vols = ( mask * area ) * ( eta[:-1] - eta[1:] ) # mask * area * level thicknesses
  return numpy.sum( vols * T, axis=-1 ) / numpy.sum( vols, axis=-1 ), (mask*eta).min(axis=-1)

ci=m6plot.pmCI(0.025,.45,.05)
if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

# Global
tPlot, z = zonalAverage(Tmod, Zmod, area)
tRefPlot, _ = zonalAverage(Tref, Zref, area)
m6plot.yzplot( tPlot - tRefPlot , y, z, splitscale=[0., -1000., -6500.],
      suptitle=title1+' - '+title2, title=r'''Global zonal-average $\theta$ response [$\degree$C] '''+cmdLineArgs.label,
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/T_global_xave_response.png')

m6plot.yzcompare( tPlot, tRefPlot , y, z, splitscale=[0., -1000., -6500.],
      suptitle=r'Global zonal-average $\theta$ [$\degree$C] '+cmdLineArgs.label,
  HT = numpy.zeros(T.shape[1:])
  for k in range(T.shape[0]):
    zTop = numpy.minimum( z[k], -upperDepth )
    zBot = numpy.maximum( z[k+1], -D )
    dh = numpy.maximum( zTop -zBot, 0. )
    #dh = numpy.minimum( z[k]-z[k+1], D-H)
    H = H + dh
    HT = HT + dh*T[k]
  return HT/(H+1.e-20)

if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

ci=m6plot.pmCI(0.05,1.,.1)

tPlot = depthAverageT(Tmod, Zmod, depth, lDepth, uDepth)
tRefPlot = depthAverageT(Tref, Zref, depth, lDepth, uDepth)
m6plot.xyplot( tPlot - tRefPlot , x, y, area=area,
      suptitle=rootGroup.title+' '+cmdLineArgs.label,
      title=r'%i-%im depth-average $\theta$ difference [$\degree$C]'%(uDepth,lDepth),
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/T_%i-%im_zave_difference.png'%(uDepth,lDepth))

m6plot.xycompare( tPlot, tRefPlot , x, y, area=area,
      suptitle=r'%i-%im depth-average $\theta$ difference [$\degree$C]'%(uDepth,lDepth)+cmdLineArgs.label,
      title1=title1, title2=title2,
      clim=m6plot.linCI(-2,29,.5), colormap='dunneRainbow', extend='max',
      dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
      save=cmdLineArgs.outdir+'/T_%i-%im_zave_difference.3_panel.png'%(uDepth,lDepth))
Ejemplo n.º 15
0
if len(rootGroup.variables[varName].shape) == 4:
    Smod = rootGroup.variables[varName][:].mean(axis=0)
else:
    Smod = rootGroup.variables[varName][:]
if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
else: Zmod = Zref


def zonalAverage(T, eta, area, mask=1.):
    vols = (mask * area) * (eta[:-1] - eta[1:]
                            )  # mask * area * level thicknesses
    return numpy.sum(vols * T, axis=-1) / numpy.sum(vols, axis=-1), (
        mask * eta).min(axis=-1)


ci = m6plot.pmCI(0.0125, .225, .025)
if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

# Global
sPlot, z = zonalAverage(Smod, Zmod, area)
sRefPlot, _ = zonalAverage(Sref, Zref, area)
m6plot.yzplot(sPlot - sRefPlot,
              y,
              z,
              splitscale=[0., -1000., -6500.],
              suptitle=title1 + ' - ' + title2,
              title='''Global zonal-average salinity response [ppt] ''' +
              cmdLineArgs.label,
Ejemplo n.º 16
0
def main(cmdLineArgs, stream=False):
    numpy.seterr(divide='ignore', invalid='ignore',
                 over='ignore')  # To avoid warnings

    if not os.path.exists(cmdLineArgs.gridspec):
        raise ValueError(
            'Specified gridspec directory/tar file does not exist.')
    if os.path.isdir(cmdLineArgs.gridspec):
        x = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['x'][::2, ::2]
        xcenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['x'][1::2, 1::2]
        y = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['y'][::2, ::2]
        ycenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['y'][1::2, 1::2]
        msk = netCDF4.Dataset(cmdLineArgs.gridspec +
                              '/ocean_mask.nc').variables['mask'][:]
        area = msk * netCDF4.Dataset(
            cmdLineArgs.gridspec +
            '/ocean_hgrid.nc').variables['area'][:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = netCDF4.Dataset(cmdLineArgs.gridspec +
                                '/ocean_topog.nc').variables['depth'][:]
    elif os.path.isfile(cmdLineArgs.gridspec):
        x = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'x')[::2, ::2]
        xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'x')[1::2, 1::2]
        y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'y')[::2, ::2]
        ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'y')[1::2, 1::2]
        msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_mask.nc',
                                      'mask')[:]
        area = msk * m6toolbox.readNCFromTar(
            cmdLineArgs.gridspec, 'ocean_hgrid.nc', 'area')[:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_topog.nc',
                                        'depth')[:]
    else:
        raise ValueError(
            'Unable to extract grid information from gridspec directory/tar file.'
        )

    # open dataset
    rootGroup = netCDF4.MFDataset(cmdLineArgs.infile)

    # gather months from input dataset
    tvar = rootGroup.variables['time']
    times = [
        netCDF4.num2date(i, tvar.units, calendar=tvar.calendar.lower())
        for i in tvar[:]
    ]
    idx = list(set([i.month - 1 for i in times]))
    month_label = [i.strftime('%b') for i in times]
    month_label = month_label[:len(idx)]
    month_label = str.join(', ', month_label)

    # read sst from model
    if 'sst' in rootGroup.variables: varName = 'sst'
    elif 'tos' in rootGroup.variables: varName = 'tos'
    else:
        raise Exception('Could not find "sst", "ptemp" or "tos" in file "%s"' %
                        (cmdLineArgs.infile))
    if rootGroup.variables[varName].shape[0] > 1:
        Tmod = rootGroup.variables[varName][:].mean(axis=0)
    else:
        Tmod = rootGroup.variables[varName][0]

    # read sst from obs
    Tobs = netCDF4.Dataset(cmdLineArgs.woa_monthly)
    if 'temp' in Tobs.variables: Tobs = Tobs.variables['temp']
    elif 'ptemp' in Tobs.variables: Tobs = Tobs.variables['ptemp']
    else:
        raise Exception('Could not find "temp" or "ptemp" in file "%s"' %
                        (cmdLineArgs.woa_monthly))
    if len(Tobs.shape) == 3: Tobs = Tobs[0]
    else: Tobs = Tobs[idx, 0].mean(axis=0)

    # create title for plot
    if cmdLineArgs.suptitle != '':
        suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
    else:
        suptitle = rootGroup.title + ' ' + cmdLineArgs.label

    # invoke m6plot
    imgbufs = []
    ci = m6plot.pmCI(0.25, 4.5, .5)
    if stream is True: objOut = io.BytesIO()
    else: objOut = cmdLineArgs.outdir + '/SST_bias_WOA05.png'
    m6plot.xyplot(Tmod - Tobs,
                  x,
                  y,
                  area=area,
                  suptitle=suptitle,
                  title=month_label +
                  ' SST bias (w.r.t. WOA\'05) [$\degree$C]',
                  clim=ci,
                  colormap='dunnePM',
                  centerlabels=True,
                  extend='both',
                  save=objOut)
    if stream is True: imgbufs.append(objOut)

    m6plot.xycompare(Tmod,
                     Tobs,
                     x,
                     y,
                     area=area,
                     suptitle=suptitle,
                     title1=month_label + ' SST [$\degree$C]',
                     title2='WOA\'05 ' + month_label + ' SST [$\degree$C]',
                     clim=m6plot.linCI(-2, 29, .5),
                     colormap='dunneRainbow',
                     extend='max',
                     dlim=ci,
                     dcolormap='dunnePM',
                     dextend='both',
                     centerdlabels=True,
                     save=cmdLineArgs.outdir + '/SST_bias_WOA05.3_panel.png')

    if stream is True:
        return imgbufs
Ejemplo n.º 17
0
x = netCDF4.Dataset(cmdLineArgs.gridspecdir+'/ocean_hgrid.nc').variables['x'][::2,::2]
y = netCDF4.Dataset(cmdLineArgs.gridspecdir+'/ocean_hgrid.nc').variables['y'][::2,::2]
msk = netCDF4.Dataset(cmdLineArgs.gridspecdir+'/ocean_mask.nc').variables['mask'][:]
area = msk*netCDF4.Dataset(cmdLineArgs.gridspecdir+'/ocean_hgrid.nc').variables['area'][:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
msk = numpy.ma.array(msk, mask=(msk==0))

Sobs = netCDF4.Dataset( cmdLineArgs.woa ).variables['salt']
if len(Sobs.shape)==3: Sobs = Sobs[0]
else: Sobs = Sobs[:,0].mean(axis=0)

rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'salt' in rootGroup.variables: varName = 'salt'
elif 'so' in rootGroup.variables: varName = 'so'
else: raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.annual_file))
if rootGroup.variables[varName].shape[0]>1: salt = rootGroup.variables[varName][:,0].mean(axis=0)
else: Smod = rootGroup.variables[varName][0,0]

ci=m6plot.pmCI(0.125,2.25,.25)
m6plot.xyplot( Smod - Sobs , x, y, area=area,
      suptitle=rootGroup.title+' '+cmdLineArgs.label, title='SSS bias (w.r.t. WOA\'05) [ppt]',
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/SSS_bias_WOA05.png')

m6plot.xycompare( Smod, Sobs , x, y, area=area,
      suptitle=rootGroup.title+' '+cmdLineArgs.label,
      title1='SSS [ppt]',
      title2='WOA\'05 SSS [ppt]',
      clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
      dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
      save=cmdLineArgs.outdir+'/SSS_bias_WOA05.3_panel.png')
Ejemplo n.º 18
0
    for k in range(T.shape[0]):
        zTop = numpy.minimum(z[k], -upperDepth)
        zBot = numpy.maximum(z[k + 1], -D)
        dh = numpy.maximum(zTop - zBot, 0.)
        #dh = numpy.minimum( z[k]-z[k+1], D-H)
        H = H + dh
        HT = HT + dh * T[k]
    return HT / (H + 1.e-20)


if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

ci = m6plot.pmCI(0.05, 1., .1)

tPlot = depthAverageT(Tmod, Zmod, depth, lDepth, uDepth)
tRefPlot = depthAverageT(Tref, Zref, depth, lDepth, uDepth)
m6plot.xyplot(tPlot - tRefPlot,
              x,
              y,
              area=area,
              suptitle=title1 + ' - ' + title2,
              title=r'%i-%im depth-average $\theta$ difference [$\degree$C]' %
              (uDepth, lDepth) + cmdLineArgs.label,
              clim=ci,
              colormap='dunnePM',
              centerlabels=True,
              extend='both',
              save=cmdLineArgs.outdir + '/T_%i-%im_zave_difference.png' %
Ejemplo n.º 19
0
Zobs = netCDF4.Dataset( cmdLineArgs.woa ).variables['eta'][:]

rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'salt' in rootGroup.variables: varName = 'salt'
elif 'so' in rootGroup.variables: varName = 'so'
else:raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.annual_file))
if len(rootGroup.variables[varName].shape)==4: Smod = rootGroup.variables[varName][:].mean(axis=0)
else: Smod = rootGroup.variables[varName][:]
if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
else: Zmod = Zobs # Using model z-output

def zonalAverage(S, eta, area, mask=1.):
  vols = ( mask * area ) * ( eta[:-1] - eta[1:] ) # mask * area * level thicknesses
  return numpy.sum( vols * S, axis=-1 ) / numpy.sum( vols, axis=-1 ), (mask*eta).min(axis=-1)

ci=m6plot.pmCI(0.125,2.25,.25)

# Global
sPlot, z = zonalAverage(Smod, Zmod, area)
sObsPlot, _ = zonalAverage(Sobs, Zobs, area)
m6plot.yzplot( sPlot - sObsPlot , y, z, splitscale=[0., -1000., -6500.],
      suptitle=rootGroup.title+' '+cmdLineArgs.label, title='''Global zonal-average salinity bias (w.r.t. WOA'05) [ppt]''',
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/S_global_xave_bias_WOA05.png')

m6plot.yzcompare( sPlot, sObsPlot , y, z, splitscale=[0., -1000., -6500.],
      suptitle=rootGroup.title+' '+cmdLineArgs.label,
      title1='Global zonal-average salinity [ppt]',
      title2='''WOA'05 salinity [ppt]''',
      clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='both',
      dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
Ejemplo n.º 20
0
def main(cmdLineArgs,stream=None):
  if not os.path.exists(cmdLineArgs.gridspec): raise ValueError('Specified gridspec directory/tar file does not exist.')
  if os.path.isdir(cmdLineArgs.gridspec):
    x = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['x'][::2,::2]
    xcenter = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['x'][1::2,1::2]
    y = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['y'][::2,::2]
    ycenter = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['y'][1::2,1::2]
    msk = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_mask.nc').variables['mask'][:]
    area = msk*netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_hgrid.nc').variables['area'][:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
    depth = netCDF4.Dataset(cmdLineArgs.gridspec+'/ocean_topog.nc').variables['depth'][:]
    try: basin_code = netCDF4.Dataset(cmdLineArgs.gridspec+'/basin_codes.nc').variables['basin'][:]
    except: basin_code = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
  elif os.path.isfile(cmdLineArgs.gridspec):
    x = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','x')[::2,::2]
    xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','x')[1::2,1::2]
    y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','y')[::2,::2]
    ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','y')[1::2,1::2]
    msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_mask.nc','mask')[:]
    area = msk*m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_hgrid.nc','area')[:,:].reshape([msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
    depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'ocean_topog.nc','depth')[:]
    try: basin_code = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,'basin_codes.nc','basin')[:]
    except: basin_code = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
  else:
    raise ValueError('Unable to extract grid information from gridspec directory/tar file.') 

  if stream != None:
    if len(stream) != 2:
      raise ValueError('If specifying output streams, exactly two streams are needed for this analysis')
  
  rootGroup = netCDF4.MFDataset( cmdLineArgs.annual_file )
  if 'vh' in rootGroup.variables:
    varName = 'vh'; conversion_factor = 1.e-9
  elif 'vmo' in rootGroup.variables:
    varName = 'vmo'; conversion_factor = 1.e-9
  else: raise Exception('Could not find "vh" or "vmo" in file "%s"'%(cmdLineArgs.annual_file))
  if len(rootGroup.variables[varName].shape)==4: VHmod = rootGroup.variables[varName][:].mean(axis=0)
  else: VHmod = rootGroup.variables[varName][:]
  try: VHmod = VHmod.filled(0.)
  except: pass
  if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
  elif 'zw' in rootGroup.variables:
    zw = rootGroup.variables['zw'][:]
    Zmod = numpy.zeros((zw.shape[0], depth.shape[0], depth.shape[1] ))
    for k in range(zw.shape[0]):
      Zmod[k] = -numpy.minimum( depth, abs(zw[k]) )
  else: raise Exception('Neither a model-space output file or a z-space diagnostic file?')
  
  def MOCpsi(vh, vmsk=None):
    """Sums 'vh' zonally and cumulatively in the vertical to yield an overturning stream function, psi(y,z)."""
    shape = list(vh.shape); shape[-3] += 1
    psi = numpy.zeros(shape[:-1])
    if len(shape)==3:
      for k in range(shape[-3]-1,0,-1):
        if vmsk is None: psi[k-1,:] = psi[k,:] - vh[k-1].sum(axis=-1)
        else: psi[k-1,:] = psi[k,:] - (vmsk*vh[k-1]).sum(axis=-1)
    else:
      for n in range(shape[0]):
        for k in range(shape[-3]-1,0,-1):
          if vmsk is None: psi[n,k-1,:] = psi[n,k,:] - vh[n,k-1].sum(axis=-1)
          else: psi[n,k-1,:] = psi[n,k,:] - (vmsk*vh[n,k-1]).sum(axis=-1)
    return psi
  
  def plotPsi(y, z, psi, ci, title):
    cmap = plt.get_cmap('dunnePM')
    plt.contourf(y, z, psi, levels=ci, cmap=cmap, extend='both')
    cbar = plt.colorbar()
    plt.contour(y, z, psi, levels=ci, colors='k', hold='on')
    plt.gca().set_yscale('splitscale',zval=[0,-2000,-6500])
    plt.title(title)
    cbar.set_label('[Sv]'); plt.ylabel('Elevation [m]')

  def findExtrema(y, z, psi, min_lat=-90., max_lat=90., min_depth=0., mult=1.):
    psiMax = mult*numpy.amax( mult * numpy.ma.array(psi)[(y>=min_lat) & (y<=max_lat) & (z<-min_depth)] )
    idx = numpy.argmin(numpy.abs(psi-psiMax))
    (j,i) = numpy.unravel_index(idx, psi.shape)
    plt.plot(y[j,i],z[j,i],'kx',hold=True)
    plt.text(y[j,i],z[j,i],'%.1f'%(psi[j,i]))
  
  m6plot.setFigureSize(npanels=1)
  cmap = plt.get_cmap('dunnePM')

  if cmdLineArgs.suptitle != '':  suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
  else: suptitle = rootGroup.title + ' ' + cmdLineArgs.label

  # Global MOC
  z = Zmod.min(axis=-1); psiPlot = MOCpsi(VHmod)*conversion_factor
  yy = y[1:,:].max(axis=-1)+0*z
  ci=m6plot.pmCI(0.,40.,5.)
  plotPsi(yy, z, psiPlot, ci, 'Global MOC [Sv]')
  plt.xlabel(r'Latitude [$\degree$N]')
  plt.suptitle(suptitle)
  findExtrema(yy, z, psiPlot, max_lat=-30.)
  findExtrema(yy, z, psiPlot, min_lat=25.)
  findExtrema(yy, z, psiPlot, min_depth=2000., mult=-1.)
  if stream != None:
    plt.savefig(stream[0])
  else:
    plt.savefig(cmdLineArgs.outdir+'/MOC_global.png')
  
  # Atlantic MOC
  plt.clf()
  m = 0*basin_code; m[(basin_code==2) | (basin_code==4) | (basin_code==6) | (basin_code==7) | (basin_code==8)]=1
  ci=m6plot.pmCI(0.,22.,2.)
  z = (m*Zmod).min(axis=-1); psiPlot = MOCpsi(VHmod, vmsk=m*numpy.roll(m,-1,axis=-2))*conversion_factor
  yy = y[1:,:].max(axis=-1)+0*z
  plotPsi(yy, z, psiPlot, ci, 'Atlantic MOC [Sv]')
  plt.xlabel(r'Latitude [$\degree$N]')
  plt.suptitle(suptitle)
  findExtrema(yy, z, psiPlot, min_lat=26.5, max_lat=27.) # RAPID
  findExtrema(yy, z, psiPlot, max_lat=-33.)
  findExtrema(yy, z, psiPlot)
  findExtrema(yy, z, psiPlot, min_lat=5.)
  if stream != None:
    plt.savefig(stream[1])
  else:
    plt.savefig(cmdLineArgs.outdir+'/MOC_Atlantic.png')
Ejemplo n.º 21
0
def depthAverageT(T, z, d, lowerDepth, upperDepth):
    D = numpy.minimum(d, lowerDepth)
    H = numpy.zeros(T.shape[1:])
    HT = numpy.zeros(T.shape[1:])
    for k in range(T.shape[0]):
        zTop = numpy.minimum(z[k], -upperDepth)
        zBot = numpy.maximum(z[k + 1], -D)
        dh = numpy.maximum(zTop - zBot, 0.)
        #dh = numpy.minimum( z[k]-z[k+1], D-H)
        H = H + dh
        HT = HT + dh * T[k]
    return HT / (H + 1.e-20)


ci = m6plot.pmCI(0.25, 4.5, .5)

tPlot = depthAverageT(Tmod, Zmod, depth, lDepth, uDepth)
tObsPlot = depthAverageT(Tobs, Zobs, depth, lDepth, uDepth)
m6plot.xyplot(
    tPlot - tObsPlot,
    x,
    y,
    area=area,
    suptitle=rootGroup.title + ' ' + cmdLineArgs.label,
    title=r'''%i-%im depth-average $\theta$ bias (w.r.t. WOA'05) [$\degree$C]'''
    % (uDepth, lDepth),
    clim=ci,
    colormap='dunnePM',
    centerlabels=True,
    extend='both',
Ejemplo n.º 22
0
elif 'so' in rootGroupRef.variables: varName='so'
else: raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.ref))
if rootGroupRef.variables[varName].shape[0]>1: Sref = rootGroupRef.variables[varName][:,0].mean(axis=0)
else: Sref = rootGroupRef.variables[varName][0,0]

rootGroup = netCDF4.Dataset( cmdLineArgs.annual_file )
if 'salt' in rootGroup.variables: varName='salt'
elif 'so' in rootGroup.variables: varName='so'
else: raise Exception('Could not find "salt" or "so" in file "%s"'%(cmdLineArgs.annual_file))
if len(rootGroup.variables[varName].shape)==4: Smod = rootGroup.variables[varName][:,0].mean(axis=0)
else: Smod = rootGroup.variables[varName][0]

if len(cmdLineArgs.label1): title1 = cmdLineArgs.label1
else: title1 = rootGroup.title
if len(cmdLineArgs.label2): title2 = cmdLineArgs.label2
else: title2 = rootGroupRef.title

ci=m6plot.pmCI(0.025,0.525,.05)
m6plot.xyplot( Smod - Sref , x, y, area=area,
      suptitle=title1+' - '+title2,
      title='SSS difference [ppt] '+cmdLineArgs.label,
      clim=ci, colormap='dunnePM', centerlabels=True, extend='both',
      save=cmdLineArgs.outdir+'/SSS_difference.png')

m6plot.xycompare( Smod, Sref , x, y, area=area,
      suptitle='SSS difference [ppt] '+cmdLineArgs.label,
      title1=title1, title2=title2,
      clim=m6plot.linCI(20,30,10, 31,39,.5), colormap='dunneRainbow', extend='max',
      dlim=ci, dcolormap='dunnePM', dextend='both', centerdlabels=True,
      save=cmdLineArgs.outdir+'/SSS_difference.3_panel.png')
Ejemplo n.º 23
0
def main(cmdLineArgs, stream=None):
    if not os.path.exists(cmdLineArgs.gridspec):
        raise ValueError(
            'Specified gridspec directory/tar file does not exist.')
    if os.path.isdir(cmdLineArgs.gridspec):
        xcenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['x'][1::2, 1::2]
        y = netCDF4.Dataset(cmdLineArgs.gridspec +
                            '/ocean_hgrid.nc').variables['y'][1::2, 1::2].max(
                                axis=-1)
        ycenter = netCDF4.Dataset(cmdLineArgs.gridspec +
                                  '/ocean_hgrid.nc').variables['y'][1::2, 1::2]
        msk = netCDF4.Dataset(cmdLineArgs.gridspec +
                              '/ocean_mask.nc').variables['mask'][:]
        area = msk * netCDF4.Dataset(
            cmdLineArgs.gridspec +
            '/ocean_hgrid.nc').variables['area'][:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = netCDF4.Dataset(cmdLineArgs.gridspec +
                                '/ocean_topog.nc').variables['depth'][:]
        try:
            basin = netCDF4.Dataset(cmdLineArgs.gridspec +
                                    '/basin_codes.nc').variables['basin'][:]
        except:
            basin = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
    elif os.path.isfile(cmdLineArgs.gridspec):
        xcenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'x')[1::2, 1::2]
        y = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_hgrid.nc',
                                    'y')[1::2, 1::2].max(axis=-1)
        ycenter = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                          'ocean_hgrid.nc', 'y')[1::2, 1::2]
        msk = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_mask.nc',
                                      'mask')[:]
        area = msk * m6toolbox.readNCFromTar(
            cmdLineArgs.gridspec, 'ocean_hgrid.nc', 'area')[:, :].reshape(
                [msk.shape[0], 2, msk.shape[1], 2]).sum(axis=-3).sum(axis=-1)
        depth = m6toolbox.readNCFromTar(cmdLineArgs.gridspec, 'ocean_topog.nc',
                                        'depth')[:]
        try:
            basin = m6toolbox.readNCFromTar(cmdLineArgs.gridspec,
                                            'basin_codes.nc', 'basin')[:]
        except:
            basin = m6toolbox.genBasinMasks(xcenter, ycenter, depth)
    else:
        raise ValueError(
            'Unable to extract grid information from gridspec directory/tar file.'
        )

    if stream != None:
        if len(stream) != 4:
            raise ValueError(
                'If specifying output streams, exactly four (4) streams are needed for this analysis'
            )

    Tobs = netCDF4.Dataset(cmdLineArgs.woa)
    if 'temp' in Tobs.variables: Tobs = Tobs.variables['temp']
    else: Tobs = Tobs.variables['ptemp']
    if len(Tobs.shape) == 3: Tobs = Tobs[:]
    else: Tobs = Tobs[:].mean(axis=0)
    Zobs = netCDF4.Dataset(cmdLineArgs.woa).variables['eta'][:]

    rootGroup = netCDF4.MFDataset(cmdLineArgs.annual_file)
    if 'temp' in rootGroup.variables: varName = 'temp'
    elif 'ptemp' in rootGroup.variables: varName = 'ptemp'
    elif 'thetao' in rootGroup.variables: varName = 'thetao'
    else:
        raise Exception(
            'Could not find "temp", "ptemp" or "thetao" in file "%s"' %
            (cmdLineArgs.annual_file))
    if len(rootGroup.variables[varName].shape) == 4:
        Tmod = rootGroup.variables[varName][:].mean(axis=0)
    else:
        Tmod = rootGroup.variables[varName][:]
    if 'e' in rootGroup.variables: Zmod = rootGroup.variables['e'][0]
    else: Zmod = Zobs  # Using model z-ou:put

    def zonalAverage(T, eta, area, mask=1.):
        vols = (mask * area) * (eta[:-1] - eta[1:]
                                )  # mask * area * level thicknesses
        return numpy.sum(vols * T, axis=-1) / numpy.sum(vols, axis=-1), (
            mask * eta).min(axis=-1)

    ci = m6plot.pmCI(0.25, 4.5, .5)

    if cmdLineArgs.suptitle != '':
        suptitle = cmdLineArgs.suptitle + ' ' + cmdLineArgs.label
    else:
        suptitle = rootGroup.title + ' ' + cmdLineArgs.label

    # Global
    tPlot, z = zonalAverage(Tmod, Zmod, area)
    tObsPlot, _ = zonalAverage(Tobs, Zobs, area)
    if stream != None: objOut = stream[0]
    else: objOut = cmdLineArgs.outdir + '/T_global_xave_bias_WOA05.png'
    m6plot.yzplot(
        tPlot - tObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title=
        r'''Global zonal-average $\theta$ bias (w.r.t. WOA'05) [$\degree$C]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)

    if stream is None:
        m6plot.yzcompare(tPlot,
                         tObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1=r'Global zonal-average $\theta$ [$\degree$C]',
                         title2=r'''WOA'05 $\theta$ [$\degree$C]''',
                         clim=m6plot.linCI(-2, 29, .5),
                         colormap='dunneRainbow',
                         extend='max',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/T_global_xave_bias_WOA05.3_panel.png')

    # Atlantic + Arctic
    newMask = 1. * msk
    newMask[(basin != 2) & (basin != 4)] = 0.
    tPlot, z = zonalAverage(Tmod, Zmod, area, mask=newMask)
    tObsPlot, _ = zonalAverage(Tobs, Zobs, area, mask=newMask)
    if stream != None: objOut = stream[1]
    else: objOut = cmdLineArgs.outdir + '/T_Atlantic_xave_bias_WOA05.png'
    m6plot.yzplot(
        tPlot - tObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title=
        r'''Atlantic zonal-average $\theta$ bias (w.r.t. WOA'05) [$\degree$C]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)

    if stream is None:
        m6plot.yzcompare(
            tPlot,
            tObsPlot,
            y,
            z,
            splitscale=[0., -1000., -6500.],
            suptitle=suptitle,
            title1=r'Atlantic zonal-average $\theta$ [$\degree$C]',
            title2=r'''WOA'05 $\theta$ [$\degree$C]''',
            clim=m6plot.linCI(-2, 29, .5),
            colormap='dunneRainbow',
            extend='max',
            dlim=ci,
            dcolormap='dunnePM',
            dextend='both',
            centerdlabels=True,
            save=cmdLineArgs.outdir +
            '/T_Atlantic_xave_bias_WOA05.3_panel.png')

    # Pacific
    newMask = 1. * msk
    newMask[(basin != 3)] = 0.
    tPlot, z = zonalAverage(Tmod, Zmod, area, mask=newMask)
    tObsPlot, _ = zonalAverage(Tobs, Zobs, area, mask=newMask)
    if stream != None: objOut = stream[2]
    else: objOut = cmdLineArgs.outdir + '/T_Pacific_xave_bias_WOA05.png'
    m6plot.yzplot(
        tPlot - tObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title=
        r'''Pacific zonal-average $\theta$ bias (w.r.t. WOA'05) [$\degree$C]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)

    if stream is None:
        m6plot.yzcompare(tPlot,
                         tObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1=r'Pacific zonal-average $\theta$ [$\degree$C]',
                         title2=r'''WOA'05 $\theta$ [$\degree$C]''',
                         clim=m6plot.linCI(-2, 29, .5),
                         colormap='dunneRainbow',
                         extend='max',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/T_Pacific_xave_bias_WOA05.3_panel.png')

    # Indian
    newMask = 1. * msk
    newMask[(basin != 5)] = 0.
    tPlot, z = zonalAverage(Tmod, Zmod, area, mask=newMask)
    tObsPlot, _ = zonalAverage(Tobs, Zobs, area, mask=newMask)
    if stream != None: objOut = stream[3]
    else: objOut = cmdLineArgs.outdir + '/T_Indian_xave_bias_WOA05.png'
    m6plot.yzplot(
        tPlot - tObsPlot,
        y,
        z,
        splitscale=[0., -1000., -6500.],
        suptitle=suptitle,
        title=
        r'''Indian zonal-average $\theta$ bias (w.r.t. WOA'05) [$\degree$C]''',
        clim=ci,
        colormap='dunnePM',
        centerlabels=True,
        extend='both',
        save=objOut)

    if stream is None:
        m6plot.yzcompare(tPlot,
                         tObsPlot,
                         y,
                         z,
                         splitscale=[0., -1000., -6500.],
                         suptitle=suptitle,
                         title1=r'Indian zonal-average $\theta$ [$\degree$C]',
                         title2=r'''WOA'05 $\theta$ [$\degree$C]''',
                         clim=m6plot.linCI(-2, 29, .5),
                         colormap='dunneRainbow',
                         extend='max',
                         dlim=ci,
                         dcolormap='dunnePM',
                         dextend='both',
                         centerdlabels=True,
                         save=cmdLineArgs.outdir +
                         '/T_Indian_xave_bias_WOA05.3_panel.png')