def load_andremap_MLD(firstyear, lastyear, mesh, filetmp):
    "Load and compute (mean) mixed layer depth for the period (firstyear---lastyear)."

    # load the files into one dataset
    files = [filetmp.format(d) for d in range(firstyear, lastyear + 1, 1)]
    fl = MFDataset(files)

    print 'Computing mean, max, min ...'
    MLDmean = fl.variables['mixlay'][:, :].mean(axis=0)  # 1x 2D field
    MLDmax = fl.variables['mixlay'][:, :].max(axis=0)  # 1x 2D field
    MLDmin = fl.variables['mixlay'][:, :].min(axis=0)  # 1x 2D field
    print 'Done.'

    # load climatology
    climpath = '/mnt/lustre01/work/bm0944/a270046/DATA/climatology/'
    clim = pf.climatology(climpath, climname='phc')  # climname='phc'|'woa05'

    # map fesom data to PHC climatology grid
    xx, yy = np.meshgrid(clim.x, clim.y)
    zz_MLDmean = np.zeros((clim.T.shape[1], clim.T.shape[2]))
    zz_MLDmax = np.zeros((clim.T.shape[1], clim.T.shape[2]))
    zz_MLDmin = np.zeros((clim.T.shape[1], clim.T.shape[2]))

    distances, inds = pf.create_indexes_and_distances(mesh,
                                                      xx,
                                                      yy,
                                                      k=10,
                                                      n_jobs=2)

    # remap mean
    zz_MLDmean[:,:] = pf.fesom2regular(MLDmean, mesh, xx, yy, distances=distances,\
                                inds=inds, how='idist', k=10,\
                                radius_of_influence=200000)
    zz_MLDmax[:,:]  = pf.fesom2regular(MLDmax , mesh, xx, yy, distances=distances,\
                                inds=inds, how='idist', k=10,\
                                radius_of_influence=200000)
    zz_MLDmin[:,:]  = pf.fesom2regular(MLDmin , mesh, xx, yy, distances=distances,\
                                inds=inds, how='idist', k=10,\
                                radius_of_influence=200000)

    # set land to NaN
    zz_MLDmean[np.isnan(clim.T[0, :, :])] = np.nan
    zz_MLDmax[np.isnan(clim.T[0, :, :])] = np.nan
    zz_MLDmin[np.isnan(clim.T[0, :, :])] = np.nan

    return xx, yy, zz_MLDmean, zz_MLDmax, zz_MLDmin
