Пример #1
0
def plot(c):
    r = resource()
    r.trYReverse = c.reverseY
    r.trXReverse = c.reverseX
    r.trXLog = c.XlogAxis
    r.trYLog = c.YlogAxis
    #
    #Line styles
    r.xyLineColors = lineColors
    r.xyLineThicknesses = lineThickness
    #Plot title
    r.tiMainString = c.PlotTitle
    #Axis labels (ToDo: add defaults)
    #X and Y axis labels
    r.tiXAxisString = c.Xlabel
    r.tiYAxisString = c.Ylabel
    if c.switchXY:
        r.tiXAxisString, r.tiYAxisString = r.tiYAxisString, r.tiXAxisString

    #  Legends, for multicurve plot
    legends = []
    for id in c.listVariables():
        if not id == c.Xid:
            if len(c.label[id]) > 0:
                legends.append(c.label[id])
            else:
                legends.append(id)
    #ToDo: Add option to skip legends
    #Legends are redundant if there's only one curve
    if len(legends) > 1:
        r.pmLegendDisplayMode = "Always"
        r.xyExplicitLegendLabels = legends
    #
    #Suppress line drawing and just plot symbol for scatter plot curves
    r.xyMarkers = plotSymbols
    r.xyMarkerColors = lineColors
    r.xyMarkerSizeF = .01
    r.xyMarkLineModes = []
    for id in c.listVariables():
        if not id == c.Xid:
            if c.scatter[id]:
                r.xyMarkLineModes.append('Markers')
            else:
                r.xyMarkLineModes.append('Lines')
    #
    w = Ngl.open_wks('x11', 'Climate Workbook')
    if c.switchXY:
        plot = Ngl.xy(w, c.Y(), c.X(), r)
    else:
        plot = Ngl.xy(w, c.X(), c.Y(), r)
    #
    #Now draw the plot
    r.nglDraw = True
    Ngl.panel(w, [plot], [1, 1], r)
    return plotObj(w, plot)  #So that user can delete window or save plot
Пример #2
0
def contour(A, **kwargs):
    #The following allows an expert user to pass
    #Ngl options directly to the plotter.
    #ToDo: Note that
    #options explicitly specified later will over-ride
    #what the user specified. This should be fixed,
    #by checking for things already specified. We should
    #also allow for using this resource to specify a color
    #map.
    if 'resource' in kwargs.keys():
        r = kwargs['resource']
    else:
        r = Dummy()
    #
    r.cnFillOn = True  #Uses color fill
    # Set axes if they have been specified
    # as keyword arguments
    if 'x' in kwargs.keys():
        r.sfXArray = kwargs['x']
    if 'y' in kwargs.keys():
        r.sfYArray = kwargs['y']
    #
    # Now create the plot

    rw = Dummy()
    #Set the color map
    if 'colors' in kwargs.keys():
        if (kwargs['colors'] == 'gray') or (kwargs['colors'] == 'grey'):
            #Set the default greyscale
            rw.wkColorMap = 'gsdtol'
        else:
            rw.wkColorMap = kwargs['colors']
    else:
        #Default rainbow color table
        rw.wkColorMap = "temp1"

    w = Ngl.open_wks('x11', 'Climate Workbook', rw)
    r.nglDraw = False
    r.nglFrame = False
    plot = Ngl.contour(w, A, r)
    #Now draw the plot
    r.nglDraw = True
    Ngl.panel(w, [plot], [1, 1], r)
    return plotObj(w, plot, rw)  #So user can delete or save plot
Пример #3
0
colors00 = Ngl.read_colormap_file("MPL_RdBu")
ncolors00 = colors00.shape[0]
colors0 = colors00[np.linspace(2,
                               ncolors00 - 1,
                               int((res.cnMaxLevelValF - res.cnMinLevelValF) /
                                   res.cnLevelSpacingF),
                               dtype=int), :]
grey_color = np.expand_dims(np.array([0.85, 0.85, 0.85, 1]), axis=0)
colors = np.append(grey_color, colors0[::-1, :], axis=0)

res.cnFillPalette = colors  #'BlWhRe' #'MPL_YlOrRd'         #-- choose color map
plot = []
title = 'CESM all forcing vs all forcing without ' + sf + ' effect ~C~FWI >= p' + str(
    pxx) + ' risk ratio'
for pp in range(5, nperiods, 1):
    for vv in range(0, n_vars, 1):
        print('period ' + str(pp + 1))
        #  res.tiMainString = var[vv]+' '+str(pyear0[pp])+'-'+str(pyear1[pp])
        res.tiMainString = ''
        riskratio_cyc, lon_cyc = Ngl.add_cyclic(
            riskratio_ens_agree_masked[vv, pp, :, :], lon)
        res.sfXArray = lon_cyc
        p = Ngl.contour_map(wks, riskratio_cyc, res)
        plot.append(p)

Ngl.panel(wks, plot, [n_vars, 1], pres)
#Ngl.text_ndc(wks,title,0.5,0.92,txres)
Ngl.frame(wks)

Ngl.delete_wks(wks)
Пример #4
0
def draw_clubb_bgt(ptype, cseason, ncases, cases, casenames, nsite, lats, lons,
                   filepath, filepathobs, casedir, varis, vname, cscale,
                   chscale, pname):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    _Font = 25
    interp = 2
    extrap = False
    mkres = Ngl.Resources()
    mkres.gsMarkerIndex = 2
    mkres.gsMarkerColor = "Red"
    mkres.gsMarkerSizeF = 15.
    infiles = ["" for x in range(ncases)]
    ncdfs = ["" for x in range(ncases)]
    nregions = nsite
    nvaris = len(varis)
    plotbgt = ["" for x in range(nsite * ncases)]
    alphas = [
        'a) ', 'b) ', 'c) ', 'd) ', 'e) ', 'f) ', 'g) ', 'h) ', 'i) ', 'j) ',
        'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ',
        'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) '
    ]

    for ire in range(0, nsite):
        for im in range(0, ncases):
            if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' +
                                  str(lats[ire]) + 'N'):
                os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' +
                         str(lats[ire]) + 'N')

            plotname = casedir + '/' + str(lons[ire]) + 'E_' + str(
                lats[ire]) + 'N/' + pname + '_' + casenames[im] + "_" + str(
                    lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason
            plotbgt[im +
                    ncases * ire] = pname + '_' + casenames[im] + "_" + str(
                        lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason

            wks = Ngl.open_wks(ptype, plotname)

            Ngl.define_colormap(wks, "radar")
            plot = []
            res = Ngl.Resources()
            res.nglDraw = False
            res.nglFrame = False
            res.nglScale = False
            #         res.vpWidthF         = 0.40                      # set width and height
            #         res.vpHeightF        = 0.40
            #         res.vpXF             = 0.04
            #         res.vpYF             = 0.30
            res.nglMaximize = False
            if (lats[ire] > 0 and lons[ire] < 230):
                res.trYMinF = 400.
                res.trYMaxF = 1000.
            else:
                res.trYMinF = 700.
                res.trYMaxF = 1000.

            res.tiMainFont = _Font
            res.tmYLLabelFont = _Font
            res.tmXBLabelFont = _Font
            res.tiYAxisFont = _Font
            res.tiXAxisFont = _Font

            res.tmXBLabelFontHeightF = 0.02
            res.tmXBLabelFontThicknessF = 1.0
            res.xyMarkLineMode = "MarkLines"
            res.xyLineThicknesses = [
                3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 2., 2., 2., 2, 2, 2, 2, 2, 2,
                2
            ]
            res.xyLineColors = np.arange(1, 16, 4)
            res.xyDashPatterns = np.arange(0, 24, 1)
            res.xyMarkers = np.arange(16, 40, 1)
            res.xyMarkerSizeF = 0.005
            res.xyMarkerColors = np.arange(1, 16, 4)

            res.pmLegendDisplayMode = "NEVER"
            res.pmLegendSide = "top"  # Change location of
            res.pmLegendParallelPosF = 0.75  # move units right
            res.pmLegendOrthogonalPosF = -0.65  # more neg = down
            res.pmLegendWidthF = 0.05  # Change width and
            res.pmLegendHeightF = 0.06  # height of legend.
            res.lgLabelFontHeightF = 0.03  # change font height
            res.lgLabelFontThicknessF = 1.

            #         res.lgBoxMinorExtentF      = 0.5
            res.lgPerimOn = False
            res.tiYAxisString = "Pressure [hPa]"
            res.tmYLLabelFontHeightF = 0.02

            res.trYReverse = True

            res1 = Ngl.Resources()
            res1 = res

            pres = Ngl.Resources()
            #         pres.gsnPaperOrientation= "Landscape"

            #         pres.wkPaperWidthF  = 20  # in inches
            #         pres.wkPaperHeightF = 28  # in inches

            pres.nglMaximize = False
            #         pres.vpWidthF         = 0.40                      # set width and height
            #         pres.vpHeightF        = 0.40

            pres.nglFrame = False
            pres.txFont = _Font
            pres.nglPanelYWhiteSpacePercent = 5
            pres.nglPanelXWhiteSpacePercent = 3
            pres.nglPanelTop = .9
            #         pres.nglPanelBottom=0.3
            #         pres.nglPanelLeft= 0.2
            #         pres.nglPanelRight= 0.95
            pres.nglPanelFigureStrings = alphas
            pres.nglPanelFigureStringsJust = 'Topleft'
            pres.nglPanelFigureStringsFontHeightF = 0.015

            for iv in range(0, nvaris):

                if (varis[iv] == "rtp2" or varis[iv] == "thlp2"):
                    budget_ends = ["_ta", "_tp", "_dp1"]
                    budget_name = [
                        '~F10~turb adv', '~F10~turb prod', '~F10~dissipation'
                    ]
                    nterms = len(budget_ends)
                if (varis[iv] == "wprtp"):
                    budget_ends = [
                        "_bt", "_ma", "_ta", "_tp", "_ac", "_bp", "_pr1",
                        "_pr2", "_pr3", "_dp1", "_mfl", "_cl", "_sicl", "_pd",
                        "_forcing"
                    ]
                    budget_name = budget_ends
                    nterms = len(budget_ends)
                if (varis[iv] == "wpthlp"):
                    budget_ends = ["_tp", "_bp", "_pr1"]
                    budget_name = [
                        '~F10~turb prod', '~F10~buoy+pres', '~F10~ret to iso'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == "rtpthlp"):
                    budget_ends = [
                        "_bt", "_ma", "_ta", "_tp1", "_tp2", "_dp1", "_dp2",
                        "_cl", "_sf", "_forcing"
                    ]
                    budget_name = budget_ends
                    nterms = len(budget_ends)
                if (varis[iv] == "wp2"):
                    budget_ends = ["_ta", "_bp", "_pr1", "_dp1", "_dp2"]
                    budget_name = budget_ends
                    nterms = len(budget_ends)

                if (varis[iv] == "wp3"):
                    budget_ends = [
                        "_ta", "_tp", "_bp1", "_bp2", "_pr1", "_pr2", "_dp1"
                    ]
                    budget_name = budget_ends
                    nterms = len(budget_ends)

                if (varis[iv] == "up2" or varis[iv] == "vp2"):
                    budget_ends = [
                        "_bt", "_ma", "_ta", "_tp", "_dp1", "_dp2", "_pr1",
                        "_pr2", "_cl", "_pd", "_sf"
                    ]
                    budget_name = budget_ends
                    nterms = len(budget_ends)

                if (varis[iv] == "um" or varis[iv] == "vm"):
                    budget_ends = ["_bt", "_ma", "_ta", "_gf", "_f"]
                    budget_name = budget_ends
                    nterms = len(budget_ends)

                if (varis[iv] == "thlm" or varis[iv] == "rtm"):
                    budget_ends = ["_bt", "_ma", "_ta", "_cl", "_mc"]
                    budget_name = budget_ends
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_no_N2_zm'):
                    budget_ends = ['tau_no_N2_zm', 'bkgnd', 'sfc', 'shear']
                    budget_name = [
                        '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bkgnd~N~',
                        '~F8~t~N~~F25~~B~shear~N~', '~F8~t~N~~F25~~B~shear~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_xp2_zm'):
                    budget_ends = ['tau_xp2_zm', 'tau_no_N2_zm']
                    budget_name = [
                        '~F8~t~N~~F25~~B~x`~S~2~N~~N~',
                        '~F8~t~N~~F25~~B~noN2~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_wp2_zm'):
                    budget_ends = ['tau_wp2_zm', 'tau_no_N2_zm', 'bvpos']
                    budget_name = [
                        '~F8~t~N~~F25~~B~w`~S~2~N~~N~',
                        '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_wpxp_zm'):
                    budget_ends = [
                        'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear'
                    ]
                    budget_name = [
                        '~F8~t~N~~F25~~B~w`x`~N~', '~F8~t~N~~F25~~B~noN2~N~',
                        '~F8~t~N~~F25~~B~bv~N~', '~F8~t~N~~F25~~B~clr~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_wp3_zm'):
                    budget_ends = [
                        'tau_wp3_zm', 'tau_no_N2_zm', 'bvpos', 'clear'
                    ]
                    budget_name = [
                        '~F8~t~N~~F25~~B~w`~S~3~N~~N~',
                        '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~',
                        '~F8~t~N~~F25~~B~clr~N~'
                    ]
                    nterms = len(budget_ends)

                ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
                infiles[im] = filepath[im] + cases[im] + '/' + cases[
                    im] + '_' + cseason + '_climo.nc'
                inptrs = Dataset(infiles[im], 'r')  # pointer to file1
                lat = inptrs.variables['lat'][:]
                nlat = len(lat)
                lon = inptrs.variables['lon'][:]
                nlon = len(lon)
                ilev = inptrs.variables['ilev'][:]
                nilev = len(ilev)
                ncdf = Dataset(ncdfs[im], 'r')
                n = ncdf.variables['n'][:]
                idx_cols = ncdf.variables['idx_cols'][:, :]
                ncdf.close()
                A_field = np.zeros((nterms, nilev), np.float32)

                for it in range(0, nterms):
                    for subc in range(0, n[ire]):
                        npoint = idx_cols[ire, n[subc] - 1] - 1

                        varis_bgt = varis[iv] + budget_ends[it]
                        tmp0 = inptrs.variables[varis[iv]][0, :, npoint]
                        theunits0 = "~F25~" + inptrs.variables[varis[iv]].units

                        if (varis[iv] == 'wpthlp'
                                and budget_ends[it] == '_bp'):
                            tmp = inptrs.variables[varis_bgt][
                                0, :, npoint] + inptrs.variables['wpthlp_pr3'][
                                    0, :, npoint]
                        else:
                            tmp = inptrs.variables[varis_bgt][0, :, npoint]
                        theunits = str(
                            chscale[iv]) + "~F25~" + inptrs.variables[
                                varis[iv] + '_bt'].units

                        if (varis[iv] == "wprtp" or varis[iv] == "thlp2"):
                            tmp[0:10] = 0.0
                            tmp0[0:10] = 0.0
                        txres = Ngl.Resources()
                        txres.txFontHeightF = 0.02
                        txres.txFont = _Font

                        tmp = tmp * cscale[iv]
                        A_field[it, :] = (A_field[it, :] +
                                          tmp[:] / n[ire]).astype(np.float32)

                inptrs.close()
                res.tiXAxisString = vname[iv] + '  Unit=  ' + theunits

                if (varis[iv] == "wpthlp" or varis[iv] == "thlp2"
                        or varis[iv] == "wp3" or varis[iv] == "wp2"):
                    res1.tiXAxisString = vname[iv] + '  Unit=  ' + theunits0
                    p0 = Ngl.xy(wks, tmp0, ilev, res1)
                    plot.append(p0)

                if (varis[iv] == 'wpthlp'):
                    if (lons[ire] < 230):
                        res.trXMinF = -1.
                        res.trXMaxF = 1.
                        Common_functions.create_legend(wks, budget_name, 0.013,
                                                       np.arange(1, 16, 4),
                                                       0.77, 0.85 - iv * 0.45)
                    else:
                        res.trXMinF = -0.4
                        res.trXMaxF = 0.4
                        Common_functions.create_legend(wks, budget_name, 0.013,
                                                       np.arange(1, 16, 4),
                                                       0.77, 0.85 - iv * 0.45)

                if (varis[iv] == 'thlp2'):
                    if (lons[ire] < 230):
                        res.trXMinF = -2.8
                        res.trXMaxF = 2.8
                        Common_functions.create_legend(wks, budget_name, 0.013,
                                                       np.arange(1, 16, 4),
                                                       0.77, 0.85 - iv * 0.45)
                    else:
                        res.trXMinF = -1.
                        res.trXMaxF = 1.
                        Common_functions.create_legend(wks, budget_name, 0.013,
                                                       np.arange(1, 16, 4),
                                                       0.77, 0.85 - iv * 0.45)

                res.tiXAxisString = vname[iv] + '  Unit=  ' + theunits
                p = Ngl.xy(wks, A_field, ilev, res)
                plot.append(p)

                del (res.trXMaxF)
                del (res.trXMinF)
                xp = np.mod(iv, 2)
                yp = int(iv / 2)

            Ngl.panel(wks, plot[:], [nvaris, 2], pres)
            txres = Ngl.Resources()
            txres.txFont = _Font
            txres.txFontHeightF = 0.02

            Ngl.text_ndc(
                wks, casenames[im] + "  BUDGET at " + str(lons[ire]) + "E," +
                str(lats[ire]) + "N", 0.5, 0.91, txres)
            Ngl.frame(wks)
            Ngl.destroy(wks)

    return (plotbgt)
Пример #5
0
def plot_power(Pow, symmetry=("symm"), source="", var1="", plotpath="./", flim=0.5, nWavePlt=20, cmin=0.05, cmax=0.55,
               cspc=0.05, plotxy=[1, 1], N=[1, 2]):

    dims = Pow.shape
    nplot = dims[0]

    FillMode = "AreaFill"

    # text labels
    abc = list(string.ascii_lowercase)

    # plot resources
    wkstype = "png"
    wks = ngl.open_wks(wkstype, plotpath + "SpaceTimePower_" + source + var1)
    plots = []

    # coherence2 plot resources
    res = coh_resources(cmin, cmax, cspc, FillMode, flim, nWavePlt)
    # phase arrow resources
    resA = phase_resources(flim, nWavePlt)

    # dispersion curve resources
    dcres = ngl.Resources()
    dcres.gsLineThicknessF = 2.0
    dcres.gsLineDashPattern = 0

    # text box resources
    txres = ngl.Resources()
    txres.txPerimOn = True
    txres.txFontHeightF = 0.013
    txres.txBackgroundFillColor = "Background"

    # panel plot resources
    resP = panel_resources(nplot, abc)

    # plot contours and phase arrows
    pp = 0
    while pp < nplot:
        if nplot == 1:
            coh2 = Pow
        else:
            coh2 = Pow[pp, :, :]
        if len(symmetry) == nplot:
            Symmetry = symmetry[pp]
        else:
            Symmetry = symmetry

        res.tiMainString = source + "    log10( Power(" + var1 + "))           " + Symmetry
        plot = ngl.contour(wks, coh2, res)

        (matsuno_names, textlabels, textlocsX, textlocsY) = text_labels(Symmetry)
        nlabel = len(textlocsX)

        # generate matsuno mode dispersion curves
        if Symmetry == "midlat":
            He = [3000, 7000, 10000]
            matsuno_modes = mp.matsuno_modes_wk_bg(he=He, n=N, latitude=0., max_wn=nWavePlt, n_wn=500, u=25)
        else:
            He = [12, 25, 50]
            matsuno_modes = mp.matsuno_modes_wk(he=He, n=N, latitude=0., max_wn=nWavePlt, n_wn=500)

        # add polylines for dispersion curves
        for he in matsuno_modes:
            df = matsuno_modes[he]
            wn = df.index.values
            for wavename in df:
                for matsuno_name in matsuno_names:
                    if wavename == (matsuno_name + str(he) + "m)"):
                        wave = df[wavename].values
                        wnwave = wn[~np.isnan(wave)]
                        wave = wave[~np.isnan(wave)]
                        ngl.add_polyline(wks, plot, wnwave, wave, dcres)

        # add text boxes
        ll = 0
        while ll < nlabel:
            ngl.add_text(wks, plot, textlabels[ll], textlocsX[ll], textlocsY[ll], txres)
            ll += 1

        plots.append(plot)
        pp += 1

        # panel plots
    ngl.panel(wks, plots, plotxy, resP)
    ngl.delete_wks(wks)
    #ngl.end()

    return
Пример #6
0
res.cnMinLevelValF     = -0.1#0.45#-0.1             #-- contour min. value
res.cnMaxLevelValF     = 2.0#1.5#2.0          #-- contour max. value
res.cnLevelSpacingF    = 0.1#0.05#0.1             #-- contour interval
colors00 = Ngl.read_colormap_file("MPL_RdBu")
ncolors00= colors00.shape[0]
colors0 = colors00[np.linspace(2,ncolors00-1,int((res.cnMaxLevelValF-res.cnMinLevelValF)/res.cnLevelSpacingF),dtype=int),:] 
grey_color = np.expand_dims(np.array([0.85, 0.85, 0.85, 1]), axis=0)
colors = np.append(grey_color,colors0[::-1,:],axis=0)

res.cnFillPalette      = colors#'BlWhRe' #'MPL_YlOrRd'         #-- choose color map
plot = []
title = 'CESM all forcing vs '+sf+' foricng~C~FWI >= p'+str(pxx)+' risk ratio'
for pp in range(2,nperiods,1):
 print('period '+str(pp+1))
 res.tiMainString = str(pyear0[pp])+'-'+str(pyear1[pp]) 
 riskratio_cyc, lon_cyc = Ngl.add_cyclic(riskratio_ens_agree_masked[pp,:,:], lon)
 res.sfXArray           =  lon_cyc
 p = Ngl.contour_map(wks,riskratio_cyc,res)
 if pp==(nperiods-1):
  for rr in range(0,n_reg,1):
   poly_y = [df_reg['reg_N'][rr],df_reg['reg_S'][rr],df_reg['reg_S'][rr],df_reg['reg_N'][rr],df_reg['reg_N'][rr]]
   poly_x = [df_reg['reg_E'][rr],df_reg['reg_E'][rr],df_reg['reg_W'][rr],df_reg['reg_W'][rr],df_reg['reg_E'][rr]]
   poly_reg = Ngl.add_polygon(wks,p,poly_x,poly_y,gsres)
 plot.append(p)

Ngl.panel(wks,plot,[4,1],pres)
Ngl.text_ndc(wks,title,0.5,0.92,txres)
Ngl.frame(wks)

Ngl.delete_wks(wks)
Пример #7
0
def large_scale_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir):


# ncases, the number of models
# cases, the name of models
# casename, the name of cases
# filepath, model output filepath
# filepathobs, filepath for observational data
# inptrs = [ncases]
 if not os.path.exists(casedir):
        os.mkdir(casedir)

 _Font   = 25
 interp = 2
 extrap = False
 mkres = Ngl.Resources()
 mkres.gsMarkerIndex = 2
 mkres.gsMarkerColor = 'Red'
 mkres.gsMarkerSizeF = 15.
 infiles  = ['' for x in range(ncases)]
 ncdfs    = ['' for x in range(ncases)]
 nregions = nsite
 localnames=np.append('ERAI',casenames)
 varis    = [ 'CLOUD'  , 'CLDLIQ', 'THETA','RELHUM']
 varisobs = ['CC_ISBL', 'CLWC_ISBL', 'THETA','RELHUM' ]
 alphas   = ['a) ','b) ','c) ','d) ','e) ','f) ','g) ','h) ','i) ', 'j) ', 'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ', 'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) ']

 nvaris = len(varis)
 cunits = ['%','g/kg','K', '%' ]
 cscale = [100, 1000 , 1.,   1 ]
 cscaleobs = [100, 1000 , 1.,   1,     1,   1000,     1,1,1,1,1,1,1]
 obsdataset =['ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI','ERAI','ERAI']

 plotlgs=['' for x in range(nsite)]


 for ire in range (0, nsite):
     if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'):
         os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N')

     plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/Largescale_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason
     plotlgs[ire] = 'Largescale_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason

     wks= Ngl.open_wks(ptype,plotname)
     Ngl.define_colormap(wks,'GMT_paired')
     plot = []

     res     = Ngl.Resources()
     res.nglMaximize          =  False
     res.nglDraw              = False
     res.nglFrame             = False
     res.lgPerimOn              = False                 # no box around
     res.vpWidthF         = 0.30                      # set width and height
     res.vpHeightF        = 0.30

     res.tiYAxisString   = "Pressure [hPa]"

     if (lats[ire] > 0 and lons[ire]<230 ):
         res.trYMinF = 400.
         res.trYMaxF = 1000.
     else:
         res.trYMinF = 700.
         res.trYMaxF = 1000.


     res.tiMainFont        = _Font
     res.tmYLLabelFont  = _Font
     res.tmXBLabelFont  = _Font
     res.tiYAxisFont =  _Font
     res.tiXAxisFont =  _Font

     res.tmXBLabelFontHeightF = 0.01
     res.tmXBLabelFontThicknessF = 1.0
     res.xyMarkLineMode      = 'Lines'
     res.xyLineThicknesses = [3.0, 3.0, 3.0, 3.0, 3.0, 3.0,3.,3.,3.,3.,3,3,3,3,3,3,3]

     res.xyDashPatterns    = np.arange(0,24,1)

     pres            = Ngl.Resources()
     pres.nglFrame = False
     pres.txFont     = _Font
     pres.nglPanelYWhiteSpacePercent = 5
     pres.nglPanelXWhiteSpacePercent = 5
#     pres.nglPanelTop = 0.88
     pres.wkPaperWidthF  = 17  # in inches
     pres.wkPaperHeightF = 28  # in inches
     pres.nglMaximize = True
     pres.nglPanelTop                      = 0.935
     pres.nglPanelFigureStrings            = alphas
     pres.nglPanelFigureStringsJust        = 'Topleft'
     pres.nglPanelFigureStringsFontHeightF = 0.015


     for iv in range (0, nvaris):   
         if(iv == nvaris-1):
             res.pmLegendDisplayMode    = 'NEVER'
             res.xyExplicitLegendLabels = casenames[:]
             res.pmLegendSide           = 'top'             
             res.pmLegendParallelPosF   = 0.6               
             res.pmLegendOrthogonalPosF = -0.5                  
             res.pmLegendWidthF         = 0.10              
             res.pmLegendHeightF        = 0.10          
             res.lgLabelFontHeightF     = .02               
             res.lgLabelFontThicknessF  = 1.5
             res.lgPerimOn              = True
         else:
             res.pmLegendDisplayMode    = 'NEVER'


         if(obsdataset[iv] =='CCCM'):
             if(cseason == 'ANN'):
                 fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-'+cseason+'.nc'
             else:
                 fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-'+cseason+'.nc'
             inptrobs = Dataset(fileobs,'r')
             latobs=inptrobs.variables['lat'][:]
             latobs_idx = np.abs(latobs - lats[ire]).argmin()
             lonobs=inptrobs.variables['lon'][:]
             lonobs_idx = np.abs(lonobs - lons[ire]).argmin()

             B=inptrobs.variables[varisobs[iv]][:,latobs_idx,lonobs_idx]
         else:
             if (varisobs[iv] =='PRECT'):
                 fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc'
             else:
                 fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc'
             inptrobs = Dataset(fileobs,'r')
             if (varisobs[iv] =='THETA'):
                 latobs=inptrobs.variables['lat'][:]
                 latobs_idx = np.abs(latobs - lats[ire]).argmin()
                 lonobs=inptrobs.variables['lon'][:]
                 lonobs_idx = np.abs(lonobs - lons[ire]).argmin()
                 B = inptrobs.variables['T'][0,:,latobs_idx,lonobs_idx]
                 pre1 = inptrobs.variables['lev'][:]
                 for il1 in range (0, len(pre1)):
                     B[il1] = B[il1]*(1000/pre1[il1])**0.286
             else: 
                 pre1 = inptrobs.variables['lev'][:]
                 latobs=inptrobs.variables['lat'][:]
                 latobs_idx = np.abs(latobs - lats[ire]).argmin()
                 lonobs=inptrobs.variables['lon'][:]
                 lonobs_idx = np.abs(lonobs - lons[ire]).argmin()

                 B = inptrobs.variables[varisobs[iv]][0,:,latobs_idx,lonobs_idx]

         B[:]=B[:] * cscaleobs[iv]


         for im in range (0,ncases):
             ncdfs[im]  = './data/'+cases[im]+'_site_location.nc'
             infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc'
             inptrs = Dataset(infiles[im],'r')       # pointer to file1
             lat=inptrs.variables['lat'][:]
             nlat=len(lat)
             lon=inptrs.variables['lon'][:]
             nlon=len(lon)
             lev=inptrs.variables['lev'][:]
             nlev=len(lev)
             ncdf= Dataset(ncdfs[im],'r')
             n   =ncdf.variables['n'][:]
             idx_cols=ncdf.variables['idx_cols'][:,:]
             ncdf.close()
             if (im ==0 ):
                 A_field = np.zeros((ncases,nlev),np.float32)

             for subc in range( 0, n[ire]):
                 npoint=idx_cols[ire,n[subc]-1]-1
                 if (varis[iv] == 'THETA'):
                     tmp = inptrs.variables['T'][0,:,npoint]
                     hyam =inptrs.variables['hyam'][:]
                     hybm =inptrs.variables['hybm'][:]
                     ps=inptrs.variables['PS'][0,npoint] 
                     ps=ps
                     p0=inptrs.variables['P0']
                     pre = np.zeros((nlev),np.float32)
                     for il in range (0, nlev):
                         pre[il] = hyam[il]*p0 + hybm[il] * ps
                         tmp[il] = tmp[il] * (100000/pre[il])**0.286
                     theunits=str(cscale[iv])+inptrs.variables['T'].units

                 else:
                     tmp=inptrs.variables[varis[iv]][0,:,npoint] 
                     theunits=str(cscale[iv])+inptrs.variables[varis[iv]].units
                 A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 )

             A_field[im,:] = A_field[im,:] *cscale[iv]
             inptrs.close()

         textres               = Ngl.Resources()
         textres.txFontHeightF = 0.02   
         textres.txFont        = _Font
         textres.txFontHeightF = 0.015

         res.tiXAxisString   = varis[iv]+ "  Unit=  " + cunits[iv]
         res.trXMinF = min(np.min(A_field[0, :]),np.min(B))
         res.trXMaxF = max(np.max(A_field[0, :]),np.max(B))

         if(varis[iv] == 'CLOUD') :
            if (lats[ire] >= 0 and lons[ire]<230): 
               res.trXMinF = 0.
               res.trXMaxF = 50.
            else:
               res.trXMinF = 0.
               res.trXMaxF = 100.

         if(varis[iv] =='CLDLIQ') :
            if (lats[ire] >= 0):
               res.trXMinF = 0.
               res.trXMaxF = 0.1
            else:
               res.trXMinF = 0.
               res.trXMaxF = 0.1

         if(varis[iv] =='RELHUM') :
             res.trXMinF = 0.
             res.trXMaxF = 100.

         if(varis[iv] == 'THETA') :
            if (lats[ire] >= 0 and lons[ire]<230 ):
               res.trXMinF = 290.
               res.trXMaxF = 340.
            else:
               res.trXMinF = 280
               res.trXMaxF = 320

         if(varis[iv] == 'T') :
             res.trXMinF = 180
             res.trXMaxF = 300
         if(varis[iv] == 'U') :
             res.trXMinF = -40
             res.trXMaxF = 40
         res.trYReverse        = True
         res.xyLineColors      = np.arange(3,20,2)
         res.xyMarkerColors    = np.arange(2,20,2)
         p = Ngl.xy(wks,A_field,lev,res)
         
         res.trYReverse        = False
         res.xyLineColors      = ['black']
         pt = Ngl.xy(wks,B,pre1,res)

         Ngl.overlay(p,pt)
         plot.append(p)

     Ngl.panel(wks,plot[:],[nvaris/2,2],pres)
     txres = Ngl.Resources()
     txres.txFontHeightF = 0.02
     txres.txFont        = _Font
     Ngl.text_ndc(wks,'Large-scale VAR at '+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.93,txres)
     Common_functions.create_legend(wks,localnames,0.02,np.append('black',np.arange(3,20,2)),0.25,0.85)


     Ngl.frame(wks)
     Ngl.destroy(wks)

 return plotlgs