コード例 #2
0
def showfile(ifile, variable, depth, meshpath, box, res, influence, timestep,
             levels, quiet, ofile, mapproj, abg, clim, cmap, interp, ptype, k):
    '''
    meshpath - Path to the folder with FESOM1.4 mesh files.

    ifile    - Path to FESOM1.4 netCDF file.

    variable - The netCDF variable to be plotted.
    '''
    if not quiet:
        click.secho('Mesh: {}'.format(meshpath))
        click.secho('File: {}'.format(ifile))
        click.secho('Variable: {}'.format(variable), fg='red')
        click.secho('Depth: {}'.format(depth), fg='red')
        click.secho('BOX: {}'.format(box))
        click.secho('Resolution: {}'.format(res))
        click.secho('Influence raduis: {} meters'.format(influence), fg='red')
        click.secho('Timestep: {}'.format(timestep))
        if levels:
            click.secho('Levels: {}'.format(levels), fg='red')
        else:
            click.secho('Levels: auto', fg='red')

    if cmap:
        if cmap in cmo.cmapnames:
            colormap = cmo.cmap_d[cmap]
        elif cmap in plt.cm.datad:
            colormap = plt.get_cmap(cmap)
        else:
            raise ValueError(
                'Get unrecognised name for the colormap `{}`. Colormaps should be from standard matplotlib set of from cmocean package.'
                .format(cmap))
    else:
        if clim:
            colormap = cmo.cmap_d['balance']
        else:
            colormap = plt.get_cmap('Spectral_r')

    sstep = timestep
    radius_of_influence = influence

    left, right, down, up = box
    lonNumber, latNumber = res

    mesh = pf.load_mesh(meshpath, abg=abg, usepickle=False, usejoblib=True)
    flf = Dataset(ifile)
    lonreg = np.linspace(left, right, lonNumber)
    latreg = np.linspace(down, up, latNumber)
    lonreg2, latreg2 = np.meshgrid(lonreg, latreg)

    dind = (abs(mesh.zlevs - depth)).argmin()
    realdepth = mesh.zlevs[dind]

    level_data, nnn = pf.get_data(flf.variables[variable][sstep], mesh,
                                  realdepth)
    if interp == 'nn':
        ofesom = pf.fesom2regular(level_data,
                                  mesh,
                                  lonreg2,
                                  latreg2,
                                  radius_of_influence=radius_of_influence)
    elif interp == 'idist':
        ofesom = pf.fesom2regular(level_data,
                                  mesh,
                                  lonreg2,
                                  latreg2,
                                  radius_of_influence=radius_of_influence,
                                  how='idist',
                                  k=k)
    elif interp == 'linear':
        points = np.vstack((mesh.x2, mesh.y2)).T
        qh = qhull.Delaunay(points)
        ofesom = LinearNDInterpolator(qh, level_data)((lonreg2, latreg2))

    elif interp == 'cubic':
        points = np.vstack((mesh.x2, mesh.y2)).T
        qh = qhull.Delaunay(points)
        ofesom = CloughTocher2DInterpolator(qh, level_data)((lonreg2, latreg2))

    if clim:
        if variable == 'temp':
            climvar = 'T'
        elif variable == 'salt':
            climvar = 'S'
        else:
            raise ValueError(
                'You have selected --clim/-c option, but variable `{}` is not in climatology. Acceptable values are `temp` and `salt` only.'
                .format(variable))
        #os.path.join(os.path.dirname(__file__), "../")
        pathToClim = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                  "../data/")
        print(pathToClim)
        w = pf.climatology(pathToClim, clim)
        xx, yy, oclim = pf.clim2regular(
            w,
            climvar,
            lonreg2,
            latreg2,
            levels=[realdepth],
            radius_of_influence=radius_of_influence)
        oclim = oclim[0, :, :]
        data = ofesom - oclim
    else:
        data = ofesom

    if mapproj == 'merc':
        ax = plt.subplot(111, projection=ccrs.Mercator())
    elif mapproj == 'pc':
        ax = plt.subplot(111, projection=ccrs.PlateCarree())
    elif mapproj == 'np':
        ax = plt.subplot(111, projection=ccrs.NorthPolarStereo())
    elif mapproj == 'sp':
        ax = plt.subplot(111, projection=ccrs.SouthPolarStereo())
    elif mapproj == 'rob':
        ax = plt.subplot(111, projection=ccrs.Robinson())

    ax.set_extent([left, right, down, up], crs=ccrs.PlateCarree())

    if levels:
        mmin, mmax, nnum = levels
        nnum = int(nnum)
    else:
        mmin = np.nanmin(data)
        mmax = np.nanmax(data)
        nnum = 40

    data_levels = np.linspace(mmin, mmax, nnum)
    if ptype == 'cf':
        mm = ax.contourf(lonreg,\
                     latreg,\
                     data,
                     levels = data_levels,
                     transform=ccrs.PlateCarree(),
                     cmap=colormap,
                    extend='both')
    elif ptype == 'pcm':
        data_cyc, lon_cyc = add_cyclic_point(data, coord=lonreg)
        mm = ax.pcolormesh(lon_cyc,\
                         latreg,\
                         data_cyc,
                         vmin = mmin,
                         vmax = mmax,
                         transform=ccrs.PlateCarree(),
                         cmap=colormap,
                        )
    else:
        raise ValueError('Inknown plot type {}'.format(ptype))

    ax.coastlines(resolution='50m', lw=0.5)
    ax.add_feature(
        cfeature.GSHHSFeature(levels=[1], scale='low', facecolor='lightgray'))
    cb = plt.colorbar(mm, orientation='horizontal', pad=0.03)
    cb.set_label(flf.variables[variable].units)
    plt.title('{} at {}m.'.format(variable, realdepth))
    plt.tight_layout()
    if ofile:
        plt.savefig(ofile, dpi=100)
    else:
        plt.show()