Пример #8
0
res2.trXMinF = faxis[0]    # Limits for X axis
res2.trXMaxF = faxis[-1] 


res2.tiXAxisString = "~F25~Frequency (Hz)"
res2.tiYAxisString = "~F25~Power Spectrum"
leftname = "Period from ~F34~%~F25~ to {} seconds".format(1./faxis[-1])
res2.tiMainString = "Spectral Analysis (FFT)"+ \
                    "~C~~B~"+leftname

plot = []
plot.append(Ngl.xy(wks,t,sig,res))
plot.append(Ngl.xy(wks,faxis,PS,res2))

#wrf_tools.ngl_Strings(wks, plot[0], left=leftname, center="", right="")

panelres = Ngl.Resources()

Ngl.panel(wks,plot[0:1+1],[2,1],panelres)  

#Ngl.draw(plot[0])
#Ngl.frame(wks)
Ngl.destroy(wks); del res, plot

Ngl.end()

end_time = cpu_time(); end_time = (end_time - start_time)/60.0
print(os.path.basename(__file__)+" has done!\nTime elapsed: {:.2f}".format(end_time), "mins.")

Пример #9
0
            pres.nglFrame = False
            pres.nglPanelLabelBar = True

            # Calculate start Y position for first row of plots
            height = 0.275  # we know this will be height of small plots
            extra = 1.0 - (3 * height)
            top = 1.0 - (extra / 2.)  # 子图第一行所在的高度

            # Draw a title before we draw plots
            title = figData[3]['headLineTxt']
            txres = Ngl.Resources()
            txres.txJust = "BottomCenter"
            txres.txFontHeightF = 0.02
            Ngl.text_ndc(wks, title, 0.5, top + 0.01, txres)

            # # Loop across plots and panel them on one page
            # for n in range(0,1):
            #     # Define location in a unit square for each set of plots.
            pres.nglPanelTop = top - (0 * height)
            pres.nglPanelBottom = top - ((2 + 1) * height)
            pres.nglPanelYWhiteSpacePercent = 3

            Ngl.panel(wks, plots[0:7], [3, 2], pres)
            # plot = Ngl.contour_map(wks, plotData, res)

            # Ngl.draw(plot)

            Ngl.frame(wks)
            Ngl.destroy(wks)
            # Ngl.end()
Пример #10
0
def large_scale_prf(ptype, cseason, ncases, cases, casenames, nsite, lats,
                    lons, filepath, filepathobs, casedir, dofv):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    _Font = 25
    interp = 2
    extrap = False
    mkres = Ngl.Resources()
    mkres.gsMarkerIndex = 2
    mkres.gsMarkerColor = "Red"
    mkres.gsMarkerSizeF = 15.
    infiles = ["" for x in range(ncases)]
    ncdfs = ["" for x in range(ncases)]
    nregions = nsite

    varis = [
        "CLOUD", "OMEGA", "Q", "CLDLIQ", "THETA", "RELHUM", "U", "CLDICE", "T"
    ]
    varisobs = [
        "CC_ISBL", "OMEGA", "SHUM", "CLWC_ISBL", "THETA", "RELHUM", "U",
        "CIWC_ISBL", "T"
    ]
    nvaris = len(varis)
    cunits = [
        "%", "mba/day", "g/kg", "g/kg", "K", "%", "m/s", "g/kg", "m/s", "m/s",
        "K", "m"
    ]
    cscale = [100, 864, 1000, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1]
    cscaleobs = [100, 1, 1, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1]
    obsdataset = [
        "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI",
        "ERAI"
    ]

    plotlgs = ["" for x in range(nsite)]

    for ire in range(0, nsite):
        if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' +
                              str(lats[ire]) + 'N'):
            os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) +
                     'N')

        plotname = casedir + '/' + str(lons[ire]) + 'E_' + str(
            lats[ire]) + 'N/Largescale_' + str(lons[ire]) + "E_" + str(
                lats[ire]) + "N_" + cseason
        plotlgs[ire] = 'Largescale_' + str(lons[ire]) + "E_" + str(
            lats[ire]) + "N_" + cseason

        wks = Ngl.open_wks(ptype, plotname)
        Ngl.define_colormap(wks, "GMT_paired")
        plot = []

        res = Ngl.Resources()
        res.nglMaximize = False
        res.nglDraw = False
        res.nglFrame = False
        res.lgPerimOn = False  # no box around
        res.vpWidthF = 0.30  # set width and height
        res.vpHeightF = 0.30

        res.tiYAxisString = "Pressure [hPa]"
        res.tiMainFont = _Font
        res.tmYLLabelFont = _Font
        res.tmXBLabelFont = _Font
        res.tiYAxisFont = _Font
        res.tiXAxisFont = _Font

        res.tmXBLabelFontHeightF = 0.01
        res.tmXBLabelFontThicknessF = 1.0
        res.xyMarkLineMode = 'Lines'

        #     res.tmXBLabelAngleF = 45
        res.xyLineThicknesses = [
            3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3
        ]

        res.xyDashPatterns = np.arange(0, 24, 1)

        pres = Ngl.Resources()
        pres.nglFrame = False
        pres.txString = "Large-scale VAR at" + str(lons[ire]) + "E," + str(
            lats[ire]) + "N"
        pres.txFont = _Font
        pres.nglPanelYWhiteSpacePercent = 5
        pres.nglPanelXWhiteSpacePercent = 5
        pres.nglPanelTop = 0.88
        pres.wkPaperWidthF = 17  # in inches
        pres.wkPaperHeightF = 28  # in inches
        pres.nglMaximize = True
        pres.wkWidth = 10000
        pres.wkHeight = 10000

        for iv in range(0, nvaris):
            if (iv == nvaris - 1):
                res.pmLegendDisplayMode = "NEVER"
                res.xyExplicitLegendLabels = casenames[:]
                res.pmLegendSide = "top"
                res.pmLegendParallelPosF = 0.6
                res.pmLegendOrthogonalPosF = -0.5
                res.pmLegendWidthF = 0.10
                res.pmLegendHeightF = 0.10
                res.lgLabelFontHeightF = .02
                res.lgLabelFontThicknessF = 1.5
                res.lgPerimOn = True
            else:
                res.pmLegendDisplayMode = "NEVER"

            if (obsdataset[iv] == "CCCM"):
                if (cseason == "ANN"):
                    fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc"
                else:
                    fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc"
                inptrobs = Dataset(fileobs, 'r')
                latobs = inptrobs.variables['lat'][:]
                latobs_idx = np.abs(latobs - lats[ire]).argmin()
                lonobs = inptrobs.variables['lon'][:]
                lonobs_idx = np.abs(lonobs - lons[ire]).argmin()

                B = inptrobs.variables[varisobs[iv]][:, latobs_idx, lonobs_idx]
            else:
                if (varisobs[iv] == "PRECT"):
                    fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc'
                else:
                    fileobs = filepathobs + obsdataset[
                        iv] + '_' + cseason + '_climo.nc'
                inptrobs = Dataset(fileobs, 'r')
                if (varisobs[iv] == "THETA"):
                    latobs = inptrobs.variables['lat'][:]
                    latobs_idx = np.abs(latobs - lats[ire]).argmin()
                    lonobs = inptrobs.variables['lon'][:]
                    lonobs_idx = np.abs(lonobs - lons[ire]).argmin()
                    B = inptrobs.variables['T'][0, :, latobs_idx, lonobs_idx]
                    pre1 = inptrobs.variables['lev'][:]
                    for il1 in range(0, len(pre1)):
                        B[il1] = B[il1] * (1000 / pre1[il1])**0.286
                else:
                    pre1 = inptrobs.variables['lev'][:]
                    latobs = inptrobs.variables['lat'][:]
                    latobs_idx = np.abs(latobs - lats[ire]).argmin()
                    lonobs = inptrobs.variables['lon'][:]
                    lonobs_idx = np.abs(lonobs - lons[ire]).argmin()

                    B = inptrobs.variables[varisobs[iv]][0, :, latobs_idx,
                                                         lonobs_idx]

            B[:] = B[:] * cscaleobs[iv]

            for im in range(0, ncases):
                ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
                infiles[im] = filepath[im] + '/' + cases[
                    im] + '_' + cseason + '_climo.nc'
                inptrs = Dataset(infiles[im], 'r')  # pointer to file1
                lat = inptrs.variables['lat'][:]
                nlat = len(lat)
                lon = inptrs.variables['lon'][:]
                nlon = len(lon)
                lev = inptrs.variables['lev'][:]
                nlev = len(lev)
                ncdf = Dataset(ncdfs[im], 'r')
                n = ncdf.variables['n'][:]
                idx_cols = ncdf.variables['idx_cols'][:, :]
                if (dofv):
                    idx_lats = ncdf.variables['idx_coord_lat'][:, :]
                    idx_lons = ncdf.variables['idx_coord_lon'][:, :]
                ncdf.close()
                theunits = "[units]"
                if (im == 0):
                    A_field = np.zeros((ncases, nlev), np.float32)

                for subc in range(0, n[ire]):
                    npoint = idx_cols[ire, n[subc] - 1] - 1
                    if (dofv):
                        npointlat = idx_lats[ire, 0]
                        npointlon = idx_lons[ire, 0]
                    if (varis[iv] == 'THETA'):
                        if (dofv):
                            tmp = inptrs.variables['T'][0, :, npointlat,
                                                        npointlon]
                        else:
                            tmp = inptrs.variables['T'][0, :, npoint]
                        hyam = inptrs.variables['hyam'][:]
                        hybm = inptrs.variables['hybm'][:]
                        if (dofv):
                            ps = inptrs.variables['PS'][0, npointlat,
                                                        npointlon]
                        else:
                            ps = inptrs.variables['PS'][0, npoint]
                        ps = ps
                        p0 = 100000.0  #CAM uses a hard-coded p0
                        pre = np.zeros((nlev), np.float32)
                        for il in range(0, nlev):
                            pre[il] = hyam[il] * p0 + hybm[il] * ps
                            tmp[il] = tmp[il] * (100000 / pre[il])**0.286
                        theunits = str(
                            cscale[iv]) + "x" + inptrs.variables['T'].units

                    else:
                        if (dofv):
                            tmp = inptrs.variables[varis[iv]][0, :, npointlat,
                                                              npointlon]
                        else:
                            tmp = inptrs.variables[varis[iv]][0, :, npoint]
                        theunits = str(cscale[iv]) + "x" + inptrs.variables[
                            varis[iv]].units
                    ##import pdb; pdb.set_trace()
                    A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype(
                        np.float32)

                A_field[im, :] = A_field[im, :] * cscale[iv]
                inptrs.close()

            res.tiMainString = varis[iv] + "  " + theunits
            res.trXMinF = min(np.min(A_field[0, :]), np.min(B))
            res.trXMaxF = max(np.max(A_field[0, :]), np.max(B))
            if (varis[iv] == "THETA"):
                res.trXMinF = 270.
                res.trXMaxF = 400.
            if (varis[iv] == "CLOUD" or varis[iv] == "RELHUM"):
                res.trXMinF = 0.
                res.trXMaxF = 100.
            if (varis[iv] == "T"):
                res.trXMinF = 180
                res.trXMaxF = 300
            if (varis[iv] == "U"):
                res.trXMinF = -40
                res.trXMaxF = 40
            res.trYReverse = True
            res.xyLineColors = np.arange(3, 20, 2)
            res.xyMarkerColors = np.arange(2, 20, 2)
            p = Ngl.xy(wks, A_field, lev, res)

            res.trYReverse = False
            res.xyLineColors = ["black"]
            pt = Ngl.xy(wks, B, pre1, res)
            Ngl.overlay(p, pt)
            plot.append(p)

        Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres)
        txres = Ngl.Resources()
        txres.txFontHeightF = 0.02
        txres.txFont = _Font
        Ngl.text_ndc(
            wks, "Large-scale VAR at" + str(lons[ire]) + "E," +
            str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres)
        Common_functions.create_legend(wks, casenames, 0.02,
                                       np.arange(3, 20,
                                                 2), 0.1, 0.89 + ncases * 0.01)

        Ngl.frame(wks)
        Ngl.destroy(wks)

    return plotlgs
Пример #11
0
            # Resources for panelling
            pres = Ngl.Resources()
            pres.nglFrame = False
            pres.nglPanelLabelBar = True

            # Calculate start Y position for first row of plots
            height = 0.8  # we know this will be height of small plots
            extra = 1.0 - (height)
            top = 1.0 - (extra / 2.)  #子图第一行所在的高度

            # Draw a title before we draw plots
            title = figData[3]['headLineTxt']
            txres = Ngl.Resources()
            txres.txJust = "BottomCenter"
            txres.txFontHeightF = 0.02
            Ngl.text_ndc(wks, title, 0.5, top + 0.01, txres)

            # Define location in a unit square for each set of plots.
            pres.nglPanelTop = top
            pres.nglPanelBottom = top - height

            Ngl.panel(wks, plots[0:nplots], [3, 1], pres)

            # plot = Ngl.contour_map(wks, plotData, res)

            # Ngl.draw(plot)

            Ngl.frame(wks)
            Ngl.destroy(wks)
            # Ngl.end()
Пример #12
0
def draw_2D_plot(ptype, cseason, ncases, cases, casenames, nsite, lats, lons,
                 filepath, filepathobs, casedir):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    if not os.path.exists(casedir + '/2D'):
        os.mkdir(casedir + '/2D')

    _Font = 25
    interp = 2
    extrap = False
    infiles = ['' for x in range(ncases)]
    ncdfs = ['' for x in range(ncases)]
    alpha = ['A', 'B', 'C', 'D', 'E', 'F']
    cunits = ['']
    varis = [
        'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'TMQ', 'PS', 'TS', 'U10',
        'CLDTOT', 'CLDLOW', 'CLDHGH', 'TGCLDLWP'
    ]
    varisobs = [
        'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'PREH2O', 'PS', 'TS', 'U10',
        'CLDTOT_CAL', 'CLDTOT_CAL', 'CLDTOT_CAL', 'TGCLDLWP_OCEAN'
    ]
    nvaris = len(varis)
    cscale = [1, 1, 86400000, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1000, 1, 1, 1]
    cscaleobs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    # cntrs = [[0 for col in range(11)] for row in range(nvaris)]
    cntrs = np.zeros((nvaris, 11), np.float32)

    obsdataset = [
        'CERES-EBAF', 'CERES-EBAF', 'GPCP', 'ERAI', 'NCEP', 'ERAI', 'NCEP',
        'ERAI', 'ERAI', 'CALIPSOCOSP', 'CALIPSOCOSP', 'CALIPSOCOSP', 'NVAP'
    ]

    plot2d = ['' for x in range(nvaris)]
    for iv in range(0, nvaris):
        # make plot for each field
        if (varis[iv] == 'CLDTOT' or varis[iv] == 'CLDLOW'
                or varis[iv] == 'CLDHGH'):
            cntrs[iv, :] = [2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90]
        if (varis[iv] == 'LWCF'):
            cntrs[iv, :] = [1, 2, 5, 10, 15, 20, 25, 30, 35, 40, 45]
        if (varis[iv] == 'SWCF' or varis[iv] == 'FLUT'):
            cntrs[iv, :] = [
                -40, -50, -60, -70, -80, -90, -100, -110, -120, -130, -140
            ]
        if (varis[iv] == 'PRECT' or varis[iv] == 'QFLX'):
            cntrs[iv, :] = [0.5, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15]
        if (varis[iv] == 'LHFLX'):
            cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
        if (varis[iv] == 'SHFLX'):
            cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
        if (varis[iv] == 'U10'):
            cntrs[iv, :] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        if (varis[iv] == 'TMQ'):
            cntrs[iv, :] = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
        if (varis[iv] == 'TGCLDLWP'):
            cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]

#  Observational data
        if (obsdataset[iv] == 'CCCM'):
            if (cseason == 'ANN'):
                fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-' + cseason + '.nc'
            else:
                fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-' + cseason + '.nc'
        else:
            if (varisobs[iv] == 'PRECT'):
                fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc'
            else:
                fileobs = filepathobs + obsdataset[
                    iv] + '_' + cseason + '_climo.nc'

#       infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc'

        inptrobs = Dataset(fileobs, 'r')
        latobs = inptrobs.variables['lat'][:]
        lonobs = inptrobs.variables['lon'][:]
        if (varisobs[iv] == 'U10'):
            B0 = inptrobs.variables[varisobs[iv]][0, :, :]
            B1 = inptrobs.variables['V10'][0, :, :]
            B = (B0 * B0 + B1 * B1)
            B = B * cscaleobs[iv]
            B = np.sqrt(B)
        else:
            B = inptrobs.variables[varisobs[iv]][0, :, :]
            B = B * cscaleobs[iv]

        #************************************************
        # create plot
        #************************************************
        plotname = casedir + '/2D/Horizontal_' + varis[iv] + '_' + cseason
        plot2d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason
        wks = Ngl.open_wks(ptype, plotname)
        Ngl.define_colormap(wks, 'cmocean_thermal')
        #   Ngl.define_colormap(wks,'MPL_coolwarm')

        #   ngl_define_colormap(wks,'prcp_1')
        plot = []

        textres = Ngl.Resources()
        textres.txFontHeightF = 0.02  # Size of title.
        textres.txFont = _Font
        Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres)

        pres = Ngl.Resources()
        pres.nglMaximize = True
        pres.nglPanelYWhiteSpacePercent = 5
        pres.nglPanelXWhiteSpacePercent = 5
        pres.nglPanelBottom = 0.20
        pres.nglPanelTop = 0.9
        pres.pmLabelBarWidthF = 0.8
        pres.nglFrame = False
        pres.nglPanelLabelBar = True  # Turn on panel labelbar
        pres.nglPanelLabelBarLabelFontHeightF = 0.015  # Labelbar font height
        pres.nglPanelLabelBarHeightF = 0.0750  # Height of labelbar
        pres.nglPanelLabelBarWidthF = 0.700  # Width of labelbar
        pres.lbLabelFont = 'helvetica-bold'  # Labelbar font
        pres.nglPanelTop = 0.935
        pres.nglPanelFigureStrings = alpha
        pres.nglPanelFigureStringsJust = 'BottomRight'

        res = Ngl.Resources()
        res.nglDraw = False  #-- don't draw plots
        res.nglFrame = False
        res.cnFillOn = True
        res.cnFillMode = 'RasterFill'
        res.cnLinesOn = False
        res.nglMaximize = True
        res.mpFillOn = True
        res.mpCenterLonF = 180
        res.tiMainFont = _Font
        res.tiMainFontHeightF = 0.025
        res.tiXAxisString = ''
        res.tiXAxisFont = _Font
        res.tiXAxisFontHeightF = 0.025
        res.tiYAxisString = ''
        res.tiYAxisFont = _Font
        res.tiYAxisOffsetXF = 0.0
        res.tiYAxisFontHeightF = 0.025
        res.tmXBLabelFont = _Font
        res.tmYLLabelFont = _Font
        res.tiYAxisFont = _Font
        res.vpWidthF = 0.80  # set width and height
        res.vpHeightF = 0.40
        res.vpXF = 0.04
        res.vpYF = 0.30

        res.cnInfoLabelOn = False
        res.cnFillOn = True
        res.cnLinesOn = False
        res.cnLineLabelsOn = False
        res.lbLabelBarOn = False

        #   res.vcRefMagnitudeF = 5.
        #   res.vcMinMagnitudeF = 1.
        #   res.vcRefLengthF    = 0.04
        #   res.vcRefAnnoOn     = True#False
        #   res.vcRefAnnoZone   = 3
        #   res.vcRefAnnoFontHeightF = 0.02
        #   res.vcRefAnnoString2 =''
        #   res.vcRefAnnoOrthogonalPosF   = -1.0
        #  res.vcRefAnnoArrowLineColor   = 'blue'         # change ref vector color
        #  res.vcRefAnnoArrowUseVecColor = False
        #   res.vcMinDistanceF  = .05
        #   res.vcMinFracLengthF         = .
        #   res.vcRefAnnoParallelPosF    =  0.997
        #   res.vcFillArrowsOn           = True
        #   res.vcLineArrowThicknessF    =  3.0
        #   res.vcLineArrowHeadMinSizeF   = 0.01
        #   res.vcLineArrowHeadMaxSizeF   = 0.03
        #   res.vcGlyphStyle              = 'CurlyVector'     # turn on curley vectors
        #  res@vcGlyphStyle              ='Fillarrow'
        #   res.vcMonoFillArrowFillColor = True
        #   res.vcMonoLineArrowColor     = True
        #   res.vcLineArrowColor          = 'green'           # change vector color
        #   res.vcFillArrowEdgeColor      ='white'
        #   res.vcPositionMode            ='ArrowTail'
        #   res.vcFillArrowHeadInteriorXF =0.1
        #   res.vcFillArrowWidthF         =0.05           #default
        #   res.vcFillArrowMinFracWidthF  =.5
        #   res.vcFillArrowHeadMinFracXF  =.5
        #   res.vcFillArrowHeadMinFracYF  =.5
        #   res.vcFillArrowEdgeThicknessF = 2.0
        res.mpFillOn = False

        res.cnLevelSelectionMode = 'ExplicitLevels'

        res.cnLevels = cntrs[iv][:]

        for im in range(0, ncases):
            ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
            infiles[im] = filepath[im] + cases[im] + '/' + cases[
                im] + '_' + cseason + '_climo.nc'
            inptrs = Dataset(infiles[im], 'r')  # pointer to file1
            lat = inptrs.variables['lat'][:]
            nlat = len(lat)
            lon = inptrs.variables['lon'][:]
            nlon = len(lon)
            area = inptrs.variables['area'][:]

            area_wgt = np.zeros(nlat)

            sits = np.linspace(0, nsite - 1, nsite)
            ncdf = Dataset(ncdfs[im], 'r')
            n = ncdf.variables['n'][:]
            idx_cols = ncdf.variables['idx_cols'][:]
            if (varis[iv] == 'PRECT'):
                A = inptrs.variables['PRECC'][
                    0, :] + inptrs.variables['PRECL'][0, :]
            else:
                A = inptrs.variables[varis[iv]][0, :]

            if (varis[iv] == 'FLUT'):
                A = inptrs.variables['FLUT'][0, :] - inptrs.variables['FLNS'][
                    0, :]
            else:
                A = inptrs.variables[varis[iv]][0, :]

            if (varis[iv] == 'U10'):
                A = inptrs.variables['U10'][0, :] * inptrs.variables['U10'][
                    0, :]
                A = np.sqrt(A)
            else:
                A = inptrs.variables[varis[iv]][0, :]

            A_xy = A
            A_xy = A_xy * cscale[iv]
            ncdf.close()
            inptrs.close()

            if im == 0:
                dsizes = len(A_xy)
                field_xy = [[0 for col in range(dsizes)]
                            for row in range(ncases)]

            field_xy[im][:] = A_xy

            res.lbLabelBarOn = False
            if (np.mod(im, 2) == 0):
                res.tiYAxisOn = True
            else:
                res.tiYAxisOn = False

            res.tiXAxisOn = False
            res.sfXArray = lon
            res.sfYArray = lat
            res.mpLimitMode = 'LatLon'
            res.mpMaxLonF = max(lon)
            res.mpMinLonF = min(lon)
            res.mpMinLatF = min(lat)
            res.mpMaxLatF = max(lat)
            res.tiMainString = 'GLB=' + str(
                np.sum(A_xy[:] * area[:] / np.sum(area)))
            textres.txFontHeightF = 0.015
            Ngl.text_ndc(wks, alpha[im] + '  ' + casenames[im], 0.3,
                         .135 - im * 0.03, textres)

            p = Ngl.contour_map(wks, A_xy, res)
            plot.append(p)

# observation
#   res.nglLeftString = obsdataset[iv]
#  res@lbLabelBarOn = True
#  res@lbOrientation        = 'vertical'         # vertical label bars
        res.lbLabelFont = _Font
        res.tiYAxisOn = True
        res.tiXAxisOn = True
        res.tiXAxisFont = _Font
        rad = 4.0 * np.arctan(1.0) / 180.0
        re = 6371220.0
        rr = re * rad

        dlon = abs(lonobs[2] - lonobs[1]) * rr
        dx = dlon * np.cos(latobs * rad)
        jlat = len(latobs)
        dy = np.zeros(jlat, dtype=float)
        # close enough
        dy[0] = abs(lat[2] - lat[1]) * rr
        dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5
        dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr
        area_wgt = dx * dy  #
        is_SE = False

        sum1 = 0
        sum2 = 0

        for j in range(0, jlat - 1):
            for i in range(0, len(lonobs) - 1):
                if (np.isnan(B[j][i]) != '--'):
                    sum1 = sum1 + area_wgt[j] * B[j][i]
                    sum2 = sum2 + area_wgt[j]

        glb = sum1 / sum2
        res.sfXArray = lonobs
        res.sfYArray = latobs
        res.mpLimitMode = 'LatLon'
        res.mpMaxLonF = max(lonobs)
        res.mpMinLonF = min(lonobs)
        res.mpMinLatF = min(latobs)
        res.mpMaxLatF = max(latobs)
        res.tiMainString = 'GLB=' + str(glb)

        p = Ngl.contour_map(wks, B, res)
        if (iv == 0):
            poly_res = Ngl.Resources()
            poly_res.gsMarkerIndex = 16
            poly_res.gsMarkerSizeF = 0.005
            poly_res.gsMarkerColor = 'green'
            dum = Ngl.add_polymarker(wks, p, lons, lats, poly_res)

        plot.append(p)

        if (np.mod(ncases + 1, 2) == 1):
            Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres)
        else:
            Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres)
        Ngl.frame(wks)
        Ngl.destroy(wks)