def load_andcompute_TSRho_split(firstyear, lastyear, mesh, filetmp):
    "Load and compute mean T, S, and density (sigma1) for the period (firstyear---lastyear). Split the computation in parts if you encounter memory errors."

    ## load the files into one dataset
    #files = [filetmp.format(d) for d in range(firstyear,lastyear+1,1)]
    #fl = MFDataset(files)
    #
    #print 'Computing mean ...'
    #temp = fl.variables['temp'][:,:].mean(axis=0) # 1x 3D field
    #salt = fl.variables['salt'][:,:].mean(axis=0) # 1x 3D field
    #print 'Done.'

    # load the files into one dataset
    files = [filetmp.format(d) for d in range(firstyear, lastyear + 1, 1)]
    fl = MFDataset(files)

    # initialize
    dim3D = np.shape(fl.variables['temp'][0, :])[0]
    temp = np.zeros(dim3D)
    salt = np.zeros(dim3D)

    print 'Computing mean ...'
    temp[0:dim3D / 2] = fl.variables['temp'][:, 0:dim3D / 2].mean(
        axis=0)  # 1x 3D field
    temp[dim3D / 2:] = fl.variables['temp'][:, dim3D / 2:].mean(
        axis=0)  # 1x 3D field
    salt[0:dim3D / 2] = fl.variables['salt'][:, 0:dim3D / 2].mean(
        axis=0)  # 1x 3D field
    salt[dim3D / 2:] = fl.variables['salt'][:, dim3D / 2:].mean(
        axis=0)  # 1x 3D field
    print 'Done.'

    # load climatology
    climpath = '/mnt/lustre01/work/bm0944/a270046/DATA/climatology/'
    clim = pf.climatology(climpath, climname='phc')  # climname='phc'|'woa05'

    # map fesom data to PHC climatology grid
    xx, yy, zz_temp_pot = pf.fesom2clim(temp,
                                        mesh,
                                        clim,
                                        verbose=False,
                                        how='idist',
                                        k_neighbors=10,
                                        radius_of_influence=200000)
    xx, yy, zz_salt = pf.fesom2clim(salt,
                                    mesh,
                                    clim,
                                    verbose=False,
                                    how='idist',
                                    k_neighbors=10,
                                    radius_of_influence=200000)

    # initialize additional variables
    zz_temp_insitu = np.copy(zz_temp_pot)

    zz_sigma_1 = np.zeros_like(zz_temp_pot)
    PHC_temp_insitu = np.zeros_like(zz_temp_pot)
    PHC_sigma_1 = np.zeros_like(zz_temp_pot)

    # for every layer (0 ... 32):
    for ilevel in np.arange(np.shape(clim.z)[0]):

        # FESOM PART
        # calculates temperature from potential temperature at the reference pressure PR and in situ pressure P
        zz_temp_insitu[ilevel, :, :] = sw.eos80.temp(zz_salt[ilevel, :, :],
                                                     zz_temp_pot[ilevel, :, :],
                                                     clim.z[ilevel],
                                                     pr=0)

        # density of Sea Water using UNESCO 1983 (EOS 80) polynomial
        zz_sigma_1[ilevel, :, :] = sw.eos80.pden(zz_salt[ilevel, :, :],
                                                 zz_temp_insitu[ilevel, :, :],
                                                 clim.z[ilevel],
                                                 pr=1000.) - 1000.

        # PHC PART (pot. 'clim' values are loaded in newest version of pyfesom)
        PHC_temp_insitu[ilevel, :, :] = sw.eos80.temp(clim.S[ilevel, :, :],
                                                      clim.T[ilevel, :, :],
                                                      clim.z[ilevel],
                                                      pr=0)
        PHC_sigma_1[ilevel, :, :] = sw.eos80.pden(
            clim.S[ilevel, :, :],
            PHC_temp_insitu[ilevel, :, :],
            clim.z[ilevel],
            pr=1000.) - 1000.

    return xx, yy, zz_temp_pot, zz_salt, clim, zz_sigma_1, PHC_sigma_1