#   Ngl.end()
    return plot2d
Пример #13
0
def draw_clm_plot (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir):

# ncases, the number of models
# cases, the name of models
# casename, the name of cases
# filepath, model output filepath
# filepathobs, filepath for observational data
# inptrs = [ncases]
 if not os.path.exists(casedir):
        os.mkdir(casedir)

 if not os.path.exists(casedir+"/2D"):
        os.mkdir(casedir+"/2D") 

 _Font   = 25
 interp = 2
 extrap = False
 mkres = Ngl.Resources()
 mkres.gsMarkerIndex = 2
 mkres.gsMarkerColor = "Red"
 mkres.gsMarkerSizeF = 15.   
 infiles  = ["" for x in range(ncases)] 
 ncdfs    = ["" for x in range(ncases)] 
 varis    = ["SOILWATER_10CM",     "QBOT"]
 varisobs = ["PRECT"              ,"PRECT"]
 alpha    = ["A","B","C","D","E","F"]
 nvaris = len(varis)
 cunits = [""]
 cscale = [1,1,1,86400000, 1,  1,1,100,100,1,1,1000,1,1,1,1]
 cscaleobs =  [1,1,1,1,1,1,1,1,1,1,1,1,1,1]
# cntrs = [[0 for col in range(11)] for row in range(nvaris)]
 cntrs = np.zeros((nvaris,11),np.float32)

 obsdataset=  ["GPCP","GPCP", "NCEP", "ERAI", "CALIPSOCOSP","CALIPSOCOSP","NCEP","NCEP","NVAP"]
 
 plotclm=["" for x in range(nvaris)]
 for iv in range(0, nvaris):
# make plot for each field 
   if(varis[iv] == "SOILWATER_10CM" or varis[iv] == "QBOT" ):
       cntrs[iv,:] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]






#  Observational data
   if(obsdataset[iv] =="CCCM"):
       if(cseason == "ANN"):
           fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc"
       else:
           fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc"
   else:
       if (varisobs[iv] =="PRECT"):
           fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc'
       else:
           fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc'

#       infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc'


   inptrobs = Dataset(fileobs,'r') 
   latobs=inptrobs.variables['lat'][:]
   lonobs=inptrobs.variables['lon'][:]
   if (varisobs[iv] =="U10"):
      B0=inptrobs.variables[varisobs[iv]][0,:,:] 
      B1=inptrobs.variables["V10"][0,:,:]
      B=(B0*B0+B1*B1)
      B=B * cscaleobs[iv]
      B=np.sqrt(B)
   else:
      B=inptrobs.variables[varisobs[iv]][0,:,:]
      B=B * cscaleobs[iv]

   #************************************************
   # create plot
   #************************************************
   plotname = casedir+'/2D/Land_'+varis[iv]+'_'+cseason
   plotclm[iv] = 'Land_'+varis[iv]+'_'+cseason
   wks= Ngl.open_wks(ptype,plotname)
   Ngl.define_colormap(wks,"cmocean_thermal")
 
#   ngl_define_colormap(wks,"prcp_1")
   plot = []

   textres               = Ngl.Resources()
   textres.txFontHeightF = 0.02   # Size of title.
   textres.txFont        = _Font
   Ngl.text_ndc(wks,varis[iv],0.1,.97,textres)

   pres            = Ngl.Resources()
   pres.nglMaximize = True
   pres.nglPanelYWhiteSpacePercent = 5
   pres.nglPanelXWhiteSpacePercent = 5
   pres.nglPanelBottom = 0.20
   pres.nglPanelTop = 0.9
   pres.pmLabelBarWidthF        = 0.8
   pres.nglFrame         = False
   pres.nglPanelLabelBar                 = True     # Turn on panel labelbar
   pres.nglPanelLabelBarLabelFontHeightF = 0.015    # Labelbar font height
   pres.nglPanelLabelBarHeightF          = 0.0750   # Height of labelbar
   pres.nglPanelLabelBarWidthF           = 0.700    # Width of labelbar
   pres.lbLabelFont                      = "helvetica-bold" # Labelbar font
   pres.nglPanelTop                      = 0.935
   pres.nglPanelFigureStrings            = alpha
   pres.nglPanelFigureStringsJust        = "BottomRight"


   res = Ngl.Resources()
   res.nglDraw         =  False            #-- don't draw plots
   res.nglFrame        =  False  
   res.cnFillOn     = True
   res.cnFillMode   = "RasterFill"
   res.cnLinesOn    = False
   res.nglMaximize = True
   res.mpFillOn     = True
   res.mpCenterLonF = 180
   res.tiMainFont                     = _Font
   res.tiMainFontHeightF              = 0.025
   res.tiXAxisString                  = ""
   res.tiXAxisFont                    = _Font
   res.tiXAxisFontHeightF             = 0.025
   res.tiYAxisString                  = ""
   res.tiYAxisFont                    = _Font
   res.tiYAxisOffsetXF                = 0.0
   res.tiYAxisFontHeightF             = 0.025       
   res.tmXBLabelFont = _Font
   res.tmYLLabelFont = _Font
   res.tiYAxisFont   = _Font
   res.vpWidthF         = 0.80                      # set width and height
   res.vpHeightF        = 0.40
   res.vpXF             = 0.04
   res.vpYF             = 0.30

   res.cnInfoLabelOn                  = False  
   res.cnFillOn                       = True
   res.cnLinesOn                      = False
   res.cnLineLabelsOn                 = False
   res.lbLabelBarOn                   = False
 
   res.mpFillOn                   = False
   
   res.cnLevelSelectionMode = "ExplicitLevels"

   res.cnLevels      = cntrs[iv][:]

   for im in range(0, ncases):
       ncdfs[im]  = './data/'+cases[im]+'_site_location.nc' 
       infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_clm.nc'
       inptrs = Dataset(infiles[im],'r')       # pointer to file1
       lat=inptrs.variables['lat'][:]
       nlat=len(lat)
       lon=inptrs.variables['lon'][:]
       nlon=len(lon)
       area=inptrs.variables['area'][:]

       area_wgt = np.zeros(nlat)

       sits=np.linspace(0,nsite-1,nsite)
       ncdf= Dataset(ncdfs[im],'r')
       n   =ncdf.variables['n'][:]
       idx_cols=ncdf.variables['idx_cols'][:]
       if (varis[iv] == 'PRECT'):
           A = inptrs.variables['PRECC'][0,:]+inptrs.variables['PRECL'][0,:]
       else:
           A = inptrs.variables[varis[iv]][0,:]

       if (varis[iv] == 'FLUT'):
           A = inptrs.variables['FLUT'][0,:]-inptrs.variables['FLNS'][0,:]
       else:
           A = inptrs.variables[varis[iv]][0,:]

       if (varis[iv] == 'U10'):
           A = inptrs.variables['U10'][0,:]*inptrs.variables['U10'][0,:]
           A = np.sqrt(A)
       else:
           A = inptrs.variables[varis[iv]][0,:]


       A_xy=A
       A_xy = A_xy * cscale[iv]
       ncdf.close()
       inptrs.close()

       if im == 0 :
           dsizes = len(A_xy)
           field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] 
       
       field_xy[im][:] = A_xy
  
       res.lbLabelBarOn = False 
       if(np.mod(im,2)==0): 
           res.tiYAxisOn  = True
       else:
           res.tiYAxisOn  = False
  
       res.tiXAxisOn  = False 
       res.sfXArray     = lon
       res.sfYArray     = lat
       res.mpLimitMode  = "LatLon"
       res.mpMaxLonF    = max(lon) 
       res.mpMinLonF    = min(lon) 
       res.mpMinLatF    = min(lat) 
       res.mpMaxLatF    = max(lat) 
       res.tiMainString    =  "GLB="+str(np.sum(A_xy[:]*area[:]/np.sum(area)))
       textres.txFontHeightF = 0.015
       Ngl.text_ndc(wks,alpha[im]+"  "+ casenames[im],0.3,.135-im*0.03,textres)

       
#       varM = A_xy
#       for ix in range(0, nlon-1):
#         if ( np.isnan(A_xy[ix]) or not np.isfinite(A_xy[ix])):
#            varM[ix]=0.0

       p = Ngl.contour_map(wks,A_xy,res)
       plot.append(p)

   res.lbLabelFont          = _Font
   res.tiYAxisOn  = True
   res.tiXAxisOn  = True
   res.tiXAxisFont = _Font
   rad    = 4.0*np.arctan(1.0)/180.0
   re     = 6371220.0
   rr     = re*rad

   dlon   = abs(lonobs[2]-lonobs[1])*rr
   dx     = dlon* np.cos(latobs*rad)
   jlat   = len(latobs )
   dy     = np.zeros(jlat,dtype=float)
                                                            # close enough
   dy[0]  = abs(lat[2]-lat[1])*rr
   dy[1:jlat-2]  = abs(lat[2:jlat-1]-lat[0:jlat-3])*rr*0.5
   dy[jlat-1]    = abs(lat[jlat-1]-lat[jlat-2])*rr
   area_wgt   = dx*dy  # 
   is_SE= False

   sum1 = 0 
   sum2 = 0 

   for j in range(0, jlat-1):
      for i in range(0, len(lonobs)-1):
        if (np.isnan(B[j][i]) != "--"):
           sum1= sum1+area_wgt[j]*B[j][i]
           sum2= sum2+area_wgt[j]
   
   glb=sum1/sum2
   res.sfXArray     = lonobs
   res.sfYArray     = latobs
   res.mpLimitMode  = "LatLon"
   res.mpMaxLonF    = max(lonobs)
   res.mpMinLonF    = min(lonobs)
   res.mpMinLatF    = min(latobs)
   res.mpMaxLatF    = max(latobs)
   res.tiMainString   =  "GLB="+str(glb)


   p =Ngl.contour_map(wks,B,res)
   plot.append(p)

   if(np.mod(ncases+1,2)==1):
      Ngl.panel(wks,plot[:],[(ncases+1)/2+1,2],pres) 
   else:
      Ngl.panel(wks,plot[:],[(ncases+1)/2,2],pres)
   Ngl.frame(wks)
   Ngl.destroy(wks)

#   Ngl.end()
 return plotclm
Пример #14
0
# directory. (The Ngl.pynglpath function is used to determine the
# directory.)
#
# Make sure the rangs database exists before we try to generate this frame.
#
rangs_dir = Ngl.pynglpath("rangs")  # Location of RANGS dir.

if (os.path.exists(rangs_dir)):
    nmap = 3
else:
    nmap = 2
    print("Sorry, you do not have the RANGS database installed.")
    print("Will not generate the third frame of this example.")

plot = []
for i in range(nmap):
    res.mpDataBaseVersion = map_res[i]
    res.tiMainString = "Resolution = '" + map_res[i] + "'"
    plot.append(Ngl.contour_map(wks, fsd, res))  # Create plot, but don't draw

#
# Set some panel resources: a common labelbar and title.
# "[1,3]" indicates 1 row, 3 columns.
#
panelres = Ngl.Resources()
panelres.txString = "Comparison of coastline resolutions"
panelres.nglPanelLabelBar = True  # Common labelbar
Ngl.panel(wks, plot, [1, 3], panelres)

Ngl.end()
def silhs_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir):

# ncases, the number of models
# cases, the name of models
# casename, the name of cases
# filepath, model output filepath
# filepathobs, filepath for observational data
# inptrs = [ncases]
 if not os.path.exists(casedir):
        os.mkdir(casedir)

 _Font   = 25
 interp = 2
 extrap = False
 mkres = Ngl.Resources()
 mkres.gsMarkerIndex = 2
 mkres.gsMarkerColor = "Red"
 mkres.gsMarkerSizeF = 15.
 infiles  = ["" for x in range(ncases)]
 ncdfs    = ["" for x in range(ncases)]
 nregions = nsite

 varis    = [ "SILHS_CLUBB_PRECIP_FRAC","SILHS_CLUBB_ICE_SS_FRAC","HR","AWNC","AWNI","ADSNOW","ANSNOW","AQSNOW","RHW","QRS","QRL","AQRAIN" ]
 nvaris = len(varis)
 cunits = ["%","mba/day","g/kg","g/kg","K", "%", "m/s", "g/kg", "m/s", "m/s","K","m" ]
 cscale = [1, 1, 1, 1, 1., 1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ]

 plotsilhs=["" for x in range(nsite)]

 for ire in range (0, nsite):
     if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'):
         os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N')

     plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/silhs_'+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason
     plotsilhs[ire] = 'CLUBB_standard_'+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason
     wks= Ngl.open_wks(ptype,plotname)

     Ngl.define_colormap(wks,"GMT_paired")
     plot = []
     res     = Ngl.Resources()
     res.nglDraw              = False
     res.nglFrame             = False
     res.lgLabelFontHeightF     = .012                   # change font height
     res.lgPerimOn              = False                 # no box around
     res.vpWidthF         = 0.30                      # set width and height
     res.vpHeightF        = 0.30
     res.txFontHeightF   = .01
     #res.vpXF             = 0.04
     # res.vpYF             = 0.30
     res.tmYLLabelFont  = _Font 
     res.tmXBLabelFont  = _Font 
     res.tmXBLabelFontHeightF = 0.005
     res.tmXBLabelFontThicknessF = 1.0
     res.tmXBLabelAngleF = 45
     res.xyMarkLineMode      = "Lines"
     res.xyLineThicknesses = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,2.,2.,2.,2.,2,2,2,2,2,2,2]

     res.xyDashPatterns    = np.arange(0,24,1)
#     res.xyMarkers         = np.arange(16,40,1)
#     res.xyMarkerSizeF       = 0.005


     pres            = Ngl.Resources()
     pres.nglMaximize = True

     pres.txString   = str(lons[ire])+"E,"+str(lats[ire])+"N"
     pres.txFont = _Font 
     pres.nglPanelYWhiteSpacePercent = 5
     pres.nglPanelXWhiteSpacePercent = 5
     pres.nglPanelTop = 0.93

     txres               = Ngl.Resources()
     txres.txFontHeightF = 0.01
     for iv in range (0, nvaris):   
         if(iv == nvaris-1):
             res.pmLegendDisplayMode    = "ALWAYS"
             res.xyExplicitLegendLabels = casenames[:]
             res.pmLegendSide           = "top"             
             res.pmLegendParallelPosF   = 0.6               
             res.pmLegendOrthogonalPosF = -0.5                  
             res.pmLegendWidthF         = 0.10              
             res.pmLegendHeightF        = 0.10          
             res.lgLabelFontHeightF     = .02               
             res.lgLabelFontThicknessF  = 1.5
             res.lgPerimOn              = False
         else:
             res.pmLegendDisplayMode    = "NEVER"



         for im in range (0,ncases):
             ncdfs[im]  = './data/'+cases[im]+'_site_location.nc'
             infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc'
             inptrs = Dataset(infiles[im],'r')       # pointer to file1
             lat=inptrs.variables['lat'][:]
             nlat=len(lat)
             lon=inptrs.variables['lon'][:]
             nlon=len(lon)
             lev=inptrs.variables['ilev'][:]
             nlev=len(lev)
             ncdf= Dataset(ncdfs[im],'r')
             n   =ncdf.variables['n'][:]
             idx_cols=ncdf.variables['idx_cols'][:,:]
             ncdf.close()
             if (im ==0):
                 A_field = np.zeros((ncases,nlev),np.float32)

             for subc in range( 0, n[ire]):
                 npoint=idx_cols[ire,n[subc]-1]-1
                 if (varis[iv] == 'THETA'):
                     tmp = inptrs.variables['T'][0,:,npoint]
                     hyam =inptrs.variables['hyam'][:]
                     hybm =inptrs.variables['hybm'][:]
                     ps=inptrs.variables['PS'][0,npoint] 
                     ps=ps
                     p0=inptrs.variables['P0']
                     pre = np.zeros((nlev),np.float32)
                     for il in range (0, nlev):
                         pre[il] = hyam[il]*p0 + hybm[il] * ps
                         tmp[il] = tmp[il] * (100000/pre[il])**0.286
                     theunits=str(cscale[iv])+inptrs.variables['T'].units

                 else:
                     tmp=inptrs.variables[varis[iv]][0,:,npoint] 
                     theunits=str(cscale[iv])+inptrs.variables[varis[iv]].units
                 A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 )
             A_field[im,:] = A_field[im,:] *cscale[iv]

             inptrs.close()
         res.tiMainString    =  varis[iv]+"  x"+theunits
         res.trXMinF = min(np.min(A_field[0, :]))#,np.min(B))
         res.trXMaxF = max(np.max(A_field[0, :]))#,np.max(B))
         if(varis[iv] == "THETA"):
             res.trXMinF = 280.
             res.trXMaxF = 400.
         if(varis[iv] == "CLOUD" or varis[iv] =="RELHUM") :
             res.trXMinF = 0.
             res.trXMaxF = 100.
         if(varis[iv] == "T") :
             res.trXMinF = 180
             res.trXMaxF = 300
         if(varis[iv] == "U") :
             res.trXMinF = -40
             res.trXMaxF = 40
         res.trYReverse        = True
         res.xyLineColors      = np.arange(2,20,1)
         res.xyMarkerColors    = np.arange(2,20,2)
         p = Ngl.xy(wks,A_field,lev,res)
         
         plot.append(p)


     Ngl.panel(wks,plot[:],[nvaris/3,3],pres)
     txres = Ngl.Resources()
     txres.txFontHeightF = 0.020
     Ngl.text_ndc(wks,"SILHS VAR at"+ str(lons[ire])+"E,"+str(lats[ire])+"N",0.5,0.05,txres)


     Ngl.frame(wks)

     Ngl.destroy(wks)

 return plotsilhs
Пример #16
0
    txres = Ngl.Resources()
    txres.txJust = "BottomCenter"
    txres.txFontHeightF = 0.02
    Ngl.text_ndc(wks, title, 0.5, top + 0.01, txres)

    # # Loop across plots and panel them on one page
    # for n in range(0,1):
    #     # Define location in a unit square for each set of plots.
    # add 子图序号
    pres.tiMainFont = "Helvetica-Bold"
    pres.nglPanelFigureStringsPerimOn = False
    pres.nglPanelFigureStringsJust = "TopLeft"
    # pres.nglPanelFigureStringsFont = "Helvetica-Bold"
    pres.nglPanelFigureStringsOrthogonalPosF = -0.66
    pres.nglPanelFigureStringsParallelPosF = -0.525
    pres.nglPanelFigureStringsFontHeightF = 0.017
    pres.nglPanelFigureStrings = figData[3]['seqNum']

    pres.nglPanelTop = top - (0 * height)  # leave room for title
    pres.nglPanelBottom = top - (f_row * height)
    pres.nglPanelYWhiteSpacePercent = 3

    Ngl.panel(wks, plots[0:nplots + 1], [f_row, f_col], pres)
    # plot = Ngl.contour_map(wks, plotData, res)

    # Ngl.draw(plot)

    Ngl.frame(wks)
    Ngl.destroy(wks)
    # Ngl.end()
Пример #17
0
def plotline(nlines,plotin,yearsin,nsep,title,Datatitle,figtitlein,colormap,xString,yString,unit):
        wkres = Ngl.Resources()
        wkres.wkColorMap = colormap
        wks_type = "eps"
        wks = Ngl.open_wks(wks_type,figtitlein,wkres)

	res = Ngl.Resources()
        plot = []

        res.tiXAxisString = xString
        res.tiYAxisString = yString

	for iline in range(0,nlines):
                yearsplot = yearsin[iline]
                print yearsplot
#               nyearsin = len(yearsplot)
#               yearnums = range(0,nyearsin)
                A = np.array(yearsplot)
                regress = (np.zeros((5,nsep),np.float))

                for ibin in range(0,nsep):
                        if ibin == 0:
                                if (plotdensity):
                                        res.tiYAxisString = "frequency"
                                else:
                                        res.tiYAxisString = "number of events"
                        else:
                                res.tiYAxisString = ""

                        linreg = plotin[iline][ibin][:]
                        print A.shape
                        print linreg.shape
                        regress[:,ibin] = stats.linregress(A,linreg)

                        if ibin == nsep -1:
                                res.tiMainString = '{:^80}'.format('          >' + '{:2.1g}'.format(tbound1[ibin]) + unit + '; p=' + '{:5.3f}'.format(regress[3,ibin]) + "           ")
                        else:
                                res.tiMainString = '{:^80}'.format('{:2.1g}'.format(tbound1[ibin]) + '-' + '{:2.1g}'.format(tbound2[ibin]) + unit + '; p=' + '{:5.3f}'.format(regress[3,ibin]))

                        plot.append(Ngl.xy(wks,yearsplot,plotin[iline][ibin,:],res))

        panelres = Ngl.Resources()
        panelres.nglPanelLabelBar = True
        panelres.nglPanelYWhiteSpacePercent = 8.
        panelres.nglPanelXWhiteSpacePercent = 0.0

        panelres.nglPanelLabelBar                 = False     # Turn on panel labelbar
        panelres.nglPanelTop                      = 1.0
        panelres.nglPanelBottom                      = 0.00
        panelres.nglPanelLeft                   = 0.0
        panelres.nglPanelRight                  = 1.0
        panelres.nglPaperOrientation = "Portrait"
        panelres.nglScale = False
        panelres.nglMaximize = True

        #txres = Ngl.Resources()
        #txres.txFontHeightF = 0.012
        #Ngl.text_ndc(wks,'Annual timeseries of global number of events of various scales from' + Datatitle,0.5,0.94,txres)

        Ngl.panel(wks,plot,[nlines,float(nbounds)],panelres)

        print 'panelled'
Пример #18
0
def plotmap(plotvars1,plotvars2,
            plotmin1,plotmax1,plotmin2,plotmax2,
            vartitle1,vartitle2,
            title,
            figtitle,
            minlon,maxlon,minlat,maxlat,
            FillValue,panellabels = [],
            labelbarlabels = [],
            labelbarlabels2 = []):

    nplots = plotvars1.shape[0]
    wkres = Ngl.Resources()
    wkres.wkColorMap = "WhiteBlue"
    wks_type = "eps"
    wks = Ngl.open_wks(wks_type,figtitle,wkres)

    # if lons start negative, shift everything over so there isn't a line down
    # the middle of the Pacific

    lons1 = plotvars1.lon.values
    lons2 = plotvars2.lon.values

    lats1 = plotvars1.lat.values
    lats2 = plotvars2.lat.values

    if lons1[0] < 0:
        #nlonhalf1 = len(lons1)/2
        #lonsnew1 = np.zeros(lons1.shape,np.float)
        #lonsnew1[0:nlonhalf1] = lons1[nlonhalf1:nlons1]
        #lonsnew1[nlonhalf1:nlons1] = lons1[0:nlonhalf1] + 360.0

        lonsnew1 = shiftlonlons(lons1,len(lons1))
        lonsnew2 = shiftlonlons(lons2,len(lons2)) 

        for iplot in range(0,nplots):
            plotvars1[iplot] = shiftlons(plotvars1[iplot],len(lons1))
            plotvars2[iplot] = shiftlons(plotvars2[iplot],len(lons2))
    else:
        lonsnew1 = lons1
        lonsnew2 = lons2

    # initialize plotting resources
    res1 = Ngl.Resources()
    res1 = initcontourplot(res1,minlat,minlon,maxlat,maxlon,lats1,lonsnew1)
    res1.sfMissingValueV = FillValue
    res1.lbOrientation   = "Vertical"
    # including some font heights
    res1.lbLabelFontHeightF = 0.01
    res1.lbTitleFontHeightF = 0.01
    res1.tiMainFontHeightF = 0.015
    res1.lbTitlePosition = 'Bottom'
    res1.lbBottomMarginF = 0.0

    # initialize plotting resources
    res2 = Ngl.Resources()
    res2 = initcontourplot(res2,minlat,minlon,maxlat,maxlon,lats2,lonsnew2)
    res2.sfMissingValueV = FillValue
    res2.lbOrientation   = "Vertical"
    # including some font heights
    res2.lbLabelFontHeightF = 0.01
    res2.lbTitleFontHeightF = 0.01
    res2.tiMainFontHeightF = 0.008
    res2.lbTitlePosition = 'Bottom'
    res2.lbBottomMarginF = 0.0


    # turn off grid lines
    res1.mpGridAndLimbOn = False
    res2.mpGridAndLimbOn = False
    # initialize plotting array
    toplot = []
    # fill plotting array
    for iplot in range(0,nplots):
        tempplot = plotvars1[iplot].values
        tempplot[np.where(np.isnan(tempplot))] = FillValue
        # update plot resources with correct lat/lon
        res1.cnMinLevelValF       = plotmin1[iplot]
        res1.cnMaxLevelValF       = plotmax1[iplot]
        res1.cnLevelSpacingF      = ((plotmax1[iplot]-plotmin1[iplot])/10.0)
        res1.tiMainString = (vartitle1[iplot])

        if panellabels != []:
            res1.lbTitleString = labelbarlabels[iplot]
            res1.tiYAxisString  = panellabels[iplot]  # Y axes label.


        toplot.append(Ngl.contour_map(wks,tempplot,res1))

        tempplot = plotvars2[iplot].values
        tempplot[np.where(np.isnan(tempplot))] = FillValue
        res2.cnMinLevelValF       = plotmin2[iplot]          # contour levels.
        res2.cnMaxLevelValF       = plotmax2[iplot]
        res2.cnLevelSpacingF      = ((plotmax2[iplot]-plotmin2[iplot])/10.0)
        res2.tiMainString = vartitle2[iplot]
        if panellabels != []:
            res2.lbTitleString = labelbarlabels2[iplot]
            res2.tiYAxisString  = " "  # so plots are the same
                                                      # size
        toplot.append(Ngl.contour_map(wks,tempplot,res2))

    textres = Ngl.Resources()
    textres.txFontHeightF = 0.015
    Ngl.text_ndc(wks,title,0.5,0.87,textres)

    panelres = Ngl.Resources()
    panelres.nglPanelLabelBar = True
    panelres.nglPanelYWhiteSpacePercent = 0.
    panelres.nglPanelXWhiteSpacePercent = 0.

    panelres.nglPanelLabelBar   = False     # Turn on panel labelbar
    if nplots > 5:
        panelres.nglPanelTop                      = 0.8
        panelres.nglPanelBottom                      = 0.15
    else:
        panelres.nglPanelTop                      = 0.95
        panelres.nglPanelBottom                      = 0.01

    panelres.nglPanelLeft = 0.01
    panelres.nglPanelRight = 0.99

    panelres.nglPanelFigureStrings = (
            ['a.','b.','c.','d.','e.','f.','g.','h.','i.','j.','k.','l.','m.','n.','o.','p.'])
    panelres.nglPanelFigureStringsJust = "TopLeft"
    panelres.nglPanelFigureStringsFontHeightF = 0.008
    panelres.nglPanelFigureStringsParallelPosF = -0.55
    panelres.nglPanelFigureStringsOrthogonalPosF = -0.7
    panelres.nglPanelFigureStringsPerimOn = False   # turn off boxes
    #panelres.amJust = "TopLeft"

    panelres.nglPaperOrientation = "Auto"

    plot = Ngl.panel(wks,toplot,[nplots,2],panelres)
Пример #19
0
def clubb_skw_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons,
                  filepath, filepathobs, casedir, dofv):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    _Font = 25
    interp = 2
    extrap = False
    mkres = Ngl.Resources()
    mkres.gsMarkerIndex = 2
    mkres.gsMarkerColor = "Red"
    mkres.gsMarkerSizeF = 15.
    infiles = ["" for x in range(ncases)]
    ncdfs = ["" for x in range(ncases)]
    nregions = nsite

    varis = [
        "C6rt_Skw_fnc", "C11_Skw_fnc", "C1_Skw_fnc", "C7_Skw_fnc", "Lscale",
        "Richardson_num", "Kh_zm", "tau_zm", "Skw_velocity"
    ]
    varisobs = [
        "CC_ISBL", "OMEGA", "SHUM", "CLWC_ISBL", "THETA", "RELHUM", "U",
        "CIWC_ISBL", "T"
    ]
    nvaris = len(varis)
    cunits = [
        "%", "mba/day", "g/kg", "g/kg", "K", "%", "m/s", "g/kg", "m/s", "m/s",
        "K", "m"
    ]
    cscale = [
        1, 1, 1, 1, 1., 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
    ]
    cscaleobs = [100, 1, 1, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1]
    obsdataset = [
        "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI",
        "ERAI"
    ]
    plotskw = ["" for x in range(nsite)]

    for ire in range(0, nsite):
        if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' +
                              str(lats[ire]) + 'N'):
            os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) +
                     'N')

        plotname = casedir + '/' + str(lons[ire]) + 'E_' + str(
            lats[ire]) + 'N/CLUBB_skewfunc_' + str(lons[ire]) + "E_" + str(
                lats[ire]) + "N_" + cseason
        plotskw[ire] = 'CLUBB_skewfunc_' + str(lons[ire]) + "E_" + str(
            lats[ire]) + "N_" + cseason
        wks = Ngl.open_wks(ptype, plotname)

        Ngl.define_colormap(wks, "GMT_paired")
        plot = []
        res = Ngl.Resources()
        res.nglDraw = False
        res.nglFrame = False
        res.lgLabelFontHeightF = .012  # change font height
        res.lgPerimOn = False  # no box around
        res.vpWidthF = 0.30  # set width and height
        res.vpHeightF = 0.30
        #res.vpXF             = 0.04
        # res.vpYF             = 0.30
        res.tmYLLabelFont = _Font
        res.tmXBLabelFont = _Font
        res.tmXBLabelFontHeightF = 0.01
        res.tmXBLabelFontThicknessF = 1.0
        #     res.tmXBLabelAngleF = 45
        res.xyMarkLineMode = "Lines"
        res.xyLineThicknesses = [
            3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3
        ]

        res.xyDashPatterns = np.arange(0, 24, 1)
        #     res.xyMarkers         = np.arange(16,40,1)
        #     res.xyMarkerSizeF       = 0.005

        pres = Ngl.Resources()
        #     pres.nglMaximize = True
        pres.nglFrame = False
        pres.txFont = _Font
        pres.nglPanelYWhiteSpacePercent = 5
        pres.nglPanelXWhiteSpacePercent = 5
        pres.nglPanelTop = 0.88
        pres.wkWidth = 2500
        pres.wkHeight = 2500

        for iv in range(0, nvaris):
            if (iv == nvaris - 1):
                res.pmLegendDisplayMode = "NEVER"
                res.xyExplicitLegendLabels = casenames[:]
                res.pmLegendSide = "top"
                res.pmLegendParallelPosF = 0.6
                res.pmLegendOrthogonalPosF = -0.5
                res.pmLegendWidthF = 0.10
                res.pmLegendHeightF = 0.10
                res.lgLabelFontHeightF = .02
                res.lgLabelFontThicknessF = 1.5
                res.lgPerimOn = False
            else:
                res.pmLegendDisplayMode = "NEVER"


#         if(obsdataset[iv] =="CCCM"):
#             if(cseason == "ANN"):
#                 fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc"
#             else:
#                 fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc"
#             inptrobs = Dataset(fileobs,'r')
#             B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])]
#         else:
#             if (varisobs[iv] =="PRECT"):
#                 fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc'
#             else:
#                 fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc'
#             inptrobs = Dataset(fileobs,'r')
#             if (varisobs[iv] =="THETA"):
#                 B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])]
#                 pre1 = inptrobs.variables['lev'][:]
#                 for il1 in range (0, len(pre1)):
#                     B[il1] = B[il1]*(1000/pre1[il1])**0.286
#             else:
#                 pre1 = inptrobs.variables['lev'][:]
#                 B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])]
#
#         B[:]=B[:] * cscaleobs[iv]

            for im in range(0, ncases):
                ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
                infiles[im] = filepath[im] + '/' + cases[
                    im] + '_' + cseason + '_climo.nc'
                inptrs = Dataset(infiles[im], 'r')  # pointer to file1
                lat = inptrs.variables['lat'][:]
                nlat = len(lat)
                lon = inptrs.variables['lon'][:]
                nlon = len(lon)
                lev = inptrs.variables['ilev'][:]
                nlev = len(lev)
                ncdf = Dataset(ncdfs[im], 'r')
                n = ncdf.variables['n'][:]
                idx_cols = ncdf.variables['idx_cols'][:, :]
                if (dofv):
                    idx_lats = ncdf.variables['idx_coord_lat'][:, :]
                    idx_lons = ncdf.variables['idx_coord_lon'][:, :]
                ncdf.close()
                if (im == 0):
                    A_field = np.zeros((ncases, nlev), np.float32)

                for subc in range(0, n[ire]):
                    npoint = idx_cols[ire, n[subc] - 1] - 1
                    if (dofv):
                        npointlat = idx_lats[ire, 0]
                        npointlon = idx_lons[ire, 0]
                    if (dofv):
                        tmp = inptrs.variables[varis[iv]][0, :, npointlat,
                                                          npointlon]
                    else:
                        tmp = inptrs.variables[varis[iv]][0, :, npoint]
                    theunits = str(
                        cscale[iv]) + inptrs.variables[varis[iv]].units
                    A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype(
                        np.float32)
                A_field[im, :] = A_field[im, :] * cscale[iv]
                inptrs.close()
            res.tiMainString = varis[iv] + "  " + theunits
            #         res.trXMinF = min(np.min(A_field[0, :]))
            #         res.trXMaxF = max(np.max(A_field[0, :]))
            res.trYReverse = True
            res.xyLineColors = np.arange(3, 20, 2)
            res.xyMarkerColors = np.arange(2, 20, 2)
            p = Ngl.xy(wks, A_field, lev, res)

            #         res.trYReverse        = False
            #         res.xyLineColors      = ["black"]
            #         pt = Ngl.xy(wks,B,pre1,res)
            #         Ngl.overlay(p,pt)

            plot.append(p)

        pres.txString = "Skewness Functions at" + str(lons[ire]) + "E," + str(
            lats[ire]) + "N"
        txres = Ngl.Resources()
        txres.txFontHeightF = 0.020
        txres.txFont = _Font
        Ngl.text_ndc(
            wks, "Skewness Functions at" + str(lons[ire]) + "E," +
            str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres)
        Common_functions.create_legend(wks, casenames, 0.02,
                                       np.arange(3, 20,
                                                 2), 0.1, 0.89 + ncases * 0.01)

        Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres)
        Ngl.frame(wks)
        Ngl.destroy(wks)

    return plotskw
Пример #20
0
    # Resources for panelling
    pres = Ngl.Resources()
    pres.nglFrame = False
    pres.nglPanelLabelBar = True

    # Calculate start Y position for first row of plots
    height = 0.45  # we know this will be height of small plots
    extra = 1.0 - (height)
    top = 1.0 - (extra / 2.)  # 子图第一行所在的高度

    # Draw a title before we draw plots
    title = figData[3]['headLineTxt']
    txres = Ngl.Resources()
    txres.txJust = "BottomCenter"
    txres.txFontHeightF = 0.02
    Ngl.text_ndc(wks, title, 0.5, top + 0.01, txres)

    # Define location in a unit square for each set of plots.
    pres.nglPanelTop = top
    pres.nglPanelBottom = top - height

    Ngl.panel(wks, plots[0:2], [1, 2], pres)

    # plot = Ngl.contour_map(wks, plotData, res)

    # Ngl.draw(plot)

    Ngl.frame(wks)
    Ngl.destroy(wks)
    # Ngl.end()
Пример #21
0
def draw_clubb_tau(ptype, cseason, ncases, cases, casenames, nsite, lats, lons,
                   filepath, filepathobs, casedir, varis, vname, cscale,
                   chscale, pname):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    _Font = 25
    interp = 2
    extrap = False
    mkres = Ngl.Resources()
    mkres.gsMarkerIndex = 2
    mkres.gsMarkerColor = "Red"
    mkres.gsMarkerSizeF = 15.
    infiles = ["" for x in range(ncases)]
    ncdfs = ["" for x in range(ncases)]
    nregions = nsite
    nvaris = len(varis)
    plottau = ["" for x in range(nsite * ncases)]
    alphas = [
        'a) ', 'b) ', 'c) ', 'd) ', 'e) ', 'f) ', 'g) ', 'h) ', 'i) ', 'j) ',
        'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ',
        'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) '
    ]

    for ire in range(0, nsite):
        for im in range(0, ncases):
            if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' +
                                  str(lats[ire]) + 'N'):
                os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' +
                         str(lats[ire]) + 'N')

            plotname = casedir + '/' + str(lons[ire]) + 'E_' + str(
                lats[ire]) + 'N/' + pname + '_' + casenames[im] + "_" + str(
                    lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason
            plottau[im +
                    ncases * ire] = pname + '_' + casenames[im] + "_" + str(
                        lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason

            wks = Ngl.open_wks(ptype, plotname)

            Ngl.define_colormap(wks, "radar")
            plot = []
            res = Ngl.Resources()
            res.nglMaximize = False

            res.nglDraw = False
            res.nglFrame = False
            res.vpWidthF = 0.30  # set width and height
            res.vpHeightF = 0.30
            #         if (lats[ire] > 0 and lons[ire]!=240 ):
            #             res.trYMinF = 400.
            #             res.trYMaxF = 1000.
            #         else:
            res.trYMinF = 100.
            res.trYMaxF = 1000.

            res.tiMainFont = _Font
            res.tmYLLabelFont = _Font
            res.tmXBLabelFont = _Font
            res.tiYAxisFont = _Font
            res.tiXAxisFont = _Font

            res.tmXBLabelFontHeightF = 0.01
            res.tmXBLabelFontThicknessF = 1.0
            res.xyMarkLineMode = "MarkLines"
            res.xyLineThicknesses = [
                3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 2., 2., 2., 2, 2, 2, 2, 2, 2,
                2
            ]
            res.xyDashPatterns = np.arange(0, 24, 1)
            res.xyMarkers = np.arange(16, 40, 1)
            res.xyMarkerSizeF = 0.005
            res.pmLegendDisplayMode = "Never"
            res.pmLegendSide = "top"  # Change location of
            res.pmLegendParallelPosF = 0.75  # move units right
            res.pmLegendOrthogonalPosF = -0.65  # more neg = down
            res.pmLegendWidthF = 0.1  # Change width and
            res.pmLegendHeightF = 0.15  # height of legend.
            res.lgLabelFontHeightF = .02  # change font height
            res.lgLabelFontThicknessF = 1.
            #         res.lgBoxMinorExtentF      = 0.2
            res.lgPerimOn = True
            res.tiYAxisString = "Pressure [hPa]"

            res.trYReverse = True

            pres = Ngl.Resources()
            pres.nglFrame = False
            pres.txFont = _Font
            pres.nglPanelYWhiteSpacePercent = 5
            pres.nglPanelXWhiteSpacePercent = 5
            pres.nglPanelTop = 0.93
            pres.txFont = _Font
            pres.nglMaximize = False
            pres.txFont = _Font
            pres.nglPanelTop = 0.935
            pres.nglPanelFigureStrings = alphas
            pres.nglPanelFigureStringsJust = 'Topright'
            pres.nglPanelFigureStringsFontHeightF = 0.015

            for iv in range(0, nvaris):

                if (varis[iv] == 'tau_no_N2_zm'):
                    budget_ends = ['tau_no_N2_zm', 'bkgnd', 'sfc', 'shear']
                    budget_name = [
                        '1/~F8~t~N~~F10~~B~noN2~N~',
                        '1/~F8~t~N~~F10~~B~bkgnd~N~',
                        '1/~F8~t~N~~F10~~B~surf~N~',
                        '1/~F8~t~N~~F10~~B~shear~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_xp2_zm'):
                    budget_ends = ['tau_xp2_zm', 'tau_no_N2_zm']
                    budget_name = [
                        "1/~F8~t~N~~F10~~B~x'~S~2~N~~N~",
                        '1/~F8~t~N~~F10~~B~noN2~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_wp2_zm'):
                    budget_ends = ['tau_wp2_zm', 'tau_no_N2_zm', 'bvpos']
                    budget_name = [
                        "1/~F8~t~N~~F10~~B~w'~S~2~N~~N~",
                        '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bv~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_wpxp_zm'):
                    budget_ends = [
                        'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear'
                    ]
                    budget_name = [
                        "1/~F8~t~N~~F10~~B~w'x'~N~",
                        "1/~F8~t~N~~F10~~B~noN2~N~", '1/~F8~t~N~~F10~~B~bv~N~',
                        '1/~F8~t~N~~F10~~B~clr~N~'
                    ]
                    nterms = len(budget_ends)

                if (varis[iv] == 'tau_wp3_zm'):
                    budget_ends = [
                        'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear'
                    ]
                    budget_name = [
                        "1/~F8~t~N~~F10~~B~w'x'~N~",
                        '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bv~N~',
                        '1/~F8~t~N~~F10~~B~clr~N~'
                    ]
                    nterms = len(budget_ends)

                ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
                infiles[im] = filepath[im] + cases[im] + '/' + cases[
                    im] + '_' + cseason + '_climo.nc'
                inptrs = Dataset(infiles[im], 'r')  # pointer to file1
                lat = inptrs.variables['lat'][:]
                nlat = len(lat)
                lon = inptrs.variables['lon'][:]
                nlon = len(lon)
                ilev = inptrs.variables['ilev'][:]
                nilev = len(ilev)
                ncdf = Dataset(ncdfs[im], 'r')
                n = ncdf.variables['n'][:]
                idx_cols = ncdf.variables['idx_cols'][:, :]
                ncdf.close()
                A_field = np.zeros((nterms, nilev), np.float32)

                if (varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wp2_zm'
                        or varis[iv] == 'tau_xp2_zm'
                        or varis[iv] == 'tau_wp3_zm'
                        or varis[iv] == 'tau_wpxp_zm'):
                    theunits = str(chscale[iv]) + '~F10~' + inptrs.variables[
                        varis[iv]].units + '~S~-1~N~'
                else:
                    theunits = str(
                        chscale[iv]) + '~F10~' + inptrs.variables[varis[iv] +
                                                                  '_bt'].units

                res.tiXAxisString = '1/~F8~t~N~~F25~~B~' + vname[
                    iv] + "~N~  " + '  Unit=  ' + theunits

                res1 = Ngl.Resources()
                res1 = res

                for it in range(0, nterms):
                    for subc in range(0, n[ire]):
                        npoint = idx_cols[ire, n[subc] - 1] - 1

                        if (varis[iv] == 'tau_wp2_zm'
                                or varis[iv] == 'tau_xp2_zm'
                                or varis[iv] == 'tau_wp3_zm'
                                or varis[iv] == 'tau_wpxp_zm'
                                or varis[iv] == 'tau_no_N2_zm'):
                            varis_tau = budget_ends[it]

                            if ( varis_tau == 'bkgnd' or varis_tau == 'shear' \
                               or varis_tau == 'sfc' ):
                                tmp = inptrs.variables['invrs_tau_' +
                                                       varis_tau][0, :, npoint]

                            if (varis_tau == 'tau_no_N2_zm'):
                                tmp = inptrs.variables[varis_tau][0, :, npoint]
                                tmp = 1 / tmp

                            if (varis[iv] == 'tau_wp2_zm'):
                                if (varis_tau == 'tau_wp2_zm'):
                                    tmp = inptrs.variables[varis_tau][0, :,
                                                                      npoint]
                                    tmp = 1 / tmp
                                if (varis_tau == 'bvpos'):
                                    tmp0 = inptrs.variables['tau_wp2_zm'][
                                        0, :, npoint]
                                    tmp1 = inptrs.variables['tau_no_N2_zm'][
                                        0, :, npoint]
                                    tmp = tmp0
                                    tmp = 1 / tmp0 - 1 / tmp1

                            if (varis[iv] == 'tau_zm'):
                                if (varis_tau == 'tau_zm'):
                                    tmp = inptrs.variables[varis_tau][0, :,
                                                                      npoint]
                                    tmp = 1 / tmp
                                if (varis_tau == 'bvpos'):
                                    tmp0 = inptrs.variables['tau_zm'][0, :,
                                                                      npoint]
                                    tmp1 = inptrs.variables['tau_no_N2_zm'][
                                        0, :, npoint]
                                    tmp = tmp0
                                    tmp = 1 / tmp0 - 1 / tmp1

                            if (varis[iv] == 'tau_xp2_zm'):
                                if (varis_tau == 'tau_xp2_zm'):
                                    tmp = inptrs.variables[varis_tau][0, :,
                                                                      npoint]
                                    tmp = 1 / tmp
                                if (varis_tau == 'Rich'):
                                    tmp0 = inptrs.variables['tau_xp2_zm'][
                                        0, :, npoint]
                                    tmp1 = inptrs.variables['tau_no_N2_zm'][
                                        0, :, npoint]
                                    tmp = tmp0
                                    tmp = 1 / tmp0 / (1 / tmp1) / 1000

                            if (varis[iv] == 'tau_wp3_zm'):
                                if (varis_tau == 'tau_wp3_zm'
                                        or varis_tau == 'tau_wpxp_zm'):
                                    tmp = inptrs.variables[varis_tau][0, :,
                                                                      npoint]
                                    tmp = 1 / tmp
                                    tmp[0:10] = 0
                                if (varis_tau == 'bvpos'):
                                    tmp0 = inptrs.variables['tau_wp2_zm'][
                                        0, :, npoint]
                                    tmp1 = inptrs.variables['tau_no_N2_zm'][
                                        0, :, npoint]
                                    tmp = tmp0
                                    tmp = 1 / tmp0 - 1 / tmp1
                                if (varis_tau == 'clear'):
                                    tmp0 = inptrs.variables['tau_wp3_zm'][
                                        0, :, npoint]
                                    tmp1 = inptrs.variables['tau_wp2_zm'][
                                        0, :, npoint]
                                    tmp = tmp0
                                    tmp = 1 / tmp0 - 1 / tmp1
                                    tmp[0:10] = 0

                            if (varis[iv] == 'tau_wpxp_zm'):
                                if (varis_tau == 'tau_wpxp_zm'
                                        or varis_tau == 'tau_zm'):
                                    tmp = inptrs.variables[varis_tau][0, :,
                                                                      npoint]
                                    tmp = 1 / tmp
                                if (varis_tau == 'bvpos'):
                                    tmp0 = inptrs.variables['tau_zm'][0, :,
                                                                      npoint]
                                    tmp1 = inptrs.variables['tau_no_N2_zm'][
                                        0, :, npoint]
                                    tmp = tmp0
                                    tmp = 2 / tmp0 - 1 / tmp1
                                if (varis_tau == 'clear'):
                                    tmp0 = inptrs.variables['tau_wpxp_zm'][
                                        0, :, npoint]
                                    tmp1 = inptrs.variables['tau_zm'][0, :,
                                                                      npoint]
                                    tmp = tmp0
                                    tmp = 1 / tmp0 / 5 - 2 / tmp1

                        else:
                            varis_tau = varis[iv] + budget_ends[it]
                            tmp0 = inptrs.variables[varis[iv]][0, :, npoint]
                            tmp = inptrs.variables[varis_tau][0, :, npoint]

                        tmp = tmp * cscale[iv]
                        A_field[it, :] = (A_field[it, :] +
                                          tmp[:] / n[ire]).astype(np.float32)

                inptrs.close()

                res.pmLegendDisplayMode = "Never"

                if (varis[iv] == 'tau_wp3_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 450
                    res.xyMarkerColors = [
                        'black', 'orange', 'purple', 'firebrick'
                    ]
                    res.xyLineColors = [
                        'black', 'orange', 'purple', 'firebrick'
                    ]

                if (varis[iv] == 'tau_no_N2_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 20
                    res.xyMarkerColors = ['black', 'red', 'green', 'blue']
                    res.xyLineColors = ['black', 'red', 'green', 'blue']

                if (varis[iv] == 'tau_wp2_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 12
                    res.xyMarkerColors = ['black', 'orange', 'purple']
                    res.xyLineColors = ['black', 'orange', 'purple']

                if (varis[iv] == 'tau_xp2_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 35
                    res.xyMarkerColors = ['black', 'orange']
                    res.xyLineColors = ['black', 'orange']

                p = Ngl.xy(wks, A_field, ilev, res)
                plot.append(p)

                xp = np.mod(iv, 2)
                yp = int(iv / 2)

                if (varis[iv] == 'tau_wp3_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 450
                    res.xyMarkerColors = [
                        'black', 'orange', 'purple', 'firebrick'
                    ]
                    res.xyLineColors = [
                        'black', 'orange', 'purple', 'firebrick'
                    ]
                    Common_functions.create_legend(
                        wks, budget_name[:], 0.02,
                        ['black', 'orange', 'purple', 'firebrick'],
                        0.3 + xp * 0.5, 0.8 - yp * 0.5)

                if (varis[iv] == 'tau_no_N2_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 20
                    res.xyMarkerColors = ['black', 'red', 'green', 'blue']
                    res.xyLineColors = ['black', 'red', 'green', 'blue']
                    Common_functions.create_legend(
                        wks, budget_name[:], 0.02,
                        ['black', 'red', 'green', 'blue'], 0.3 + xp * 0.5,
                        0.8 - yp * 0.5)

                if (varis[iv] == 'tau_wp2_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 12
                    res.xyMarkerColors = ['black', 'orange', 'purple']
                    res.xyLineColors = ['black', 'orange', 'purple']
                    Common_functions.create_legend(
                        wks, budget_name[:], 0.02,
                        ['black', 'orange', 'purple'], 0.3 + xp * 0.5,
                        0.8 - yp * 0.5)

                if (varis[iv] == 'tau_xp2_zm'):
                    res.trXMinF = 0
                    res.trXMaxF = 35
                    res.xyMarkerColors = ['black', 'orange']
                    res.xyLineColors = ['black', 'orange']
                    Common_functions.create_legend(wks, budget_name[:], 0.02,
                                                   ['black', 'orange'],
                                                   0.3 + xp * 0.5,
                                                   0.8 - yp * 0.5)

            Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres)
            txres = Ngl.Resources()
            txres.txFont = _Font
            txres.txFontHeightF = 0.020

            Ngl.text_ndc(
                wks, casenames[im] + "  BUDGET at " + str(lons[ire]) + "E," +
                str(lats[ire]) + "N", 0.5, 0.95, txres)
            Ngl.frame(wks)
            Ngl.destroy(wks)

    return (plottau)
Пример #22
0
#
# Slanted strings
#
txres.txJust = "BottomRight"
txres.txAngleF = -45.
text2b = Ngl.add_text(wks, xy2, "some slanted", 32., .5, txres)
txres.txJust = "BottomLeft"
txres.txAngleF = 45.
text2b = Ngl.add_text(wks, xy2, "text strings", 32., .5, txres)

#
# Filled text box.
#
txres.txAngleF = 0.
txres.txJust = "CenterLeft"
txres.txPerimOn = True
txres.txFontColor = "black"
txres.txBackgroundFillColor = "gray75"
text4 = Ngl.add_text(wks, xy1, "filled text box", 3., -1.0, txres)

#
# Now that our primitives have been added to both plots, panel them.
# Note that by adding the primitives, they will get drawn when the
# XY plots are drawn, and they will be automatically resized with
# the plot.
#
Ngl.panel(wks, [xy1, xy2], [2, 1])

Ngl.end()
Пример #23
0
top = 1.0 - (extra / 2.)

# Draw a title before we draw plots
title = "Multiple panels on one page, 3 different colormaps"
txres = Ngl.Resources()
txres.txJust = "BottomCenter"
txres.txFontHeightF = 0.02
Ngl.text_ndc(wks, title, 0.5, top + 0.01, txres)

# Loop across plots and panel them on one page
for n in range(0, 3):
    # Define location in a unit square for each set of plots.
    pres.nglPanelTop = top - (n * height)
    pres.nglPanelBottom = top - ((n + 1) * height)

    Ngl.panel(wks, plots[n * 3:n * 3 + 3], [1, 3], pres)

Ngl.frame(wks)
Ngl.end()

#
#  File:
#    ngl09p.py
#
#  Synopsis:
#    Illustrates animation of contours over a map and using masked
#    arrays.
#
#  Category:
#    Contours over maps
#
Пример #24
0
#
# Set some font heights to make them slightly bigger than the default.
# Turn off nglScale, because this resource wants to set the axes font
# heights for you.
#
resources.nglScale = False
resources.tiMainFontHeightF = 0.037
resources.lbLabelFontHeightF = 0.032
resources.tmXBLabelFontHeightF = 0.030
resources.tmYLLabelFontHeightF = 0.030

for i in range(0, nplots):
    resources.tiMainString = "Temperature at time = {}".format(i)
    plot.append(Ngl.contour(wks, temp[i, :, :], resources))

Ngl.panel(wks, plot[0:4], [2, 2])  # Draw 2 rows/2 columns of plots.

#
# Now add some extra white space around each plot.
#

panelres = Ngl.Resources()
panelres.nglPanelYWhiteSpacePercent = 5.
panelres.nglPanelXWhiteSpacePercent = 5.
Ngl.panel(wks, plot[0:4], [2, 2], panelres)  # Draw 2 rows/2 columns of plots.

#
# This section will set resources for drawing contour plots over a map.
#
del resources.tiMainString  # Don't set a main title.
Пример #25
0
def clubb_std_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons,
                  filepath, filepathobs, casedir, varis, vname, cscale,
                  chscale, pname):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    _Font = 25
    interp = 2
    extrap = False
    mkres = Ngl.Resources()
    mkres.gsMarkerIndex = 2
    mkres.gsMarkerColor = "Red"
    mkres.gsMarkerSizeF = 15.
    alphas = [
        'a) ', 'b) ', 'c) ', 'd) ', 'e) ', 'f) ', 'g) ', 'h) ', 'i) ', 'j) ',
        'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ',
        'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) '
    ]

    infiles = ["" for x in range(ncases)]
    ncdfs = ["" for x in range(ncases)]
    nregions = nsite

    nvaris = len(varis)

    plotstd = ["" for x in range(nsite)]

    for ire in range(0, nsite):
        if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' +
                              str(lats[ire]) + 'N'):
            os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) +
                     'N')

        plotname = casedir + '/' + str(lons[ire]) + 'E_' + str(
            lats[ire]) + 'N/' + pname + '_' + str(lons[ire]) + "E_" + str(
                lats[ire]) + "N_" + cseason
        plotstd[ire] = pname + '_' + str(lons[ire]) + "E_" + str(
            lats[ire]) + "N_" + cseason
        wks = Ngl.open_wks(ptype, plotname)

        Ngl.define_colormap(wks, "GMT_paired")
        plot = []
        res = Ngl.Resources()
        res.nglMaximize = False
        if (lats[ire] > 0 and lons[ire] < 230):
            res.trYMinF = 400.
            res.trYMaxF = 1000.
        else:
            res.trYMinF = 700.
            res.trYMaxF = 1000.

        res.nglDraw = False
        res.nglFrame = False
        res.lgLabelFontHeightF = .02  # change font height
        res.lgPerimOn = False  # no box around
        res.vpWidthF = 0.30  # set width and height
        res.vpHeightF = 0.30
        res.vpXF = 0.04
        res.vpYF = 0.30
        res.tmYLLabelFont = _Font
        res.tmXBLabelFont = _Font
        res.tiYAxisFont = _Font
        res.tiXAxisFont = _Font

        res.tmXBLabelFontHeightF = 0.01
        res.tmXBLabelFontThicknessF = 2.0
        res.xyMarkLineMode = "Lines"
        res.xyLineThicknesses = [
            3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3
        ]

        res.xyDashPatterns = np.arange(0, 24, 1)
        #     res.xyMarkers         = np.arange(16,40,1)
        #     res.xyMarkerSizeF       = 0.005

        res.tiYAxisString = "Pressure [hPa]"

        for iv in range(0, nvaris):
            if (iv == nvaris - 1):
                res.pmLegendDisplayMode = "NEVER"
                res.xyExplicitLegendLabels = casenames[:]
                res.pmLegendSide = "top"
                res.pmLegendParallelPosF = 0.6
                res.pmLegendOrthogonalPosF = -0.5
                res.pmLegendWidthF = 0.10
                res.pmLegendHeightF = 0.10
                res.lgLabelFontHeightF = .02
                res.lgLabelFontThicknessF = 1.5
                res.lgPerimOn = True
            else:
                res.pmLegendDisplayMode = "NEVER"


#         if(obsdataset[iv] =="CCCM"):
#             if(cseason == "ANN"):
#                 fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc"
#             else:
#                 fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc"
#             inptrobs = Dataset(fileobs,'r')
#             B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])]
#         else:
#             if (varisobs[iv] =="PRECT"):
#                 fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc'
#             else:
#                 fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc'
#             inptrobs = Dataset(fileobs,'r')
#             if (varisobs[iv] =="THETA"):
#                 B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])]
#                 pre1 = inptrobs.variables['lev'][:]
#                 for il1 in range (0, len(pre1)):
#                     B[il1] = B[il1]*(1000/pre1[il1])**0.286
#             else:
#                 pre1 = inptrobs.variables['lev'][:]
#                 B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])]
#
#         B[:]=B[:] * cscaleobs[iv]

            for im in range(0, ncases):
                ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
                infiles[im] = filepath[im] + cases[im] + '/' + cases[
                    im] + '_' + cseason + '_climo.nc'
                inptrs = Dataset(infiles[im], 'r')  # pointer to file1
                lat = inptrs.variables['lat'][:]
                nlat = len(lat)
                lon = inptrs.variables['lon'][:]
                nlon = len(lon)
                lev = inptrs.variables['ilev'][:]
                nlev = len(lev)
                ncdf = Dataset(ncdfs[im], 'r')
                n = ncdf.variables['n'][:]
                idx_cols = ncdf.variables['idx_cols'][:, :]
                ncdf.close()
                if (im == 0):
                    A_field = np.zeros((ncases, nlev), np.float32)

                for subc in range(0, n[ire]):
                    npoint = idx_cols[ire, n[subc] - 1] - 1
                    if (varis[iv] == 'THETA'):
                        tmp = inptrs.variables['T'][0, :, npoint]
                        hyam = inptrs.variables['hyam'][:]
                        hybm = inptrs.variables['hybm'][:]
                        ps = inptrs.variables['PS'][0, npoint]
                        ps = ps
                        p0 = inptrs.variables['P0']
                        pre = np.zeros((nlev), np.float32)
                        for il in range(0, nlev):
                            pre[il] = hyam[il] * p0 + hybm[il] * ps
                            tmp[il] = tmp[il] * (100000 / pre[il])**0.286
                        theunits = str(
                            chscale[iv]) + inptrs.variables['T'].units

                    else:
                        tmp = inptrs.variables[varis[iv]][0, :, npoint]
                        #                     tmp2=inptrs.variables['C6rt_Skw_fnc'][0,:,npoint]
                        #                     tmp3=inptrs.variables['tau_zm'][0,:,npoint]
                        #                     tmp4=inptrs.variables['tau_wpxp_zm'][0,:,npoint]
                        theunits = str(
                            chscale[iv]) + inptrs.variables[varis[iv]].units
                        if (varis[iv] == 'tau_zm' or varis[iv] == 'tau_wp2_zm' \
                           or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_xp2_zm' \
                           or varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wpxp_zm'):
                            tmp = 1 / tmp
                            tmp[0:10] = 0.0
                            theunits = str(chscale[iv]) + inptrs.variables[
                                varis[iv]].units + '^-1'

                    A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype(
                        np.float32)
                A_field[im, :] = A_field[im, :] * cscale[iv]

                inptrs.close()

            res.tiXAxisString = vname[iv] + "  Unit=  " + theunits

            res.trYReverse = True
            res.xyLineColors = np.arange(3, 20, 2)
            res.xyMarkerColors = np.arange(2, 20, 2)
            p = Ngl.xy(wks, A_field, lev, res)

            plot.append(p)

        pres = Ngl.Resources()
        pres.nglFrame = False
        pres.txFont = _Font
        pres.nglMaximize = False
        pres.txFont = _Font
        #     pres.nglPanelYWhiteSpacePercent = 5
        #     pres.nglPanelXWhiteSpacePercent = 5
        #     pres.wkPaperWidthF  = 17  # in inches
        #     pres.wkPaperHeightF = 28  # in inches
        pres.nglPanelTop = 0.935
        pres.nglPanelFigureStrings = alphas
        pres.nglPanelFigureStringsJust = 'Topleft'
        pres.nglPanelFigureStringsFontHeightF = 0.015

        pres.gsnPaperOrientation = "Landscape"

        txres = Ngl.Resources()
        txres.txFontHeightF = 0.02
        txres.txFont = _Font
        Ngl.text_ndc(
            wks,
            "CLUBB VAR at " + str(lons[ire]) + "E," + str(lats[ire]) + "N",
            0.5, 0.75, txres)
        Common_functions.create_legend(wks, casenames, 0.015,
                                       np.arange(3, 20, 2), 0.3,
                                       0.59 + ncases * 0.01)

        Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres)
        Ngl.frame(wks)
        Ngl.destroy(wks)

    return plotstd
Пример #26
0
def draw_e3sm_bgt (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,dpsc):

# ncases, the number of models
# cases, the name of models
# casename, the name of cases
# filepath, model output filepath
# filepathobs, filepath for observational data
# inptrs = [ncases]
 if not os.path.exists(casedir):
        os.mkdir(casedir)


 _Font   = 25
 interp = 2
 extrap = False
 mkres = Ngl.Resources()
 mkres.gsMarkerIndex = 2
 mkres.gsMarkerColor = "Red"
 mkres.gsMarkerSizeF = 15.   
 infiles  = ["" for x in range(ncases)]
 ncdfs    = ["" for x in range(ncases)]
 nregions = nsite

 varis = [ "DCQ","DCCLDLIQ","DCCLDICE","PTEQ","PTTEND","DTCOND"]
 nvaris = len(varis)
 cscale = [1E8, 1E8, 1E8, 1E8, 1E4, 1E4]
 chscale = ['1E-8', '1E-8', '1E-8', '1E-8', '1E-4', '1E-4']

 plote3smbgt=["" for x in range(nsite*ncases)] 

 for ire in range (0, nsite):
     for im in range (0,ncases):
         if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'):
             os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N')

         plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/E3SM_Budgets_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason
         plote3smbgt[im+ncases*ire] = 'E3SM_Budgets_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason

         wks= Ngl.open_wks(ptype,plotname)

         Ngl.define_colormap(wks,"radar")
         plot = []
         res     = Ngl.Resources()  
         res.nglDraw              = False
         res.nglFrame             = False
         res.lgLabelFontHeightF     = .012                   # change font height
         res.lgPerimOn              = False                 # no box around
         res.vpWidthF         = 0.30                      # set width and height
         res.vpHeightF        = 0.30

#         res.txFontHeightF   = .01
         #  res.vpXF             = 0.04
         # res.vpYF             = 0.30
         res.tmYLLabelFont  = 12
         res.tmXBLabelFont  = 12
         res.tmXBLabelFontHeightF = 0.01
         res.tmXBLabelFontThicknessF = 1.0
         res.xyMarkLineMode      = "MarkLines"
         res.xyLineThicknesses = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,2.,2.,2.,2.,2,2,2,2,2,2,2]
         res.xyLineColors      = np.arange(2,16,2)
         res.xyDashPatterns    = np.arange(0,24,1)
         res.xyMarkers         = np.arange(16,40,1)
         res.xyMarkerSizeF       = 0.005
         res.xyMarkerColors      = np.arange(2,16,2)
         res.pmLegendDisplayMode    = "ALWAYS"
         res.pmLegendSide           = "top"                 # Change location of
         res.pmLegendParallelPosF   = 0.6                  # move units right
         res.pmLegendOrthogonalPosF = -0.55                  # more neg = down
         res.pmLegendWidthF         = 0.2       # Decrease width
         res.pmLegendHeightF        = 0.1       # Decrease height
         res.lgBoxMinorExtentF      = 0.1       # Shorten the legend lines
         res.lgLabelFontHeightF     = 0.015     # Change the font size
         res.lgPerimOn              = True
         res.tiYAxisString   = "PRESSURE"
         res.trYReverse        = True

         pres            = Ngl.Resources() 
         pres.nglMaximize = True
         pres.wkWidth              = 2000
         pres.wkHeight             = 2000

         pres.nglFrame = False
         pres.txFont = 12
         pres.nglPanelYWhiteSpacePercent = 5
         pres.nglPanelXWhiteSpacePercent = 5
         pres.nglPanelTop = 0.93


         for iv in range (0, nvaris):

             if (varis[iv] == "DCQ" ):
                if (dpsc[im] == "zm" ):
                   budget_ends = ["MPDQ", "RVMTEND_CLUBB","ZMDQ", "EVAPQZM"]
                else:
                   budget_ends = ["MPDQ", "RVMTEND_CLUBB"]
                nterms = len (budget_ends)
             if (varis[iv] == "DTCOND" ):
                if (dpsc[im] == "zm" ):
                   budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT","ZMDT", "EVAPTZM", "ZMMTT"]
                else:
                   budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT"]
                nterms = len (budget_ends)
             if (varis[iv] == "PTTEND") :
                 budget_ends = ["DTCOND", "QRS", "QRL",  "TTGW"]
                 nterms = len (budget_ends)
             if (varis[iv] == "PTEQ") :
                 if (dpsc[im] == "zm" ):
                    budget_ends = ["MPDQ", "RVMTEND_CLUBB","ZMDQ", "EVAPQZM"]
                 else:
                    budget_ends = ["MPDQ", "RVMTEND_CLUBB"]  
                 nterms = len (budget_ends)
             if (varis[iv] == "DCCLDLIQ") :
                 if (dpsc[im] == "zm" ):
                    budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ","ZMDLIQ"]
                 else:
                    budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ"]
                 nterms = len (budget_ends)
             if (varis[iv] == "DCCLDICE") :
                 if (dpsc[im] == "zm" ):
                    budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE","ZMDICE"]
                 else:
                    budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE"]
                 nterms = len (budget_ends)


             ncdfs[im]  = './data/'+cases[im]+'_site_location.nc'
             infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc'
             inptrs = Dataset(infiles[im],'r')       # pointer to file1
             lat=inptrs.variables['lat'][:]
             nlat=len(lat)
             lon=inptrs.variables['lon'][:]
             nlon=len(lon)
             ilev=inptrs.variables['lev'][:]
             nilev=len(ilev)
             ncdf= Dataset(ncdfs[im],'r')
             n   =ncdf.variables['n'][:]
             idx_cols=ncdf.variables['idx_cols'][:,:]
             ncdf.close()
             A_field = np.zeros((nterms,nilev),np.float32)
             theunits=str(chscale[iv])+"x"+inptrs.variables[varis[iv]].units
             res.tiMainString    =  varis[iv]+"  "+theunits 


             for it in range(0, nterms):
                 for subc in range( 0, n[ire]):
                     varis_bgt= budget_ends[it]
                     npoint=idx_cols[ire,n[subc]-1]-1
                     tmp=inptrs.variables[varis_bgt][0,:,npoint] #/n[ire]
                     tmp=tmp*cscale[iv]
                     if (varis_bgt == "MPDT" or varis_bgt == "STEND_CLUBB" ):
                        tmp=tmp/1004
                     A_field[it,:] = (A_field[it,:]+tmp[:]/n[ire]).astype(np.float32 )

             inptrs.close()
             res.xyExplicitLegendLabels =  budget_ends[:]
             p = Ngl.xy(wks,A_field,ilev,res)
             plot.append(p)

             xp=np.mod(iv,2)
             yp=int(iv/2)


         Ngl.panel(wks,plot[:],[nvaris/2,2],pres)

         txres = Ngl.Resources()
         txres.txFont = _Font
         txres.txFontHeightF = 0.020
         Ngl.text_ndc(wks,casenames[im]+"  BUDGET at" +str(lons[ire])+"E,"+str(lats[ire])+"N",0.5,0.95,txres)

         Ngl.frame(wks)
         Ngl.destroy(wks) 

 return (plote3smbgt)
def draw_3D_plot(ptype, clevel, cseason, ncases, cases, casenames, nsite, lats,
                 lons, filepath, filepathobs, casedir):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    if not os.path.exists(casedir + "/2D"):
        os.mkdir(casedir + "/2D")

    _Font = 25
    interp = 2
    extrap = False
    mkres = Ngl.Resources()
    mkres.gsMarkerIndex = 2
    mkres.gsMarkerColor = "Red"
    mkres.gsMarkerSizeF = 15.
    infiles = ["" for x in range(ncases)]
    ncdfs = ["" for x in range(ncases)]
    varis = ["T", "OMEGA", "Z3"]
    varisobs = ["T", "OMEGA", "Z3"]
    alpha = ["A", "B", "C", "D", "E", "F"]
    nvaris = len(varis)
    cunits = [""]
    cscale = [1, 864, 1, 1, 1, 1]
    cscaleobs = [1, 1, 1, 1, 0.04]
    cntrs = np.zeros((nvaris, 11), np.float32)
    obsdataset = ["ERAI", "ERAI", "ERAI", "ERAI", "ERAI"]
    level = [
        1000., 925., 850., 700., 600., 500., 400., 300., 250., 200., 150., 100.
    ]

    plot3d = ["" for x in range(nvaris)]
    for iv in range(0, nvaris):
        # make plot for each field

        #  Observational data
        if (obsdataset[iv] == "CCCM"):
            if (cseason == "ANN"):
                fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc"
            else:
                fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc"
        else:
            if (varisobs[iv] == "PRECT"):
                fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc'
            else:
                fileobs = filepathobs + obsdataset[
                    iv] + '_' + cseason + '_climo.nc'

        inptrobs = Dataset(fileobs, 'r')
        latobs = inptrobs.variables['lat'][:]
        lonobs = inptrobs.variables['lon'][:]
        levobs = inptrobs.variables['lev'][:]
        levobs_idx = np.abs(levobs - clevel).argmin()
        B = inptrobs.variables[varisobs[iv]][0, levobs_idx, :, :]
        B = B * cscaleobs[iv]

        #   cntrs= np.arange(np.min(B),np.max(B),12)
        if (varis[iv] == "OMEGA"):
            cntrs[iv, :] = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50]

        if (varis[iv] == "Z3"):
            if (clevel == 500):
                cntrs[iv, :] = [
                    5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200,
                    6300
                ]
            else:
                cntrs[iv, :] = [
                    300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300
                ]

        if (varis[iv] == "T"):
            if (clevel == 500):
                cntrs[iv, :] = [
                    210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310
                ]
            else:
                cntrs[iv, :] = [
                    292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312
                ]

        if (varis[iv] == "Q"):
            if (clevel == 500):
                cntrs[iv, :] = [
                    210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310
                ]
            else:
                cntrs[iv, :] = [
                    292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312
                ]

        #************************************************
        # create plot
        #************************************************
        plotname = casedir + '/2D/Horizontal_' + varis[
            iv] + '_' + cseason + str(clevel)
        plot3d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason + str(clevel)

        wks = Ngl.open_wks(ptype, plotname)

        Ngl.define_colormap(wks, "amwg256")
        plot = []

        textres = Ngl.Resources()
        textres.txFontHeightF = 0.02  # Size of title.
        textres.txFont = _Font
        Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres)

        pres = Ngl.Resources()
        #   pres.nglMaximize = True
        pres.nglFrame = False
        pres.nglPanelYWhiteSpacePercent = 5
        pres.nglPanelXWhiteSpacePercent = 5
        pres.nglPanelBottom = 0.2
        pres.nglPanelTop = 0.9
        pres.nglPanelLabelBar = True
        pres.pmLabelBarWidthF = 0.8
        pres.nglFrame = False
        pres.nglPanelLabelBar = True  # Turn on panel labelbar
        pres.nglPanelLabelBarLabelFontHeightF = 0.015  # Labelbar font height
        pres.nglPanelLabelBarHeightF = 0.0750  # Height of labelbar
        pres.nglPanelLabelBarWidthF = 0.700  # Width of labelbar
        pres.lbLabelFont = "helvetica-bold"  # Labelbar font
        pres.nglPanelTop = 0.93
        pres.nglPanelFigureStrings = alpha
        pres.nglPanelFigureStringsJust = "BottomRight"

        res = Ngl.Resources()
        res.nglDraw = False  #-- don't draw plots
        res.nglFrame = False
        res.cnFillOn = True
        res.cnFillMode = "RasterFill"
        res.cnLinesOn = False
        res.nglMaximize = True
        res.mpFillOn = True
        res.mpCenterLonF = 180
        res.tiMainFont = _Font
        res.tiMainFontHeightF = 0.025
        res.tiXAxisString = ""
        res.tiXAxisFont = _Font
        res.tiXAxisFontHeightF = 0.025
        res.tiYAxisString = ""
        res.tiYAxisFont = _Font
        res.tiYAxisOffsetXF = 0.0
        res.tiYAxisFontHeightF = 0.025
        res.tmXBLabelFont = _Font
        res.tmYLLabelFont = _Font
        res.tiYAxisFont = _Font

        #   res.nglStringFont                  = _Font
        #   res.nglStringFontHeightF           = 0.04
        #   res.nglRightString                 = ""#"Cloud Fraction"
        #   res.nglScalarContour     = True
        res.cnInfoLabelOn = False
        res.cnFillOn = True
        res.cnLinesOn = False
        res.cnLineLabelsOn = False
        res.lbLabelBarOn = False

        #   res.vcRefMagnitudeF = 5.
        #   res.vcMinMagnitudeF = 1.
        #   res.vcRefLengthF    = 0.04
        #   res.vcRefAnnoOn     = True#False
        #   res.vcRefAnnoZone   = 3
        #   res.vcRefAnnoFontHeightF = 0.02
        #   res.vcRefAnnoString2 =""
        #   res.vcRefAnnoOrthogonalPosF   = -1.0
        #  res.vcRefAnnoArrowLineColor   = "blue"         # change ref vector color
        #  res.vcRefAnnoArrowUseVecColor = False
        #   res.vcMinDistanceF  = .05
        #   res.vcMinFracLengthF         = .
        #   res.vcRefAnnoParallelPosF    =  0.997
        #   res.vcFillArrowsOn           = True
        #   res.vcLineArrowThicknessF    =  3.0
        #   res.vcLineArrowHeadMinSizeF   = 0.01
        #   res.vcLineArrowHeadMaxSizeF   = 0.03
        #   res.vcGlyphStyle              = "CurlyVector"     # turn on curley vectors
        #  res@vcGlyphStyle              ="Fillarrow"
        #   res.vcMonoFillArrowFillColor = True
        #   res.vcMonoLineArrowColor     = True
        #   res.vcLineArrowColor          = "green"           # change vector color
        #   res.vcFillArrowEdgeColor      ="white"
        #   res.vcPositionMode            ="ArrowTail"
        #   res.vcFillArrowHeadInteriorXF =0.1
        #   res.vcFillArrowWidthF         =0.05           #default
        #   res.vcFillArrowMinFracWidthF  =.5
        #   res.vcFillArrowHeadMinFracXF  =.5
        #   res.vcFillArrowHeadMinFracYF  =.5
        #   res.vcFillArrowEdgeThicknessF = 2.0

        res.mpFillOn = False
        res.cnLevelSelectionMode = "ExplicitLevels"

        res.cnLevels = cntrs[iv, :]

        for im in range(0, ncases):
            ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
            infiles[im] = filepath[im] + '/' + cases[
                im] + '_' + cseason + '_climo.nc'
            inptrs = Dataset(infiles[im], 'r')  # pointer to file1
            lat = inptrs.variables['lat'][:]
            nlat = len(lat)
            lon = inptrs.variables['lon'][:]
            nlon = len(lon)
            #area=inptrs.variables['area'][:]
            lev = inptrs.variables['lev'][:]
            lev_idx = np.abs(lev - clevel).argmin()

            area_wgt = np.zeros(nlat)
            #       area_wgt[:] = gw[:]

            sits = np.linspace(0, nsite - 1, nsite)
            ncdf = Dataset(ncdfs[im], 'r')
            n = ncdf.variables['n'][:]
            idx_cols = ncdf.variables['idx_cols'][:]
            A = inptrs.variables[varis[iv]][0, lev_idx, :]
            A_xy = A
            A_xy = A_xy * cscale[iv]
            ncdf.close()
            inptrs.close()

            if im == 0:
                dsizes = len(A_xy)
                field_xy = [[0 for col in range(dsizes)]
                            for row in range(ncases)]

            field_xy[im][:] = A_xy

            res.lbLabelBarOn = False
            if (np.mod(im, 2) == 0):
                res.tiYAxisOn = True
            else:
                res.tiYAxisOn = False

            res.tiXAxisOn = False
            res.sfXArray = lon
            res.sfYArray = lat
            res.mpLimitMode = "LatLon"
            res.mpMaxLonF = max(lon)
            res.mpMinLonF = min(lon)
            res.mpMinLatF = min(lat)
            res.mpMaxLatF = max(lat)
            #res.tiMainString    =  "GLB="+str(np.sum(A_xy[:]*area[:]/np.sum(area)))
            res.tiMainString = "GLB="
            textres.txFontHeightF = 0.015
            Ngl.text_ndc(wks, alpha[im] + "  " + casenames[im], 0.3,
                         .135 - im * 0.03, textres)

            p = Ngl.contour_map(wks, A_xy, res)
            plot.append(p)


# observation
#   res.nglLeftString = obsdataset[iv]
#  res@lbLabelBarOn = True
#  res@lbOrientation        = "vertical"         # vertical label bars
        res.lbLabelFont = _Font
        res.tiYAxisOn = True
        res.tiXAxisOn = True
        res.tiXAxisFont = _Font
        rad = 4.0 * np.arctan(1.0) / 180.0
        re = 6371220.0
        rr = re * rad

        dlon = abs(lonobs[2] - lonobs[1]) * rr
        dx = dlon * np.cos(latobs * rad)
        jlat = len(latobs)
        dy = np.zeros(jlat, dtype=float)
        # close enough
        dy[0] = abs(lat[2] - lat[1]) * rr
        dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5
        dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr
        area_wgt = dx * dy  #
        is_SE = False

        sum1 = 0
        sum2 = 0

        for j in range(0, jlat - 1):
            for i in range(0, len(lonobs) - 1):
                if (np.isnan(B[j][i]) != "--"):
                    sum1 = sum1 + area_wgt[j] * B[j][i]
                    sum2 = sum2 + area_wgt[j]

        res.sfXArray = lonobs
        res.sfYArray = latobs
        res.mpLimitMode = "LatLon"
        res.mpMaxLonF = max(lonobs)
        res.mpMinLonF = min(lonobs)
        res.mpMinLatF = min(latobs)
        res.mpMaxLatF = max(latobs)
        res.tiMainString = "GLB=" + str(
            sum1 / sum2)  #Common_functions.area_avg(B, area_wgt,is_SE))

        p = Ngl.contour_map(wks, B, res)
        plot.append(p)

        if (np.mod(ncases + 1, 2) == 1):
            Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres)
        else:
            Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres)

        Ngl.frame(wks)
        Ngl.destroy(wks)
    return plot3d
Пример #28
0
def rain_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,varis,cscale,chscale,pname):

# ncases, the number of models
# cases, the name of models
# casename, the name of cases
# filepath, model output filepath
# filepathobs, filepath for observational data
# inptrs = [ncases]
 if not os.path.exists(casedir):
        os.mkdir(casedir)

 _Font   = 25
 interp = 2
 extrap = False
 mkres = Ngl.Resources()
 mkres.gsMarkerIndex = 2
 mkres.gsMarkerColor = 'Red'
 mkres.gsMarkerSizeF = 15.
 infiles  = ['' for x in range(ncases)]
 ncdfs    = ['' for x in range(ncases)]
 nregions = nsite

 varisobs = ['CC_ISBL', 'OMEGA','SHUM','CLWC_ISBL', 'THETA','RELHUM','U','CIWC_ISBL','T' ]
 nvaris = len(varis)
 cunits = ['%','mba/day','g/kg','g/kg','K', '%', 'm/s', 'g/kg', 'm/s', 'm/s','K','m' ]
 cscaleobs = [100,        1,     1, 1000 , 1.,   1,     1,   1000,     1,1,1,1,1,1,1]
 obsdataset =['ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI','ERAI','ERAI']
 plotrain=['' for x in range(nsite)]


 for ire in range (0, nsite):
     if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'):
         os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N')

     plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/'+pname+'_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason
     plotrain[ire] = pname+'_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason
     wks= Ngl.open_wks(ptype,plotname)

     Ngl.define_colormap(wks,'GMT_paired')
     plot = []
     res     = Ngl.Resources()
     res.nglDraw              = False
     res.nglFrame             = False
     res.lgLabelFontHeightF     = .02                   # change font height
     res.lgPerimOn              = False                 # no box around
     res.vpWidthF         = 0.30                      # set width and height
     res.vpHeightF        = 0.30
     #res.vpXF             = 0.04
     # res.vpYF             = 0.30
     res.tmYLLabelFont  = _Font
     res.tmXBLabelFont  = _Font
     res.tiMainFont     = _Font
     res.tmXBLabelFontHeightF = 0.015
     res.tmXBLabelFontThicknessF = 1.0
#     res.tmXBLabelAngleF = 45
     res.xyMarkLineMode      = 'Lines'
     res.xyLineThicknesses = [3.0, 3.0, 3.0, 3.0, 3.0, 3.0,3.,3.,3.,3.,3,3,3,3,3,3,3]

     res.xyDashPatterns    = np.arange(0,24,1)
#     res.xyMarkers         = np.arange(16,40,1)
#     res.xyMarkerSizeF       = 0.005


     pres            = Ngl.Resources()
#     pres.nglMaximize = True
     pres.nglFrame = False
     pres.txFont = _Font
     pres.nglPanelYWhiteSpacePercent = 5
     pres.nglPanelXWhiteSpacePercent = 5
     pres.nglPanelTop = 0.88
     pres.wkWidth = 2500
     pres.wkHeight = 2500


     for iv in range (0, nvaris):   
         if(iv == nvaris-1):
             res.pmLegendDisplayMode    = 'Never'
             res.xyExplicitLegendLabels = casenames[:]
             res.pmLegendSide           = 'top'             
             res.pmLegendParallelPosF   = 0.6               
             res.pmLegendOrthogonalPosF = -0.5                  
             res.pmLegendWidthF         = 0.10              
             res.pmLegendHeightF        = 0.10          
             res.lgLabelFontHeightF     = .02               
             res.lgLabelFontThicknessF  = 1.5
             res.lgPerimOn              = False
         else:
             res.pmLegendDisplayMode    = 'NEVER'


         for im in range (0,ncases):
             ncdfs[im]  = './data/'+cases[im]+'_site_location.nc'
             infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc'
             inptrs = Dataset(infiles[im],'r')       # pointer to file1
             lat=inptrs.variables['lat'][:]
             nlat=len(lat)
             lon=inptrs.variables['lon'][:]
             nlon=len(lon)
             lev=inptrs.variables['lev'][:]
             nlev=len(lev)
             ncdf= Dataset(ncdfs[im],'r')
             n   =ncdf.variables['n'][:]
             idx_cols=ncdf.variables['idx_cols'][:,:]
             ncdf.close()
             if (im ==0):
                 A_field = np.zeros((ncases,nlev),np.float32)

             for subc in range( 0, n[ire]):
                 npoint=idx_cols[ire,n[subc]-1]-1
                 tmp=inptrs.variables[varis[iv]][0,:,npoint] 
                 theunits=str(chscale[iv])+'x'+inptrs.variables[varis[iv]].units
                 A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 )
             A_field[im,:] = A_field[im,:] *cscale[iv]

             inptrs.close()
         res.tiMainString    =  varis[iv]+'  '+theunits
#         res.trXMinF = min(np.min(A_field[0, :]))
#         res.trXMaxF = max(np.max(A_field[0, :]))
         res.trYReverse        = True
         res.xyLineColors      = np.arange(3,20,2)
         res.xyMarkerColors    = np.arange(2,20,2)
         p = Ngl.xy(wks,A_field,lev,res)
         
#         res.trYReverse        = False
#         res.xyLineColors      = ['black']
#         pt = Ngl.xy(wks,B,pre1,res)
#         Ngl.overlay(p,pt)

         plot.append(p)


     pres.txString   = pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N'
     txres = Ngl.Resources()
     txres.txFontHeightF = 0.020
     txres.txFont = _Font
     Ngl.text_ndc(wks,pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.92+ncases*0.01,txres)
     Common_functions.create_legend(wks,casenames,np.arange(3,20,2),0.1,0.89+ncases*0.01)

     Ngl.panel(wks,plot[:],[nvaris/2,2],pres)
     Ngl.frame(wks)
     Ngl.destroy(wks)

 return plotrain
def draw_uv(sel_year, sel_month):
    print("darwing wind plot for " + str(sel_month).zfill(2) + " " +
          str(sel_year))
    files_cli = sorted(
        glob.glob(
            os.path.join(
                '/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cli',
                'uv*.grb')))
    f_cli = xr.open_mfdataset(files_cli,
                              concat_dim="time",
                              combine="nested",
                              engine="cfgrib",
                              parallel=True)
    u_cli_850 = f_cli["u"][:, 0, :, :]
    v_cli_850 = f_cli["v"][:, 0, :, :]
    u_cli_850 = u_cli_850.mean(dim="time")
    v_cli_850 = v_cli_850.mean(dim="time")
    u_cli_200 = f_cli["u"][:, 1, :, :]
    v_cli_200 = f_cli["v"][:, 1, :, :]
    u_cli_200 = u_cli_200.mean(dim="time")
    v_cli_200 = v_cli_200.mean(dim="time")

    file_cur = "/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cur/uv_850_200_" + str(
        sel_year) + str(sel_month).zfill(2) + ".grb"
    f_cur = xr.open_mfdataset(file_cur, engine="cfgrib", parallel=True)
    u_cur_850 = f_cur["u"][0, :, :]
    v_cur_850 = f_cur["v"][0, :, :]
    u_cur_200 = f_cur["u"][1, :, :]
    v_cur_200 = f_cur["v"][1, :, :]

    lat = f_cur["latitude"].values
    lon = f_cur["longitude"].values

    # u_ano_850 = u_cur_850 - u_cli_850
    # v_ano_850 = v_cur_850 - v_cli_850

    leftString = "850hPa wind"
    rightString = "m/s"
    wks_type = 'png'
    wks = Ngl.open_wks(
        wks_type,
        '/home/alley/work/Dong/mongo/seasonal_analysis/images/850_200_wind_' +
        str(sel_year) + str(sel_month) + '.png')

    res = Ngl.Resources()
    res.nglFrame = False
    res.nglDraw = False
    res.mpLimitMode = "LatLon"
    res.mpMinLonF = 60
    res.mpMaxLonF = 180
    res.mpMinLatF = -10
    res.mpMaxLatF = 60

    res.mpPerimOn = True  #-- turn on map perimeter
    res.mpFillOn = True  #-- turn on map fill
    res.mpLandFillColor = "gray"  #-- change land color to gray
    # resources.mpOceanFillColor       = -1     # Change oceans and inland
    # resources.mpInlandWaterFillColor = -1     # waters to transparent.
    res.mpOceanFillColor = "transparent"  #-- change color for oceans and inlandwater
    res.mpInlandWaterFillColor = "transparent"  #-- set ocean/inlandwater color to transparent
    res.mpGridMaskMode = "MaskNotOcean"  #-- draw grid over ocean, not land
    res.vcMonoLineArrowColor = False  #-- draw vectors in color
    res.vcMinFracLengthF = 0.33  #-- increase length of vectors
    res.vcMinMagnitudeF = 0.001  #-- increase length of vectors
    res.vcRefLengthF = 0.045  #-- set reference vector length
    res.vcRefMagnitudeF = 10.0  #-- set reference magnitude value
    res.vcLineArrowThicknessF = 3  #-- make vector lines thicker (default: 1.0)
    res.vcRefAnnoOn = False  # 不显示reference vector
    # res.vcLevelPalette            = "ncl_default"                 #-- choose color map

    res.pmLabelBarDisplayMode = "Never"  #-- turn on a labelbar
    res.lbOrientation = "Horizontal"  #-- labelbar orientation
    # res.lbLabelFontHeightF        =  0.008                        #-- labelbar label font size
    # res.lbBoxMinorExtentF         =  0.22                         #-- decrease height of labelbar boxes
    res.tiMainString = "850hPa wind field in " + str(sel_month).zfill(
        2) + " " + str(sel_year)

    # res.tiMainString = "850hPa wind"
    res.vfXArray = lon[::15]  #-- longitude values, subscript every 3rd value
    res.vfYArray = lat[::15]  #-- latitude values, subscript every 3rd value

    wind_850_cur = Ngl.vector_map(
        wks, u_cur_850[::15, ::15], v_cur_850[::15, ::15],
        res)  #-- draw a vector plot, subscript every 3rd value
    res.tiMainString = "850hPa wind field for climate state"
    wind_850_cli = Ngl.vector_map(
        wks, u_cli_850[::15, ::15], v_cli_850[::15, ::15],
        res)  #-- draw a vector plot, subscript every 3rd value
    res.tiMainString = "200hPa wind field in " + str(sel_month) + " " + str(
        sel_year)
    res.vfXArray = lon[::15]  #-- longitude values, subscript every 3rd value
    res.vfYArray = lat[::15]  #-- latitude values, subscript every 3rd value
    wind_200_cur = Ngl.vector_map(
        wks, u_cur_200[::15, ::15], v_cur_200[::15, ::15],
        res)  #-- draw a vector plot, subscript every 3rd value
    res.tiMainString = "200hPa wind field for climate state"
    wind_200_cli = Ngl.vector_map(
        wks, u_cli_200[::15, ::15], v_cli_200[::15, ::15],
        res)  #-- draw a vector plot, subscript every 3rd value

    panelres = Ngl.Resources()
    panelres.nglPanelLabelBar = True  # Turn on panel labelbar
    # panelres.nglPanelLabelBarLabelFontHeightF = 0.015    # Labelbar font height
    # panelres.nglPanelLabelBarHeightF          = 0.1750   # Height of labelbar
    # panelres.nglPanelLabelBarWidthF           = 0.700    # Width of labelbar
    # panelres.lbLabelFont                      = "helvetica-bold" # Labelbar font
    # panelres.nglPanelTop                      = 0.935
    Ngl.panel(wks, [wind_200_cli, wind_200_cur, wind_850_cli, wind_850_cur],
              [2, 2], panelres)
    # panelres.nglPanelFigureStrings            = ["A","B","C","D","E","F"]
    # panelres.nglPanelFigureStringsJust        = "BottomRight"
    # vres = Ngl.Resources()
    # vres.nglFrame = False
    # vres.nglDraw = False
    # vres.cnFillOn = True
    # vres.sfXArray = lon
    # vres.sfYArray = lat
    # vres.lbOrientation = "Horizontal"  # horizontal labelbar
    # vres.cnLinesOn = False
    # vres.cnLineLabelsOn = False
    # vres.cnLevelSelectionMode = "ExplicitLevels"
    # vres.cnFillPalette        = "BlueDarkRed18"
    # vres.cnLevels = np.arange(-5, 6, 1)
    # plot_cn = Ngl.contour(wks, h_ano, vres)

    # Ngl.overlay(plot_map, plot_cn)
    # Ngl.overlay(plot_map, plot2)
    # #
    # txres = Ngl.Resources()
    # txres.txFontHeightF = 0.024
    # #
    # Ngl.text_ndc(wks, leftString, 0.3, 0.83, txres)
    # Ngl.text_ndc(wks, rightString, 0.85, 0.83, txres)
    # #
    # Ngl.maximize_plot(wks, plot_map)
    # Ngl.draw(wind_850)
    # Ngl.frame(wks)
    Ngl.end()
    print("Finish darwing wind plot for " + str(sel_month).zfill(2) + " " +
          str(sel_year))
Пример #30
0
def cwrf_contour(fname, vname, days=None):

    if not pth.exists(fname):
        print_("You do not have the necessary '%s' file to run this script." %
               fname)
        sys.exit(1)

    dset = Nio.open_file(fname + ".nc")
    lat = dset.variables["XLAT"][0, :, :]
    lon = dset.variables["XLONG"][0, :, :]
    region, subm = re.split(os.sep, pth.dirname(fname))[-2:]

    cur_date = get_date(dset.START_DATE)
    dates = get_list_times(dset)
    if days is None:
        days = len(dates) / 10 * 10
    elif days in ('30', '60', '90'):
        days = int(days)
    else:
        print_("%s invalid, between 30, 60 and 90" % days)
        sys.exit(1)

    if vname == "RAINC":
        vdat, base = get_rain_data(dset, cur_date.month - 1, days)
        blon, blat = get_coordinates("rainc")
        title = "Precipitacion Total"
        unit = "mm"
        levels = (30, 1200, 150)
        blevels = [-300., -180., -90., -30., 30., 90., 180., 300.]
        palete = 'WhBlGrYeRe'
        bpalete = 'precip_diff_12lev'
    elif vname == "T2":
        vdat, base = get_temp_data(dset, cur_date.month - 1, days)
        blon, blat = get_coordinates("t2ave")
        title = "Temperatura Media a 2 m"
        unit = "~S~o~N~C"
        levels = (-5, 35, 5)
        blevels = [-3, -2, -1, -0.3, 0.3, 1, 2, 3]
        palete = 'MPL_coolwarm'
        bpalete = 'temp_diff_18lev'
    else:
        print_("%s not supported" % vname)
        sys.exit(1)

    rbase = regrid((blon, blat), (lon, lat), base)

    wks_type = "png"
    wks_res = Ngl.Resources()
    wks_res.wkHeight = 600
    wks_res.wkWidth = 650
    wks = Ngl.open_wks(
        wks_type, DEFAULT_FILE_FORMAT %
        (cur_date.year, cur_date.month, days, VARIABLES[vname]), wks_res)

    panelres = Ngl.Resources()
    panelres.nglMaximize = True
    panelres.nglPanelBottom = 0.03

    res = Ngl.Resources()
    res.nglDraw = False
    res.nglFrame = False
    # Mapa
    set_map(res, (np.min(lon), np.min(lat)), (np.max(lon), np.max(lat)))
    #set_map(res, (REGIONS["SA"][0][0], REGIONS["SA"][0][1]),
    #             (REGIONS["SA"][1][0], REGIONS["SA"][1][1]))
    set_labelbar(res, unit)

    res.tiMainFontHeightF = 0.025
    res.tiMainString = "Totales"
    res.sfXArray = lon
    res.sfYArray = lat

    set_contour(res, levels, cnFillPalette=palete)
    plot1 = Ngl.contour_map(wks, vdat, res)
    #res.tmYLOn = False
    #res.tmYROn = True
    #res.tmYRLabelsOn = True
    res.tiMainString = "Anomalias"
    #res.sfXArray = blon
    #res.sfYArray = blat
    set_contour(res, blevels, cnFillPalette=bpalete)
    plot2 = Ngl.contour_map(wks, vdat - rbase, res)

    txres = Ngl.Resources()
    txres.txFontHeightF = 0.03
    Ngl.text_ndc(wks, title, 0.5, 0.97, txres)

    txres.txFontHeightF = 0.02
    last = days - 1
    if days > 89:
        last = days + 1
    Ngl.text_ndc(
        wks, "Promedio %d dias desde %s hasta %s" %
        (days, dates[0].strftime("%d%b%Y"), dates[last].strftime("%d%b%Y")),
        0.5, 0.91, txres)

    txres.txFontHeightF = 0.015
    y1 = 0.120
    y2 = 0.090
    if region == "PARAGUAY":
        y1 = 0.190
        y2 = 0.160
    Ngl.text_ndc(wks, "CWRF-CAM-%s OLE~S~2~N~ (clima.pol.una.py) " % subm, 0.8,
                 y1, txres)
    txres.txFontHeightF = 0.013
    Ngl.text_ndc(
        wks, "Proyecto 14-INV-054 / GUYRA Paraguay / Facultad "
        "Politecnica", 0.75, y2, txres)

    Ngl.panel(wks, [plot1, plot2], [1, 2], panelres)
    Ngl.end()