Пример #1
1
    def test(self):
        from netCDF4 import Dataset as NetCDF

        timeidx = 0
        in_wrfnc = NetCDF(wrf_in)

        if (varname == "interplevel"):
            ref_ht_850 = _get_refvals(referent, "interplevel", repeat, multi)
            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)
            hts_850 = interplevel(hts, p, 850)

            nt.assert_allclose(to_np(hts_850), ref_ht_850)

        elif (varname == "vertcross"):
            ref_ht_cross = _get_refvals(referent, "vertcross", repeat, multi)

            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)

            pivot_point = CoordPair(hts.shape[-1] // 2, hts.shape[-2] // 2)
            ht_cross = vertcross(hts, p, pivot_point=pivot_point, angle=90.)

            nt.assert_allclose(to_np(ht_cross), ref_ht_cross, rtol=.01)

        elif (varname == "interpline"):

            ref_t2_line = _get_refvals(referent, "interpline", repeat, multi)

            t2 = getvar(in_wrfnc, "T2", timeidx=timeidx)
            pivot_point = CoordPair(t2.shape[-1] // 2, t2.shape[-2] // 2)

            t2_line1 = interpline(t2, pivot_point=pivot_point, angle=90.0)

            nt.assert_allclose(to_np(t2_line1), ref_t2_line)

        elif (varname == "vinterp"):
            # Tk to theta
            fld_tk_theta = _get_refvals(referent, "vinterp", repeat, multi)
            fld_tk_theta = np.squeeze(fld_tk_theta)

            tk = getvar(in_wrfnc, "temp", timeidx=timeidx, units="k")

            interp_levels = [200, 300, 500, 1000]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 5 / 100.
            atol = 0.0001

            field = np.squeeze(field)

            nt.assert_allclose(to_np(field), fld_tk_theta, tol, atol)
Пример #2
1
def run_post(conf):

  FIXdir = conf.get("DEFAULT","FIXbwrf")

  sfc_switch = conf.getint("post","plot_sfc")
  cloud_switch = conf.getint("post","plot_clouds")
  sfcdiags_switch = conf.getint("post","plot_sfcdiags")
  xcdiags_switch = conf.getint("post","plot_xcdiags")
  switch_700mb = conf.getint("post","plot_700mb")
  switch_500mb = conf.getint("post","plot_500mb")
  switch_300mb = conf.getint("post","plot_300mb")

#  sfc_switch = 0
#  cloud_switch = 0
#  sfcdiags_switch = 0
#  xcdiags_switch = 0
#  switch_700mb = 0
#  switch_500mb = 0
#  switch_300mb = 0

  blat = conf.getfloat("post","blat")
  blon = conf.getfloat("post","blon")

  dx = conf.getfloat("wrf","dx")

  POSTwork = conf.get("DEFAULT","POSTwork")
  os.chdir(POSTwork)

  file_wrf = glob.glob("wrfout*")[0]
  print("Processing "+file_wrf)
  init_time = file_wrf[11:21]+" "+file_wrf[22:24]+"Z"

# Download the states and coastlines
  states = cfeature.NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',
                             name='admin_1_states_provinces_shp')
# Get counties.
  reader = shpreader.Reader(FIXdir+'/shapefiles/countyp010g.shp')
  counties = list(reader.geometries())
  COUNTIES = cfeature.ShapelyFeature(counties, crs.PlateCarree())

# Open the NetCDF file
  ncfile = Dataset(file_wrf)

# Get the times and convert to datetimes
  times = getvar(ncfile, "Times", timeidx=ALL_TIMES, meta=False)
  dtimes = [datetime.strptime(str(atime), '%Y-%m-%dT%H:%M:%S.000000000') for atime in times]
  numTimes = len(times)

# Reflectivity
  ref = getvar(ncfile, "REFL_10CM", timeidx=ALL_TIMES)
  ref[0,0,0,0]=-21.0 # hack to plot a blank contour plot at the initial time

# Get upper-air quantities.
  p = getvar(ncfile, "pressure", timeidx=ALL_TIMES)
  z = getvar(ncfile, "z", units="dm", timeidx=ALL_TIMES)
  u, v = getvar(ncfile, "uvmet", units="kt", timeidx=ALL_TIMES, meta=False)
  w = getvar(ncfile, "wa", units="m s-1", timeidx=ALL_TIMES)*100. # m/s to cm/s
  rh = getvar(ncfile, "rh", timeidx=ALL_TIMES)
  wspeed = (u**2.0+v**2.0)**0.5
  tc = getvar(ncfile, "tc", timeidx=ALL_TIMES)
  dewT = getvar(ncfile, "td", units="degC", timeidx=ALL_TIMES)
  cloudfrac = getvar(ncfile, "cloudfrac", low_thresh=20., 
                     mid_thresh=955., high_thresh=4500., timeidx=ALL_TIMES)
  total_cloudfrac=np.max(cloudfrac,axis=0)
  low_cloudfrac = cloudfrac[0,:,:,:]
  mid_cloudfrac = cloudfrac[1,:,:,:]
  high_cloudfrac = cloudfrac[2,:,:,:]

# Interpolate
  z_500 = smooth2d(interplevel(z, p, 500), 3)
  tc_500 = smooth2d(interplevel(tc, p, 500), 3)
  u_500 = interplevel(u, p, 500)
  v_500 = interplevel(v, p, 500)
  wspeed_500 = interplevel(wspeed, p, 500)

  z_300 = smooth2d(interplevel(z, p, 300), 3)
  u_300 = interplevel(u, p, 300)
  v_300 = interplevel(v, p, 300)

  z_700 = interplevel(z, p, 700)
  tc_700 = interplevel(tc, p, 700)
  u_700 = interplevel(u, p, 700)
  v_700 = interplevel(v, p, 700)
  w_700 = interplevel(w, p, 700)
  rh_700 = interplevel(rh, p, 700)

  if switch_700mb == 1:

# Interpolate over NaNs.

    for itime in range(numTimes):

      z_700[itime,:,:] = interpnan(z_700[itime,:,:])
      tc_700[itime,:,:] = interpnan(tc_700[itime,:,:])
      rh_700[itime,:,:] = interpnan(rh_700[itime,:,:])
      u_700[itime,:,:] = interpnan(u_700[itime,:,:])
      v_700[itime,:,:] = interpnan(v_700[itime,:,:])
      w_700[itime,:,:] = interpnan(w_700[itime,:,:])

    z_700 = smooth2d(z_700, 3)
    tc_700 = smooth2d(tc_700, 3)
    w_700 = smooth2d(w_700, 3)

  div_300 = smooth2d(divergence([u_300*0.514444, v_300*0.514444], dx), 3) # kt to m/s

# Get the sea level pressure
  slp = getvar(ncfile, "slp", timeidx=ALL_TIMES)

# Get the wet bulb temperature
  twb = getvar(ncfile, "twb", units="degC", timeidx=ALL_TIMES)

  slp_levels=np.arange(980,1040,2)
  z_levels=np.arange(504,620,3)
  z_levels_300=np.arange(804,996,6)
  z_levels_700=np.arange(285,351,3)
  t2_levels=np.arange(-20,125,5)
  tc_levels=np.arange(-40,30,2)
  wspeed_levels=np.arange(40,150,10)
  ref_levels=np.arange(-20,60,5)
  rh_levels=np.arange(70,105,5)
  cldfrac_levels=np.arange(0.,1.1,0.1)
  twb_levels=np.arange(0,1,1)

  wup_levels=np.arange(5,55,10)
  wdown_levels=np.arange(-55,-5,10)

  div_levels=np.arange(-110,120,10)

# Get the 10-m u and v wind components.
  u_10m, v_10m = getvar(ncfile, "uvmet10", units="kt", timeidx=ALL_TIMES)
  wind_10m = (u_10m**2.0+v_10m**2.0)**0.5

# Smooth the sea level pressure since it tends to be noisy near the mountains
  smooth_slp = smooth2d(slp, 3)
  twb=twb[:,0,:,:] # lowest model level
  twb=smooth2d(twb,3)

# Get the latitude and longitude points
  lats, lons = latlon_coords(slp)

# Get the cartopy mapping object
  cart_proj = get_cartopy(slp)

  if sfcdiags_switch == 1:

    bx, by = ll_to_xy(ncfile, blat, blon, meta=False, as_int=True)

#   Create a figure
    fig = plt.figure(figsize=(12,9))
    fileout = "precip.png"

  # should be variable ACSNOW
  #  accumulated_snow = getvar(ncfile, "SNOWNC", timeidx=ALL_TIMES)

    liq_equiv = (getvar(ncfile, "RAINC", timeidx=ALL_TIMES) +
                 getvar(ncfile, "RAINNC", timeidx=ALL_TIMES))/25.4 # mm to inches

    liq_equiv_bdu = liq_equiv[:,by,bx]

    prate = np.zeros(numTimes)

    for itime in range(numTimes):

      if itime > 0 and itime < numTimes-1:
        prate[itime] = 0.5*((liq_equiv_bdu[itime+1]+liq_equiv_bdu[itime]) - 
                            (liq_equiv_bdu[itime-1]+liq_equiv_bdu[itime]))
      elif itime == 0:
        prate[0] = liq_equiv_bdu[0] 
      else:
        prate[numTimes-1] = liq_equiv_bdu[numTimes-1]-liq_equiv_bdu[numTimes-2]

    plt.bar(times, prate, width=0.0425, color="black")
    plt.plot(times, liq_equiv_bdu, color="blue")
    plt.xlim(min(times), max(times))
    plt.title("Forecast Precipitation: Boulder, CO")
    plt.xlabel("Time (UTC)")
    plt.ylabel("Running total (line) and rate (bars, inches of liquid)")

    plt.grid(b=True, which="major", axis="both", color="gray", linestyle="--")

    fig.savefig("sfcdiags/"+fileout,bbox_inches='tight')
    plt.close(fig)

#   Create a figure
    fig, ax1 = plt.subplots(figsize=(12,9))
    fileout = "t2m_td2m_wind10m_prate.png"

    t2m = 1.8*(getvar(ncfile, "T2", timeidx=ALL_TIMES)-273.15)+32.
    td2m = getvar(ncfile, "td2", units="degF", timeidx=ALL_TIMES)

    color = 'tab:blue'
    ax1.bar(times, prate, width=0.0425, color="blue")
    ax1.plot(times, liq_equiv_bdu, color="blue")
    ax1.set_ylim(0.,max([max(prate)/0.1+0.01,max(liq_equiv_bdu)+0.1]))
    ax1.set_xlabel("Time (UTC)")
    ax1.set_ylabel("Precipitation liquid amount (in) and rate (bars, in/hr)", color=color)
    ax1.tick_params(axis="y", labelcolor=color)
    ax1.grid(b=True, which="major", axis="x", color="gray", linestyle="--")

    ax2=ax1.twinx()
    ax2.plot(times, wind_10m[:,by,bx], color="black")
    ax2.barbs(times, wind_10m[:,by,bx], u_10m[:,by,bx], v_10m[:,by,bx])

    ax2.plot(times, t2m[:,by,bx], color="red")
    ax2.plot(times, td2m[:,by,bx], color="green")

    ax2.set_xlim(min(times), max(times))
    plt.title("Forecast near-surface variables: Boulder, CO")
    ax2.set_ylabel("2-m T (red) and 2-m Td (green, degF), 10-m wind (black, kt)")

    ax2.grid(b=True, which="major", axis="y", color="gray", linestyle="--")

    fig.tight_layout()
    fig.savefig("sfcdiags/"+fileout,bbox_inches='tight')
    plt.close(fig)

  if xcdiags_switch == 1:

    zinterp = np.arange(550, 880, 10)

    u_xc = vertcross(u, p, levels=zinterp, wrfin=ncfile,
      stagger='u', pivot_point=CoordPair(lat=blat,lon=blon), angle=90., meta=False)

    w_xc = vertcross(w, p, levels=zinterp, wrfin=ncfile,
      stagger='u', pivot_point=CoordPair(lat=blat,lon=blon), angle=90., meta=False)

    tc_xc = vertcross(tc, p, levels=zinterp, wrfin=ncfile,
      stagger='u', pivot_point=CoordPair(lat=blat,lon=blon), angle=90., meta=False)

    rh_xc = vertcross(rh, p, levels=zinterp, wrfin=ncfile,
      stagger='u', pivot_point=CoordPair(lat=blat,lon=blon), angle=90., meta=False)

    nx = np.shape(u_xc)[-1]
    xinterp = np.arange(0,nx,1)

    bx, by = ll_to_xy(ncfile, blat, blon, meta=False, as_int=True)

    for itime in range(numTimes):

#     Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "mtnwave_xc"+str(itime).zfill(2)+".png"

      ax=plt.gca()
      ax.set_facecolor("black")

      plt.contourf(xinterp, zinterp, u_xc[itime,:,:], 
        cmap=get_cmap("seismic"), levels=np.arange(-50,55,5))
      plt.colorbar(shrink=.62)

      w_contour = plt.contour(xinterp, zinterp, w_xc[itime,:,:],
        "--", levels=np.arange(-120,-20,20),colors="black")
      plt.clabel(w_contour, inline=1, fontsize=10, fmt="%i")

      w_contour = plt.contour(xinterp, zinterp, w_xc[itime,:,:],
        levels=np.arange(20,120,20),colors="black")
      plt.clabel(w_contour, inline=1, fontsize=10, fmt="%i")

      t_contour = plt.contour(xinterp, zinterp, tc_xc[itime,:,:],
        levels=[-20,-10,0], colors="yellow")
      plt.clabel(t_contour, inline=1, fontsize=10, fmt="%i")

#     Add location of Boulder to plot.
      plt.scatter(bx,np.max(zinterp),c='r',marker='+')

      plt.ylim([np.max(zinterp),np.min(zinterp)])
#      plt.yscale("log")
#      plt.xticks([np.arange(900,475,-25)], ["900", "875", 
#        "850", "825", "800", "775", "750", "725", "700", "675", "650",
#        "625", "600", "575", "550", "525", "500"])

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": zonal wind (fill, kt), temp (yellow lines, degC), VV (black lines, cm/s)")

      fig.savefig("xcdiags/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background xcdiags/mtnwave_xc*.png -loop 0 xcdiags/mtnwave_xc.gif")

    for itime in range(numTimes):

#     Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "mtnwave_xc_rh"+str(itime).zfill(2)+".png"

      ax=plt.gca()
      ax.set_facecolor("black")

      plt.contourf(xinterp, zinterp, rh_xc[itime,:,:],
        cmap=get_cmap("Greens"), levels=rh_levels, extend='both')
      plt.colorbar(shrink=.62)

      skip=2
      plt.quiver(xinterp[::skip], zinterp[::skip], u_xc[itime,::skip,::skip], w_xc[itime,::skip,::skip]/2.,
        scale=500, headwidth=3, color='black', pivot='middle')

      t_contour = plt.contour(xinterp, zinterp, tc_xc[itime,:,:],
        levels=[-20,-10,0], colors="yellow")
      plt.clabel(t_contour, inline=1, fontsize=10, fmt="%i")

#     Add location of Boulder to plot.
      plt.scatter(bx,np.max(zinterp),c='r',marker='+')

      plt.ylim([np.max(zinterp),np.min(zinterp)])

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": rh (fill), temp (yellow lines, degC), wind (arrows)")

      fig.savefig("xcdiags_rh/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background xcdiags_rh/mtnwave_xc_rh*.png -loop 0 xcdiags_rh/mtnwave_xc_rh.gif")

    zinterp = np.arange(150, 900, 25)

    rh_xc = vertcross(rh, p, levels=zinterp, wrfin=ncfile,
      stagger='u', pivot_point=CoordPair(lat=blat,lon=blon), angle=90., meta=False)

    tc_xc = vertcross(tc, p, levels=zinterp, wrfin=ncfile,
      stagger='u', pivot_point=CoordPair(lat=blat,lon=blon), angle=90., meta=False)

    nx = np.shape(u_xc)[-1]
    xinterp = np.arange(0,nx,1)

    bx, by = ll_to_xy(ncfile, blat, blon, meta=False, as_int=True)

    for itime in range(numTimes):

#     Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "mtnwave_xc_rh_big"+str(itime).zfill(2)+".png"

      ax=plt.gca()
      ax.set_facecolor("black")

      plt.contourf(xinterp, zinterp, rh_xc[itime,:,:],
        cmap=get_cmap("Greens"), levels=rh_levels, extend='both')
      plt.colorbar(shrink=.62)

      t_contour = plt.contour(xinterp, zinterp, tc_xc[itime,:,:],
        levels=[-20,-10,0], colors="yellow")
      plt.clabel(t_contour, inline=1, fontsize=10, fmt="%i")

#     Add location of Boulder to plot.
      plt.scatter(bx,np.max(zinterp),c='r',marker='+')

      plt.ylim([np.max(zinterp),np.min(zinterp)])

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": rh (fill), temp (yellow lines, degC)")

      fig.savefig("xcdiags_rh_big/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background xcdiags_rh_big/mtnwave_xc_rh_big*.png -loop 0 xcdiags_rh_big/mtnwave_xc_rh_big.gif")

  if sfc_switch == 1:

    bx, by = ll_to_xy(ncfile, blat, blon, meta=False, as_int=True)

    for itime in range(numTimes):

      ps = p[itime,:,by,bx]
      ps_temp = ps
      T = tc[itime,:,by,bx]
      Td = dewT[itime,:,by,bx]
      us = u[itime,:,by,bx]
      vs = v[itime,:,by,bx]

      ps = ps[ps_temp >= 100.]
      T = T[ps_temp >= 100.]
      Td = Td[ps_temp >= 100.]
      us = us[ps_temp >= 100.]
      vs = vs[ps_temp >= 100.]

      fig = plt.figure(figsize=(9, 9))
      skew = SkewT(fig, rotation=45)

      fileout = "sounding"+str(itime).zfill(2)+".png"

#     Plot the data using normal plotting functions, in this case using
#     log scaling in Y, as dictated by the typical meteorological plot.
      skew.plot(ps, T, 'r')
      skew.plot(ps, Td, 'g')
      skew.plot_barbs(ps, us, vs)
      skew.ax.set_ylim(1000, 100)
      skew.ax.set_xlim(-40, 60)

#     Calculate LCL height and plot as black dot. Because `p`'s first value is
#     ~1000 mb and its last value is ~250 mb, the `0` index is selected for
#     `p`, `T`, and `Td` to lift the parcel from the surface. If `p` was inverted,
#     i.e. start from low value, 250 mb, to a high value, 1000 mb, the `-1` index
#     should be selected.
      lcl_pressure, lcl_temperature = mpcalc.lcl(ps[0], T[0], Td[0])
      skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

#     Calculate full parcel profile and add to plot as black line
      prof = mpcalc.parcel_profile(ps, T[0], Td[0]).to('degC')
      skew.plot(ps, prof, 'k', linewidth=2)

#     Shade areas of CAPE and CIN
#      skew.shade_cin(ps, T, prof, Td)
      [cape, cin] = mpcalc.cape_cin(ps, T, Td, prof)
#      skew.shade_cape(ps, T, prof)

#     An example of a slanted line at constant T -- in this case the 0
#     isotherm
      skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)

#     Add the relevant special lines
      skew.plot_dry_adiabats()
      skew.plot_moist_adiabats()
      skew.plot_mixing_lines()

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": Boulder, CO, CAPE: "+str(round(cape.magnitude))+" J/kg CIN: "+str(round(cin.magnitude))+" J/kg")
      fig.savefig("sounding/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background sounding/sounding*.png -loop 0 sounding/sounding.gif")

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "sfc_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   Reflectivity at the lowest model level.
      plt.contourf(to_np(lons), to_np(lats), to_np(ref[itime,0,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("jet"), levels=ref_levels)

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Contour the wetbulb temperature at 0 degC.
      c_p = plt.contour(to_np(lons), to_np(lats), to_np(twb[itime,:,:]), transform=crs.PlateCarree(),
             colors="red", levels=twb_levels)
      plt.clabel(c_p, inline=1, fontsize=10, fmt="%i")

#   Make the contour outlines and filled contours for the smoothed sea level pressure.
      c_p = plt.contour(to_np(lons), to_np(lats), to_np(smooth_slp[itime,:,:]), transform=crs.PlateCarree(),
             colors="black", levels=slp_levels)
      plt.clabel(c_p, inline=1, fontsize=10, fmt="%i")

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Add the 10-m wind barbs, only plotting every other data point.
      skip=2
      plt.barbs(to_np(lons[::skip,::skip]), to_np(lats[::skip,::skip]), to_np(u_10m[itime, ::skip, ::skip]),
          to_np(v_10m[itime, ::skip, ::skip]), transform=crs.PlateCarree(), length=5.25, linewidth=0.5)

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(smooth_slp))
      ax.set_ylim(cartopy_ylim(smooth_slp))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": SLP (fill, hPa), 10-m wind (barbs, kt), LML Ref (fill, dBZ), LML WBT (red, degC)")
      fig.savefig("sfc/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background sfc/sfc*.png -loop 0 sfc/sfc.gif")

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "sfc_temp_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   2-m air temperature
      t2 = 1.8*(getvar(ncfile, "T2", timeidx=ALL_TIMES) - 273.15)+32.
      plt.contourf(to_np(lons), to_np(lats), to_np(t2[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("jet"), levels=t2_levels)

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Make the contour outlines and filled contours for the smoothed sea level pressure.
      c_p = plt.contour(to_np(lons), to_np(lats), to_np(smooth_slp[itime,:,:]), transform=crs.PlateCarree(),
             colors="black", levels=slp_levels)
      plt.clabel(c_p, inline=1, fontsize=10, fmt="%i")

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Add the 10-m wind barbs, only plotting every other data point.
      skip=2
      plt.barbs(to_np(lons[::skip,::skip]), to_np(lats[::skip,::skip]), to_np(u_10m[itime, ::skip, ::skip]),
          to_np(v_10m[itime, ::skip, ::skip]), transform=crs.PlateCarree(), length=5.25, linewidth=0.5)

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(smooth_slp))
      ax.set_ylim(cartopy_ylim(smooth_slp))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": SLP (contours, hPa), 10-m wind (barbs, kt), 2-m T (fill, degF)")
      fig.savefig("sfc_temp/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background sfc_temp/sfc_temp*.png -loop 0 sfc_temp/sfc_temp.gif")

  if cloud_switch == 1:

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "cldfrac_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   Compute and plot the total cloud fraction.
      plt.contourf(to_np(lons), to_np(lats), to_np(total_cloudfrac[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("Greys"), levels=cldfrac_levels, extend='both')

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(cloudfrac))
      ax.set_ylim(cartopy_ylim(cloudfrac))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": Total cloud fraction (fill)")
      fig.savefig("cldfrac/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background cldfrac/cldfrac*.png -loop 0 cldfrac/cldfrac.gif")

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "low_cldfrac_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   Compute and plot the cloud fraction.
      plt.contourf(to_np(lons), to_np(lats), to_np(low_cloudfrac[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("Greys"), levels=cldfrac_levels, extend='both')

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(cloudfrac))
      ax.set_ylim(cartopy_ylim(cloudfrac))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": Low cloud fraction (fill)")
      fig.savefig("low_cldfrac/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background low_cldfrac/low_cldfrac*.png -loop 0 low_cldfrac/low_cldfrac.gif")

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "mid_cldfrac_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   Compute and plot the cloud fraction.
      plt.contourf(to_np(lons), to_np(lats), to_np(mid_cloudfrac[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("Greys"), levels=cldfrac_levels, extend='both')

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(cloudfrac))
      ax.set_ylim(cartopy_ylim(cloudfrac))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": Mid cloud fraction (fill)")
      fig.savefig("mid_cldfrac/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background mid_cldfrac/mid_cldfrac*.png -loop 0 mid_cldfrac/mid_cldfrac.gif")

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "high_cldfrac_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   Compute and plot the cloud fraction.
      plt.contourf(to_np(lons), to_np(lats), to_np(high_cloudfrac[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("Greys"), levels=cldfrac_levels, extend='both')

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(cloudfrac))
      ax.set_ylim(cartopy_ylim(cloudfrac))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": High cloud fraction (fill)")
      fig.savefig("high_cldfrac/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background high_cldfrac/high_cldfrac*.png -loop 0 high_cldfrac/high_cldfrac.gif")

  if switch_500mb == 1:

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "500mb_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   wind color fill
      if np.max(wspeed_500[itime,:,:]) > np.min(wspeed_levels):
        plt.contourf(to_np(lons), to_np(lats), to_np(wspeed_500[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("rainbow"), levels=wspeed_levels)

#   Make the 500 mb height contours.
      c_z = plt.contour(to_np(lons), to_np(lats), to_np(z_500[itime,:,:]), transform=crs.PlateCarree(),
             colors="black", levels=z_levels)
      plt.clabel(c_z, inline=1, fontsize=10, fmt="%i")

#   Make the 500 mb temp contours.
      c_t = plt.contour(to_np(lons), to_np(lats), to_np(tc_500[itime,:,:]), transform=crs.PlateCarree(),
             colors="red", levels=tc_levels)
      plt.clabel(c_t, inline=1, fontsize=10, fontcolor="red", fmt="%i")

#   Add a color bar
#   plt.colorbar(ax=ax, shrink=.62)

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Add the 500mb wind barbs, only plotting every other data point.
      skip=3
      plt.barbs(to_np(lons[::skip,::skip]), to_np(lats[::skip,::skip]), to_np(u_500[itime, ::skip, ::skip]),
          to_np(v_500[itime, ::skip, ::skip]), transform=crs.PlateCarree(), length=5.25, linewidth=0.5)

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(z_500))
      ax.set_ylim(cartopy_ylim(z_500))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": 500-mb height (black, dm), temp (red, degC), and wind (fill/barbs, kt)")
      fig.savefig("500mb/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background 500mb/500mb*.png -loop 0 500mb/500mb.gif")

  if switch_700mb == 1:

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "700mb_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   rh color fill
      plt.contourf(to_np(lons), to_np(lats), to_np(rh_700[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("Greens"), levels=rh_levels, extend='both')

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Make the 700 mb height contours.
      c_z = plt.contour(to_np(lons), to_np(lats), to_np(z_700[itime,:,:]), transform=crs.PlateCarree(),
             colors="black", levels=z_levels_700)
      plt.clabel(c_z, inline=1, fontsize=10, fmt="%i")

#   Make the 700 mb temp contours.
      c_t = plt.contour(to_np(lons), to_np(lats), to_np(tc_700[itime,:,:]), transform=crs.PlateCarree(),
             colors="red", levels=tc_levels)
      plt.clabel(c_t, inline=1, fontsize=10, fontcolor="red", fmt="%i")

#   Make the 700 mb VV contours.
      c_d = plt.contour(to_np(lons), to_np(lats), to_np(w_700[itime,:,:]), transform=crs.PlateCarree(),
             colors="magenta", levels=wup_levels, linewidths=0.9)
      plt.clabel(c_d, inline=1, fontsize=10, fontcolor="magenta", fmt="%i")

      c_c = plt.contour(to_np(lons), to_np(lats), to_np(w_700[itime,:,:]), transform=crs.PlateCarree(),
             colors="blue", levels=wdown_levels, linewidths=0.9)
      plt.clabel(c_c, inline=1, fontsize=10, fontcolor="blue", fmt="%i")

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Add the 700mb wind barbs, only plotting every other data point.
      skip=3
      plt.barbs(to_np(lons[::skip,::skip]), to_np(lats[::skip,::skip]), to_np(u_700[itime, ::skip, ::skip]),
          to_np(v_700[itime, ::skip, ::skip]), transform=crs.PlateCarree(), length=5.25, linewidth=0.5)

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(z_700))
      ax.set_ylim(cartopy_ylim(z_700))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": 700-mb hgt (black, dm), T (red, degC), wind (barbs, kt), VV (cm/s), rh (fill, %)")
      fig.savefig("700mb/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background 700mb/700mb*.png -loop 0 700mb/700mb.gif")

  if switch_300mb == 1:

    for itime in range(numTimes):

#   Create a figure
      fig = plt.figure(figsize=(12,9))
      fileout = "300mb_fhr"+str(itime).zfill(2)+".png"

#   Set the GeoAxes to the projection used by WRF
      ax = plt.axes(projection=cart_proj)

#   Add the states and coastlines
      ax.add_feature(states, linewidth=0.8, edgecolor='gray')
      ax.add_feature(COUNTIES, linewidth=0.4, facecolor='none', edgecolor='gray')
      ax.coastlines('50m', linewidth=0.8)

#   300 mb divergence
      plt.contourf(to_np(lons), to_np(lats), to_np(div_300[itime,:,:]), transform=crs.PlateCarree(),
             cmap=get_cmap("seismic"), levels=div_levels)

#   Add a color bar
      plt.colorbar(ax=ax, shrink=.62)

#   Make the 300 mb height contours.
      c_z = plt.contour(to_np(lons), to_np(lats), to_np(z_300[itime,:,:]), transform=crs.PlateCarree(),
             colors="black", levels=z_levels_300)
      plt.clabel(c_z, inline=1, fontsize=10, fmt="%i")

#   Make the 300 mb divergence contours.
#      c_d = plt.contour(to_np(lons), to_np(lats), to_np(div_300[itime,:,:]), transform=crs.PlateCarree(),
#             colors="red", levels=div_levels, linewidths=0.8)
#      plt.clabel(c_d, inline=1, fontsize=10, fontcolor="red", fmt="%i")
#
#      c_c = plt.contour(to_np(lons), to_np(lats), to_np(div_300[itime,:,:]), transform=crs.PlateCarree(),
#             colors="blue", levels=conv_levels, linewidths=0.8)
#      plt.clabel(c_c, inline=1, fontsize=10, fontcolor="blue", fmt="%i")

#   Add location of Boulder to plot.
      plt.scatter(blon,blat,c='r',marker='+',transform=crs.PlateCarree())

#   Add the 300mb wind barbs, only plotting every other data point.
      skip=3
      plt.barbs(to_np(lons[::skip,::skip]), to_np(lats[::skip,::skip]), to_np(u_300[itime, ::skip, ::skip]),
          to_np(v_300[itime, ::skip, ::skip]), transform=crs.PlateCarree(), length=5.25, linewidth=0.5)

#   Set the map limits.
      ax.set_xlim(cartopy_xlim(z_300))
      ax.set_ylim(cartopy_ylim(z_300))

      plt_time=str(dtimes[itime])
      plt_time=plt_time[0:13]

      plt.title(plt_time+"Z fhr "+str(itime).zfill(2)+": 300-mb height (black, dm), wind (barbs, kt), and divergence x 10^5 (red/blue, s^-1)")
      fig.savefig("300mb/"+fileout,bbox_inches='tight')
      plt.close(fig)

    os.system("convert -delay 90 -dispose background 300mb/300mb*.png -loop 0 300mb/300mb.gif")
def interpolate_vert(ncfile, start_lat, end_lat, start_lon, end_lon, var, time,
                     start_p, end_p, interval_p):
    startpoint = CoordPair(lat=start_lat, lon=start_lon)
    endpoint = CoordPair(lat=end_lat, lon=end_lon)
    height = getvar(ncfile, 'height')
    hgt = getvar(ncfile, 'HGT')
    p = getvar(ncfile, 'pressure', timeidx=time)
    f = getvar(ncfile, var, timeidx=time)
    p_height = p[:, 0, 0]
    bool, start_layer, end_layer = get_pressure_layer(p_height, start_p, end_p)
    p_level = np.mgrid[p_height[start_layer].values:p_height[end_layer].
                       values:complex(str(end_layer - start_layer + 1) + 'j')]
    f_vert = vertcross(f,
                       p,
                       wrfin=ncfile,
                       levels=p_level,
                       start_point=startpoint,
                       end_point=endpoint,
                       latlon=True)
    if var == 'wa':
        f_vert = f_vert * 200
        print(f_vert)
    #处理插值数据的维度
    p_vert_list = f_vert.coords['vertical'].values
    print("插值的压力为:", end='')
    print(p_vert_list)
    lon_vert_list, lat_vert_list = [], []
    for i in range(len(f_vert.coords['xy_loc'])):
        s = str(f_vert.coords['xy_loc'][i].values)
        lon_vert_list.append(float(s[s.find('lon=') + 4:s.find('lon=') + 16]))
        lat_vert_list.append(float(s[s.find('lat=') + 4:s.find('lat=') + 16]))
    lon_vert_list = np.array(lon_vert_list)
    lat_vert_list = np.array(lat_vert_list)
    lon_vert_list = np.around(lon_vert_list, decimals=2)
    lat_vert_list = np.around(lat_vert_list, decimals=2)
    h_vert_list = []
    h2h = height - hgt
    for i in range(end_p, start_p - interval_p, -interval_p):
        h_vert_list.append(float(np.max(interplevel(h2h, p, i)).values))
    print("对应的高度为:", end='')
    print(h_vert_list)
    lat_vert_list = np.mgrid[lat_vert_list[0]:lat_vert_list[-1]:complex(
        str(len(lat_vert_list)) + 'j')]
    lon_vert_list = np.mgrid[lon_vert_list[0]:lon_vert_list[-1]:complex(
        str(len(lon_vert_list)) + 'j')]
    return f_vert, lat_vert_list, lon_vert_list, p_vert_list, h_vert_list
Пример #4
0
def make_result_file(opts):
    infilename = os.path.expanduser(
        os.path.join(opts.outdir, "ci_test_file.nc"))
    outfilename = os.path.expanduser(
        os.path.join(opts.outdir, "ci_result_file.nc"))

    with Dataset(infilename) as infile, Dataset(outfilename, "w") as outfile:

        for varname in WRF_DIAGS:
            var = getvar(infile, varname)
            add_to_ncfile(outfile, var, varname)

        for interptype in INTERP_METHS:
            if interptype == "interpline":
                hts = getvar(infile, "z")
                p = getvar(infile, "pressure")
                hts_850 = interplevel(hts, p, 850.)

                add_to_ncfile(outfile, hts_850, "interplevel")

            if interptype == "vertcross":

                hts = getvar(infile, "z")
                p = getvar(infile, "pressure")

                pivot_point = CoordPair(hts.shape[-1] // 2, hts.shape[-2] // 2)
                ht_cross = vertcross(hts,
                                     p,
                                     pivot_point=pivot_point,
                                     angle=90.)

                add_to_ncfile(outfile, ht_cross, "vertcross")

            if interptype == "interpline":

                t2 = getvar(infile, "T2")
                pivot_point = CoordPair(t2.shape[-1] // 2, t2.shape[-2] // 2)

                t2_line = interpline(t2, pivot_point=pivot_point, angle=90.0)

                add_to_ncfile(outfile, t2_line, "interpline")

            if interptype == "vinterp":

                tk = getvar(infile, "temp", units="k")

                interp_levels = [200, 300, 500, 1000]

                field = vinterp(infile,
                                field=tk,
                                vert_coord="theta",
                                interp_levels=interp_levels,
                                extrapolate=True,
                                field_type="tk",
                                log_p=True)

                add_to_ncfile(outfile, field, "vinterp")

        for latlonmeth in LATLON_METHS:
            if latlonmeth == "xy":
                # Hardcoded values from other unit tests
                lats = [-55, -60, -65]
                lons = [25, 30, 35]

                xy = ll_to_xy(infile, lats[0], lons[0])
                add_to_ncfile(outfile, xy, "xy")
            else:
                # Hardcoded from other unit tests
                i_s = np.asarray([10, 100, 150], int) - 1
                j_s = np.asarray([10, 100, 150], int) - 1

                ll = xy_to_ll(infile, i_s[0], j_s[0])
                add_to_ncfile(outfile, ll, "ll")
Пример #5
0
def horizontal_map(variable_name, date, start_hour, 
                                  end_hour, pressure_level=False, 
                                  subset=False, initiation=False, 
                                  save=False, gif=False):
    
    '''This function plots the chosen variable for the analysis 
    of the initiation environment on a horizontal (2D) map. Supported variables for plotting 
    procedure are updraft, reflectivity, helicity, pw, cape, cin, ctt, temperature_surface, 
    wind_shear, updraft_reflectivity, rh, omega, pvo, avo, theta_e, water_vapor, uv_wind and 
    divergence.'''
    
    ### Predefine some variables ###
    
    # Get the list of all needed wrf files
    data_dir = '/scratch3/thomasl/work/data/casestudy_baden/'
    
    # Define save directory
    save_dir = '/scratch3/thomasl/work/retrospective_part'                '/casestudy_baden/horizontal_maps/'

    # Change extent of plot
    subset_extent = [6.2, 9.4, 46.5, 48.5]
    
    # Set the location of the initiation of the thunderstorm
    initiation_location = CoordPair(lat=47.25, lon=7.85)

    # 2D variables:
    if variable_name == 'updraft':
        variable_name = 'W_UP_MAX'
        title_name = 'Maximum Z-Wind Updraft'
        colorbar_label = 'Max Z-Wind Updraft [$m$ $s^-$$^1$]'
        save_name = 'updraft'
        variable_min = 0
        variable_max = 30
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
        
    elif variable_name == 'reflectivity':
        variable_name = 'REFD_MAX'
        title_name = 'Maximum Derived Radar Reflectivity'
        colorbar_label = 'Maximum Derived Radar Reflectivity [$dBZ$]'
        save_name = 'reflectivity'
        variable_min = 0
        variable_max = 75
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
        
    elif variable_name == 'helicity':
        variable_name = 'UP_HELI_MAX'
        title_name = 'Maximum Updraft Helicity'
        colorbar_label = 'Maximum Updraft Helicity [$m^{2}$ $s^{-2}$]'
        save_name = 'helicity'
        variable_min = 0 
        variable_max = 140
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
        
    elif variable_name == 'pw':
        title_name = 'Precipitable Water'
        colorbar_label = 'Precipitable Water [$kg$ $m^{-2}$]'
        save_name = 'pw'
        variable_min = 0 
        variable_max = 50 
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
    
    elif variable_name == 'cape':
        variable_name = 'cape_2d'
        title_name = 'CAPE'
        colorbar_label = 'Convective Available Potential Energy'                             '[$J$ $kg^{-1}$]'
        save_name = 'cape'
        variable_min = 0 
        variable_max = 3000 
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
        
    elif variable_name == 'cin':
        variable_name = 'cape_2d'
        title_name = 'CIN'
        colorbar_label = 'Convective Inhibition [$J$ $kg^{-1}$]'
        save_name = 'cin'
        variable_min = 0
        variable_max = 100 

        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
        
    elif variable_name == 'ctt':
        title_name = 'Cloud Top Temperature'
        colorbar_label = 'Cloud Top Temperature [$K$]'
        save_name = 'cct'
        variable_min = 210 
        variable_max = 300 
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
    
    elif variable_name == 'temperature_surface':
        variable_name = 'T2'
        title_name = 'Temperature @ 2 m'
        colorbar_label = 'Temperature [$K$]'
        save_name = 'temperature_surface'
        variable_min = 285
        variable_max = 305

        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
            
    elif variable_name == 'wind_shear':
        variable_name = 'slp'
        title_name = 'SLP, Wind @ 850hPa, Wind @ 500hPa\n'                         'and 500-850hPa Vertical Wind Shear'
        save_name = 'wind_shear'
        variable_min = 1000
        variable_max = 1020

        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
            
    elif variable_name == 'updraft_reflectivity':
        variable_name = 'W_UP_MAX'
        title_name = 'Updraft and Reflectivity'
        colorbar_label = 'Max Z-Wind Updraft [$m$ $s^-$$^1$]'
        save_name = 'updraft_reflectivity'
        variable_min = 0
        variable_max = 30
        
        # Check if a certain pressure_level was defined.
        if pressure_level != False: 
            sys.exit('The variable {} is a 2D variable. '                      'Definition of a pressure_level for '                      'plotting process is not required.'.format(variable_name))
            
    # 3D variables:
    elif variable_name == 'rh':
        title_name = 'Relative Humidity'
        colorbar_label = 'Relative Humidity [$pct$]'
        save_name = 'rh'
        variable_min = 0
        variable_max = 100
        
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
        
    elif variable_name == 'omega':
        title_name = 'Vertical Motion'
        colorbar_label = 'Omega [$Pa$ $s^-$$^1$]'
        save_name = 'omega'
        variable_min = -50
        variable_max = 50
        
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
            
    elif variable_name == 'pvo':
        title_name = 'Potential Vorticity'
        colorbar_label = 'Potential Vorticity [$PVU$]'
        save_name = 'pvo'
        variable_min = -1 
        variable_max = 9 
        
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
            
    elif variable_name == 'avo':
        title_name = 'Absolute Vorticity'
        colorbar_label = 'Absolute Vorticity [$10^{-5}$'                             '$s^{-1}$]'
        save_name = 'avo'
        variable_min = -250
        variable_max = 250 
        
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
    
    elif variable_name == 'theta_e':
        title_name = 'Theta-E'
        colorbar_label = 'Theta-E [$K$]'
        save_name = 'theta_e'
        variable_min = 315
        variable_max = 335 
        
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
            
    elif variable_name == 'water_vapor':
        variable_name = 'QVAPOR'
        title_name = 'Water Vapor Mixing Ratio'
        colorbar_label = 'Water Vapor Mixing Ratio [$g$ $kg^{-1}$]'
        save_name = 'water_vapor'
        variable_min = 5
        variable_max = 15
        
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
    
    elif variable_name == 'uv_wind':
        variable_name = 'wspd_wdir'
        title_name = 'Wind Speed and Direction'
        colorbar_label = 'Wind Speed [$m$ $s^{-1}$]'
        save_name = 'uv_wind'
        variable_min = 0
        variable_max = 10 

        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
        
    elif variable_name == 'divergence':
        variable_name = 'ua'
        title_name = 'Horizontal Wind Divergence'
        colorbar_label = 'Divergence [$10^{-6}$ $s^{-1}$]'
        save_name = 'divergence'
        variable_min = -2.5
        variable_max = 2.5
            
        # Check if a certain pressure_level was defined.
        if pressure_level == False: 
            sys.exit('The variable {} is a 3D variable. '                      'Definition of a pressure_level for '                      'plotting process is required.'.format(variable_name))
    
    # Make a list of all wrf files in data directory
    wrflist = list()
    for (dirpath, dirnames, filenames) in os.walk(data_dir):
        wrflist += [os.path.join(dirpath, file) for file in filenames]
    
    ### Plotting Iteration ###
    
    # Iterate over a list of hourly timesteps
    time = list()
    for i in range(start_hour, end_hour):
        time = str(i).zfill(2)

        # Iterate over all 5 minutes steps of hour
        for j in range(0, 60, 5):
            minutes = str(j).zfill(2)
                
            # Load the netCDF files out of the wrflist
            ncfile = [Dataset(x) for x in wrflist
                if x.endswith('{}_{}:{}:00'.format(date, time, minutes))]
            
            # Load variable(s)
            if title_name == 'CAPE':
                variable = getvar(ncfile, variable_name)[0,:]
                
            elif title_name == 'CIN':
                variable = getvar(ncfile, variable_name)[1,:]
                
            elif variable_name == 'ctt':
                variable = getvar(ncfile, variable_name, units='K')
                
            elif variable_name == 'wspd_wdir':
                variable = getvar(ncfile, variable_name)[0,:]
            
            elif variable_name == 'QVAPOR':
                variable = getvar(ncfile, variable_name)*1000 # convert to g/kg
                    
            else:
                variable = getvar(ncfile, variable_name)

            if variable_name == 'slp':
                slp = variable.squeeze()
                
                ua = getvar(ncfile, 'ua')
                va = getvar(ncfile, 'va')

                p = getvar(ncfile, 'pressure')

                u_wind850 = interplevel(ua, p, 850)
                v_wind850 = interplevel(va, p, 850)

                u_wind850 = u_wind850.squeeze()
                v_wind850 = v_wind850.squeeze()

                u_wind500 = interplevel(ua, p, 500)
                v_wind500 = interplevel(va, p, 500)

                u_wind500 = u_wind500.squeeze()
                v_wind500 = v_wind500.squeeze()

                slp = ndimage.gaussian_filter(slp, sigma=3, order=0)
            
            # Interpolating 3d data to a horizontal pressure level
            if pressure_level != False:
                p = getvar(ncfile, 'pressure')
                variable_pressure = interplevel(variable, p, 
                                                pressure_level)
                variable = variable_pressure
                
            if variable_name == 'wspd_wdir':
                ua = getvar(ncfile, 'ua')
                va = getvar(ncfile, 'va')
                u_pressure = interplevel(ua, p, pressure_level)
                v_pressure = interplevel(va, p, pressure_level)
                
            elif title_name == 'Updraft and Reflectivity':
                reflectivity = getvar(ncfile, 'REFD_MAX')
                
            elif title_name == 'Difference in Theta-E values':
                variable = getvar(ncfile, variable_name)
                
                p = getvar(ncfile, 'pressure')
                variable_pressure1 = interplevel(variable, p, '950')
                variable_pressure2 = interplevel(variable, p, '950')
                
            elif variable_name == 'ua':
                va = getvar(ncfile, 'va')

                p = getvar(ncfile, 'pressure')

                v_pressure = interplevel(va, p, pressure_level)

                u_wind = variable.squeeze()
                v_wind = v_pressure.squeeze()

                u_wind.attrs['units']='meters/second'
                v_wind.attrs['units']='meters/second'
                
                lats, lons = latlon_coords(variable)
                lats = lats.squeeze()
                lons = lons.squeeze()

                dx, dy = mpcalc.lat_lon_grid_deltas(to_np(lons), to_np(lats))

                divergence = mpcalc.divergence(u_wind, v_wind, dx, dy, dim_order='yx')
                divergence = divergence*1e3


            # Define cart projection
            lats, lons = latlon_coords(variable)
            cart_proj = ccrs.LambertConformal(central_longitude=8.722206, 
                                    central_latitude=46.73585)

            bounds = geo_bounds(wrfin=ncfile)

            # Create figure
            fig = plt.figure(figsize=(15, 10))

            if variable_name == 'slp':
                fig.patch.set_facecolor('k')

            ax = plt.axes(projection=cart_proj)

            ### Set map extent ###
            domain_extent = [3.701088, 13.814863, 43.85472,49.49499]

            if subset == True:
                ax.set_extent([subset_extent[0],subset_extent[1],
                               subset_extent[2],subset_extent[3]],
                                 ccrs.PlateCarree())
                
            else: 
                ax.set_extent([domain_extent[0]+0.7,domain_extent[1]-0.7,
                               domain_extent[2]+0.1,domain_extent[3]-0.1],
                                 ccrs.PlateCarree())

            # Plot contour of variables
            levels_num = 11
            levels = np.linspace(variable_min, variable_max, levels_num)
            
            # Creating new colormap for diverging colormaps
            def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
                    new_cmap = LinearSegmentedColormap.from_list(
                        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, 
                                                            b=maxval),
                        cmap(np.linspace(minval, maxval, n)))
                    return new_cmap
            
            cmap = plt.get_cmap('RdYlBu')
            
            if title_name == 'CIN':
                cmap = ListedColormap(sns.cubehelix_palette(levels_num-1, 
                                        start=.5, rot=-.75, reverse=True))
                variable_plot = plt.contourf(to_np(lons), to_np(lats), to_np(variable), 
                                 levels=levels, transform=ccrs.PlateCarree(), extend='max', 
                                 cmap=cmap)
                initiation_color = 'r*'
                
            elif variable_name == 'ctt':
                cmap = ListedColormap(sns.cubehelix_palette(levels_num-1, 
                                        start=.5, rot=-.75, reverse=True))
                variable_plot = plt.contourf(to_np(lons), to_np(lats), to_np(variable), 
                                 levels=levels, transform=ccrs.PlateCarree(), extend='both', 
                                 cmap=cmap)
                initiation_color = 'r*'
                
            elif variable_name == 'pvo':
                cmap = plt.get_cmap('RdYlBu_r')
                new_cmap = truncate_colormap(cmap, 0.05, 0.9)
                new_norm = DivergingNorm(vmin=-1., vcenter=2., vmax=10)
                
                variable_plot = plt.contourf(to_np(lons), to_np(lats), to_np(variable), 
                                 levels=levels, transform=ccrs.PlateCarree(), 
                                 cmap=new_cmap, extend='both', norm=new_norm)
                initiation_color = 'k*'
                
            elif variable_name == 'avo':
                cmap = plt.get_cmap('RdYlBu_r')
                new_cmap = truncate_colormap(cmap, 0.05, 0.9)
                new_norm = DivergingNorm(vmin=variable_min, vcenter=0, vmax=variable_max)
                
                variable_plot = plt.contourf(to_np(lons), to_np(lats), to_np(variable), 
                                 levels=levels, transform=ccrs.PlateCarree(), 
                                 cmap=new_cmap, extend='both', norm=new_norm)
                initiation_color = 'k*'
                
            elif variable_name == 'omega':
                new_cmap = truncate_colormap(cmap, 0.05, 0.9)
                new_norm = DivergingNorm(vmin=variable_min, vcenter=0, vmax=variable_max)

                variable_plot = plt.contourf(to_np(lons), to_np(lats), to_np(variable), 
                                 levels=levels, transform=ccrs.PlateCarree(), 
                                 cmap=new_cmap, extend='both', norm=new_norm)
                initiation_color = 'k*'
                
            elif variable_name == 'ua':
                new_cmap = truncate_colormap(cmap, 0.05, 0.9)
                new_norm = DivergingNorm(vmin=variable_min, vcenter=0, vmax=variable_max)

                variable_plot = plt.contourf(to_np(lons), to_np(lats), divergence, 
                                 levels=levels, transform=ccrs.PlateCarree(), 
                                 cmap=new_cmap, extend='both', norm=new_norm)
                initiation_color = 'k*'
                
            elif variable_name == 'UP_HELI_MAX' or variable_name == 'W_UP_MAX' or variable_name == 'QVAPOR':
                cmap = ListedColormap(sns.cubehelix_palette(levels_num-1, 
                                        start=.5, rot=-.75))
                variable_plot = plt.contourf(to_np(lons), to_np(lats), 
                                to_np(variable), levels=levels, extend='max',
                                transform=ccrs.PlateCarree(),cmap=cmap)
                initiation_color = 'r*'
                
            elif variable_name == 'theta_e' or variable_name == 't2':
                cmap = ListedColormap(sns.cubehelix_palette(levels_num-1, 
                                        start=.5, rot=-.75))
                variable_plot = plt.contourf(to_np(lons), to_np(lats), 
                                to_np(variable), levels=levels, extend='both',
                                transform=ccrs.PlateCarree(),cmap=cmap)
                initiation_color = 'r*'

                
            elif variable_name == 'REFD_MAX':
                levels = np.arange(5., 75., 5.)
                dbz_rgb = np.array([[4,233,231],
                                    [1,159,244], [3,0,244],
                                    [2,253,2], [1,197,1],
                                    [0,142,0], [253,248,2],
                                    [229,188,0], [253,149,0],
                                    [253,0,0], [212,0,0],
                                    [188,0,0],[248,0,253],
                                    [152,84,198]], np.float32) / 255.0
                dbz_cmap, dbz_norm = from_levels_and_colors(levels, dbz_rgb,
                                                           extend='max')
                
                variable_plot = plt.contourf(to_np(lons), to_np(lats), 
                                 to_np(variable), levels=levels, extend='max',
                                 transform=ccrs.PlateCarree(), cmap=dbz_cmap,
                                            norm=dbz_norm)
                initiation_color = 'r*'
                
            elif variable_name == 'slp':
                ax.background_patch.set_fill(False)
                    
                wslice = slice(1, None, 12)
                # Plot 850-hPa wind vectors
                vectors850 = ax.quiver(to_np(lons)[wslice, wslice], 
                                       to_np(lats)[wslice, wslice],
                                       to_np(u_wind850)[wslice, wslice], 
                                       to_np(v_wind850)[wslice, wslice],
                                       headlength=4, headwidth=3, scale=400, color='gold', 
                                       label='850mb wind', transform=ccrs.PlateCarree(), 
                                       zorder=2)

                # Plot 500-hPa wind vectors
                vectors500 = ax.quiver(to_np(lons)[wslice, wslice], 
                                       to_np(lats)[wslice, wslice],
                                       to_np(u_wind500)[wslice, wslice], 
                                       to_np(v_wind500)[wslice, wslice],
                                       headlength=4, headwidth=3, scale=400, 
                                       color='cornflowerblue', zorder=2,
                                       label='500mb wind', transform=ccrs.PlateCarree())

                # Plot 500-850 shear
                shear = ax.quiver(to_np(lons[wslice, wslice]), 
                                  to_np(lats[wslice, wslice]),
                                  to_np(u_wind500[wslice, wslice]) - 
                                  to_np(u_wind850[wslice, wslice]),
                                  to_np(v_wind500[wslice, wslice]) - 
                                  to_np(v_wind850[wslice, wslice]),
                                  headlength=4, headwidth=3, scale=400, 
                                  color='deeppink', zorder=2,
                                  label='500-850mb shear', transform=ccrs.PlateCarree())

                contour = ax.contour(to_np(lons), to_np(lats), slp, levels=levels, 
                                     colors='lime', linewidths=2, alpha=0.5, zorder=1,
                                     transform=ccrs.PlateCarree())
                ax.clabel(contour, fontsize=12, inline=1, inline_spacing=4, fmt='%i')
                
                # Add a legend
                ax.legend(('850mb wind', '500mb wind', '500-850mb shear'), loc=4)

                # Manually set colors for legend
                legend = ax.get_legend()
                legend.legendHandles[0].set_color('gold')
                legend.legendHandles[1].set_color('cornflowerblue')
                legend.legendHandles[2].set_color('deeppink')
                
                initiation_color = 'w*'
            
            else:
                cmap = ListedColormap(sns.cubehelix_palette(10, 
                                        start=.5, rot=-.75))
                variable_plot = plt.contourf(to_np(lons), to_np(lats), 
                                to_np(variable), levels=levels,
                                transform=ccrs.PlateCarree(),cmap=cmap)
                initiation_color = 'r*'
                         
            # Plot reflectivity contours with colorbar 
            if title_name == 'Updraft and Reflectivity':
                dbz_levels = np.arange(35., 75., 5.)
                dbz_rgb = np.array([[253,248,2],
                        [229,188,0], [253,149,0],
                        [253,0,0], [212,0,0],
                        [188,0,0],[248,0,253],
                        [152,84,198]], np.float32) / 255.0
                dbz_cmap, dbz_norm = from_levels_and_colors(dbz_levels, dbz_rgb,
                                               extend='max')                

                contours = plt.contour(to_np(lons), to_np(lats), 
                                           to_np(reflectivity), 
                                           levels=dbz_levels, 
                                           transform=ccrs.PlateCarree(), 
                                           cmap=dbz_cmap, norm=dbz_norm, 
                                           linewidths=1)

                cbar_refl = mpu.colorbar(contours, ax, orientation='horizontal', aspect=10, 
                                         shrink=.5, pad=0.05)
                cbar_refl.set_label('Maximum Derived Radar Reflectivity'                                         '[$dBZ$]', fontsize=12.5)
                colorbar_lines = cbar_refl.ax.get_children()
                colorbar_lines[0].set_linewidths([10]*5)
            
            # Add wind quivers for every 10th data point
            if variable_name == 'wspd_wdir':
                plt.quiver(to_np(lons[::10,::10]), to_np(lats[::10,::10]),
                            to_np(u_pressure[::10, ::10]), 
                            to_np(v_pressure[::10, ::10]),
                            transform=ccrs.PlateCarree())
            
            # Plot colorbar
            if variable_name == 'slp':
                pass
            else:
                cbar = mpu.colorbar(variable_plot, ax, orientation='vertical', aspect=40, 
                                    shrink=.05, pad=0.05)
                cbar.set_label(colorbar_label, fontsize=15)
                cbar.set_ticks(levels)
            
            # Add borders and coastlines
            if variable_name == 'slp':
                ax.add_feature(cfeature.BORDERS.with_scale('10m'), 
                           edgecolor='white', linewidth=2)
                ax.add_feature(cfeature.COASTLINE.with_scale('10m'), 
                           edgecolor='white', linewidth=2)
            else:
                ax.add_feature(cfeature.BORDERS.with_scale('10m'), 
                               linewidth=0.8)
                ax.add_feature(cfeature.COASTLINE.with_scale('10m'), 
                               linewidth=0.8)
            
            ### Add initiation location ###
            if initiation == True:
                ax.plot(initiation_location.lon, initiation_location.lat, 
                        initiation_color, markersize=20, transform=ccrs.PlateCarree())
            
            # Add gridlines
            lon = np.arange(0, 20, 1)
            lat = np.arange(40, 60, 1)

            gl = ax.gridlines(xlocs=lon, ylocs=lat, zorder=3)
            
            # Add tick labels
            mpu.yticklabels(lat, ax=ax, fontsize=12.5)
            mpu.xticklabels(lon, ax=ax, fontsize=12.5)
            
            # Make nicetime
            file_name = '{}wrfout_d02_{}_{}:{}:00'.format(data_dir, 
                                                          date, time, minutes)
            xr_file = xr.open_dataset(file_name)
            nicetime = pd.to_datetime(xr_file.QVAPOR.isel(Time=0).XTIME.values)
            nicetime = nicetime.strftime('%Y-%m-%d %H:%M')
            
            # Add plot title
            if pressure_level != False: 
                ax.set_title('{} @ {} hPa'.format(title_name, pressure_level), 
                             loc='left', fontsize=15)
                ax.set_title('Valid time: {} UTC'.format(nicetime), 
                             loc='right', fontsize=15)
            else:
                if variable_name == 'slp':
                    ax.set_title(title_name, loc='left', fontsize=15, color='white')
                    ax.set_title('Valid time: {} UTC'.format(nicetime), 
                                 loc='right', fontsize=15, color='white')
                else:
                    ax.set_title(title_name, loc='left', fontsize=20)
                    ax.set_title('Valid time: {} UTC'.format(nicetime), 
                                 loc='right', fontsize=15)

            plt.show()
            
            ### Save figure ###
            if save == True:
                if pressure_level != False: 
                    if subset == True:
                        fig.savefig('{}/{}/horizontal_map_{}_subset_{}_{}_{}:{}.png'.format(
                            save_dir, save_name, save_name, pressure_level, date, time, 
                            minutes), bbox_inches='tight', dpi=300)
                    else: 
                        fig.savefig('{}/{}/horizontal_map_{}_{}_{}_{}:{}.png'.format(
                            save_dir, save_name, save_name, pressure_level, date, time, 
                            minutes), bbox_inches='tight', dpi=300)
                
                else: 
                    if subset == True:
                        fig.savefig('{}/{}/horizontal_map_{}_subset_{}_{}:{}.png'.format(
                            save_dir, save_name, save_name, date, time, minutes),
                                    bbox_inches='tight', dpi=300, facecolor=fig.get_facecolor())
                    
                    else: 
                        fig.savefig('{}/{}/horizontal_map_{}_{}_{}:{}.png'.format(
                            save_dir, save_name, save_name, date, time, minutes), 
                                    bbox_inches='tight', dpi=300, facecolor=fig.get_facecolor())
        
    ### Make a GIF from the plots ###
    if gif == True: 
        # Predifine some variables
        gif_data_dir = save_dir + save_name
        gif_save_dir = '{}gifs/'.format(save_dir)
        gif_save_name = 'horizontal_map_{}.gif'.format(save_name)

        # GIF creating procedure
        os.chdir(gif_data_dir)

        image_folder = os.fsencode(gif_data_dir)

        filenames = []

        for file in os.listdir(image_folder):
            filename = os.fsdecode(file)
            if filename.endswith( ('.png') ):
                filenames.append(filename)

        filenames.sort()
        images = list(map(lambda filename: imageio.imread(filename), 
                          filenames))

        imageio.mimsave(os.path.join(gif_save_dir + gif_save_name), 
                        images, duration = 0.50)
Пример #6
0
    def test(self):
        try:
            from netCDF4 import Dataset as NetCDF
        except:
            pass

        try:
            from PyNIO import Nio
        except:
            pass

        if not multi:
            timeidx = 0
            if not pynio:
                in_wrfnc = NetCDF(wrf_in)
            else:
                # Note: Python doesn't like it if you reassign an outer scoped
                # variable (wrf_in in this case)
                if not wrf_in.endswith(".nc"):
                    wrf_file = wrf_in + ".nc"
                else:
                    wrf_file = wrf_in
                in_wrfnc = Nio.open_file(wrf_file)
        else:
            timeidx = None
            if not pynio:
                nc = NetCDF(wrf_in)
                in_wrfnc = [nc for i in xrange(repeat)]
            else:
                if not wrf_in.endswith(".nc"):
                    wrf_file = wrf_in + ".nc"
                else:
                    wrf_file = wrf_in
                nc = Nio.open_file(wrf_file)
                in_wrfnc = [nc for i in xrange(repeat)]

        if (varname == "interplevel"):
            ref_ht_500 = _get_refvals(referent, "z_500", repeat, multi)
            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)

            # Make sure the numpy versions work first
            hts_500 = interplevel(to_np(hts), to_np(p), 500)
            hts_500 = interplevel(hts, p, 500)

            nt.assert_allclose(to_np(hts_500), ref_ht_500)

        elif (varname == "vertcross"):
            ref_ht_cross = _get_refvals(referent, "ht_cross", repeat, multi)
            ref_p_cross = _get_refvals(referent, "p_cross", repeat, multi)

            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)

            pivot_point = CoordPair(hts.shape[-1] / 2, hts.shape[-2] / 2)
            #ht_cross = vertcross(to_np(hts), p, pivot_point=pivot_point,
            #                     angle=90., latlon=True)
            # Make sure the numpy versions work first
            ht_cross = vertcross(to_np(hts),
                                 to_np(p),
                                 pivot_point=pivot_point,
                                 angle=90.)
            ht_cross = vertcross(hts, p, pivot_point=pivot_point, angle=90.)

            # Note:  Until the bug is fixed in NCL, the wrf-python cross
            # sections will contain one extra point
            nt.assert_allclose(to_np(ht_cross)[..., 0:-1],
                               ref_ht_cross,
                               rtol=.01)

            # Test the manual projection method with lat/lon
            lats = hts.coords["XLAT"]
            lons = hts.coords["XLONG"]
            ll_point = ll_points(lats, lons)
            pivot = CoordPair(lat=lats[int(lats.shape[-2] / 2),
                                       int(lats.shape[-1] / 2)],
                              lon=lons[int(lons.shape[-2] / 2),
                                       int(lons.shape[-1] / 2)])
            v1 = vertcross(hts,
                           p,
                           wrfin=in_wrfnc,
                           pivot_point=pivot_point,
                           angle=90.0)
            v2 = vertcross(hts,
                           p,
                           projection=hts.attrs["projection"],
                           ll_point=ll_point,
                           pivot_point=pivot_point,
                           angle=90.)

            nt.assert_allclose(to_np(v1), to_np(v2), rtol=.01)

            # Test opposite
            p_cross1 = vertcross(p, hts, pivot_point=pivot_point, angle=90.0)

            nt.assert_allclose(to_np(p_cross1)[..., 0:-1],
                               ref_p_cross,
                               rtol=.01)
            # Test point to point
            start_point = CoordPair(0, hts.shape[-2] / 2)
            end_point = CoordPair(-1, hts.shape[-2] / 2)

            p_cross2 = vertcross(p,
                                 hts,
                                 start_point=start_point,
                                 end_point=end_point)

            nt.assert_allclose(to_np(p_cross1), to_np(p_cross2))

        elif (varname == "interpline"):

            ref_t2_line = _get_refvals(referent, "t2_line", repeat, multi)

            t2 = getvar(in_wrfnc, "T2", timeidx=timeidx)
            pivot_point = CoordPair(t2.shape[-1] / 2, t2.shape[-2] / 2)

            #t2_line1 = interpline(to_np(t2), pivot_point=pivot_point,
            #                      angle=90.0, latlon=True)
            # Make sure the numpy version works
            t2_line1 = interpline(to_np(t2),
                                  pivot_point=pivot_point,
                                  angle=90.0)
            t2_line1 = interpline(t2, pivot_point=pivot_point, angle=90.0)

            # Note:  After NCL is fixed, remove the slice.
            nt.assert_allclose(to_np(t2_line1)[..., 0:-1], ref_t2_line)

            # Test the manual projection method with lat/lon
            lats = t2.coords["XLAT"]
            lons = t2.coords["XLONG"]
            ll_point = ll_points(lats, lons)
            pivot = CoordPair(lat=lats[int(lats.shape[-2] / 2),
                                       int(lats.shape[-1] / 2)],
                              lon=lons[int(lons.shape[-2] / 2),
                                       int(lons.shape[-1] / 2)])
            l1 = interpline(t2,
                            wrfin=in_wrfnc,
                            pivot_point=pivot_point,
                            angle=90.0)
            l2 = interpline(t2,
                            projection=t2.attrs["projection"],
                            ll_point=ll_point,
                            pivot_point=pivot_point,
                            angle=90.)
            nt.assert_allclose(to_np(l1), to_np(l2), rtol=.01)

            # Test point to point
            start_point = CoordPair(0, t2.shape[-2] / 2)
            end_point = CoordPair(-1, t2.shape[-2] / 2)

            t2_line2 = interpline(t2,
                                  start_point=start_point,
                                  end_point=end_point)

            nt.assert_allclose(to_np(t2_line1), to_np(t2_line2))
        elif (varname == "vinterp"):
            # Tk to theta
            fld_tk_theta = _get_refvals(referent, "fld_tk_theta", repeat,
                                        multi)
            fld_tk_theta = np.squeeze(fld_tk_theta)

            tk = getvar(in_wrfnc, "temp", timeidx=timeidx, units="k")

            interp_levels = [200, 300, 500, 1000]

            # Make sure the numpy version works
            field = vinterp(in_wrfnc,
                            field=to_np(tk),
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 5 / 100.
            atol = 0.0001

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_theta)))
            nt.assert_allclose(to_np(field), fld_tk_theta, tol, atol)

            # Tk to theta-e
            fld_tk_theta_e = _get_refvals(referent, "fld_tk_theta_e", repeat,
                                          multi)
            fld_tk_theta_e = np.squeeze(fld_tk_theta_e)

            interp_levels = [200, 300, 500, 1000]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="theta-e",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 3 / 100.
            atol = 50.0001

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_theta_e)/fld_tk_theta_e)*100)
            nt.assert_allclose(to_np(field), fld_tk_theta_e, tol, atol)

            # Tk to pressure
            fld_tk_pres = _get_refvals(referent, "fld_tk_pres", repeat, multi)
            fld_tk_pres = np.squeeze(fld_tk_pres)

            interp_levels = [850, 500]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            #print (np.amax(np.abs(to_np(field) - fld_tk_pres)))
            nt.assert_allclose(to_np(field), fld_tk_pres, tol, atol)

            # Tk to geoht_msl
            fld_tk_ght_msl = _get_refvals(referent, "fld_tk_ght_msl", repeat,
                                          multi)
            fld_tk_ght_msl = np.squeeze(fld_tk_ght_msl)
            interp_levels = [1, 2]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="ght_msl",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_ght_msl)))
            nt.assert_allclose(to_np(field), fld_tk_ght_msl, tol, atol)

            # Tk to geoht_agl
            fld_tk_ght_agl = _get_refvals(referent, "fld_tk_ght_agl", repeat,
                                          multi)
            fld_tk_ght_agl = np.squeeze(fld_tk_ght_agl)
            interp_levels = [1, 2]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="ght_agl",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_ght_agl)))
            nt.assert_allclose(to_np(field), fld_tk_ght_agl, tol, atol)

            # Hgt to pressure
            fld_ht_pres = _get_refvals(referent, "fld_ht_pres", repeat, multi)
            fld_ht_pres = np.squeeze(fld_ht_pres)

            z = getvar(in_wrfnc, "height", timeidx=timeidx, units="m")
            interp_levels = [500, 50]
            field = vinterp(in_wrfnc,
                            field=z,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="ght",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_ht_pres)))
            nt.assert_allclose(to_np(field), fld_ht_pres, tol, atol)

            # Pressure to theta
            fld_pres_theta = _get_refvals(referent, "fld_pres_theta", repeat,
                                          multi)
            fld_pres_theta = np.squeeze(fld_pres_theta)

            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)
            interp_levels = [200, 300, 500, 1000]
            field = vinterp(in_wrfnc,
                            field=p,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="pressure",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_pres_theta)))
            nt.assert_allclose(to_np(field), fld_pres_theta, tol, atol)

            # Theta-e to pres
            fld_thetae_pres = _get_refvals(referent, "fld_thetae_pres", repeat,
                                           multi)
            fld_thetae_pres = np.squeeze(fld_thetae_pres)

            eth = getvar(in_wrfnc, "eth", timeidx=timeidx)
            interp_levels = [850, 500, 5]
            field = vinterp(in_wrfnc,
                            field=eth,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="theta-e",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_thetae_pres)))
            nt.assert_allclose(to_np(field), fld_thetae_pres, tol, atol)
Пример #7
0
from wrf import to_np, getvar, CoordPair, vertcross
import matplotlib.gridspec as gridspec
from netCDF4 import Dataset, num2date
from pyroms import vgrid
# from   octant              import tools
import numpy as np
import matplotlib.pyplot as pltexitr

####### WRF options #######
# WRF input
filename_wrf = "/media/ueslei/Ueslei/INPE/2014/Outputs/WRF/wrf_I_t01.nc"
filename_wr = "/media/ueslei/Ueslei/INPE/2014/Outputs/WR/wr_I_t01.nc"
filename_wrs = "/media/ueslei/Ueslei/INPE/2014/Outputs/WRS/wrs_I_t01.nc"

# Create the start point and end point for the cross section
start_point = CoordPair(lat=-41, lon=-60)
end_point = CoordPair(lat=-41, lon=-30)
# WRF max height (meters)
levels = np.arange(0, 601., 1.)
# WRF grid height spacing
wrf_spacing = 100
# WRF timestep
timeidx = 80

####### ROMS options #######
# ROMS input
path = '/media/ueslei/Ueslei/INPE/2014/Outputs/WRS/'
name = 'cbm12_ocean_his.nc'

# ROMS time
ntime = 40
Пример #8
0
from cartopy import crs
from cartopy.feature import NaturalEarthFeature, COLORS
from netCDF4 import Dataset
from wrf import (getvar, to_np, get_cartopy, latlon_coords, vertcross,cartopy_xlim, cartopy_ylim, interpline, CoordPair, ALL_TIMES)
from datetime import datetime, timedelta

## SE CARGA LA SALIDA SIN POSTPROCESAR
wrf_file = Dataset("...")
## cantidad de tiempos
tpos = (getvar(wrf_file, "z", ALL_TIMES).shape)[0]

# agregar el inicio de la corrida, y luego ver el espaciado de cada una
t_ini = datetime.strptime('17-09-2012 18:00:00', '%d-%m-%Y %H:%M:%S')

# Definir lat y lon del corte vertical
cross_start = CoordPair(lat=-24.75, lon=-68.5)
cross_end = CoordPair(lat=-24.75, lon=-62)

if tpos == 0 : 
        print('ES UN SOLO TPO')
        exit()
# Se consiguen las variables del WRF
for tidx in range(0,tpos) :
#tidx = 8        ## es el tiempo de la corrida, desde cero hasta el tiempo final
        ## PARA TERRENO
        ht = getvar(wrf_file, "z", tidx)
        ter = getvar(wrf_file, "ter", tidx)
        w = getvar(wrf_file, 'wa', tidx)
        ## VARIABLE PARA GRAFICAR 
        ## Una lista de variables : https://wrf-python.readthedocs.io/en/latest/user_api/generated/wrf.getvar.html#wrf.getvar
        var = getvar(wrf_file, "theta", tidx)
Пример #9
0
    def test(self):
        try:
            from netCDF4 import Dataset as NetCDF
        except ImportError:
            pass

        try:
            import Nio
        except ImportError:
            pass

        timeidx = 0 if not multi else None
        pat = os.path.join(dir, pattern)
        wrf_files = glob.glob(pat)
        wrf_files.sort()

        wrfin = []
        for fname in wrf_files:
            if not pynio:
                f = NetCDF(fname)
                try:
                    f.set_always_mask(False)
                except AttributeError:
                    pass
                wrfin.append(f)
            else:
                if not fname.endswith(".nc"):
                    _fname = fname + ".nc"
                else:
                    _fname = fname
                f = Nio.open_file(_fname)
                wrfin.append(f)

        if (varname == "interplevel"):
            ref_ht_500 = _get_refvals(referent, "z_500", multi)
            ref_p_5000 = _get_refvals(referent, "p_5000", multi)
            ref_ht_multi = _get_refvals(referent, "z_multi", multi)
            ref_p_multi = _get_refvals(referent, "p_multi", multi)

            ref_ht2_500 = _get_refvals(referent, "z2_500", multi)
            ref_p2_5000 = _get_refvals(referent, "p2_5000", multi)
            ref_ht2_multi = _get_refvals(referent, "z2_multi", multi)
            ref_p2_multi = _get_refvals(referent, "p2_multi", multi)

            ref_p_lev2d = _get_refvals(referent, "p_lev2d", multi)

            hts = getvar(wrfin, "z", timeidx=timeidx)
            p = getvar(wrfin, "pressure", timeidx=timeidx)
            wspd_wdir = getvar(wrfin, "wspd_wdir", timeidx=timeidx)

            # Make sure the numpy versions work first
            hts_500 = interplevel(to_np(hts), to_np(p), 500)
            hts_500 = interplevel(hts, p, 500)

            # Note: the '*2*' versions in the reference are testing
            # against the new version of interplevel in NCL
            nt.assert_allclose(to_np(hts_500), ref_ht_500)
            nt.assert_allclose(to_np(hts_500), ref_ht2_500)

            # Make sure the numpy versions work first
            p_5000 = interplevel(to_np(p), to_np(hts), 5000)
            p_5000 = interplevel(p, hts, 5000)

            nt.assert_allclose(to_np(p_5000), ref_p_5000)
            nt.assert_allclose(to_np(p_5000), ref_p2_5000)

            hts_multi = interplevel(to_np(hts), to_np(p),
                                    [1000., 850., 500., 250.])
            hts_multi = interplevel(hts, p, [1000., 850., 500., 250.])

            nt.assert_allclose(to_np(hts_multi), ref_ht_multi)
            nt.assert_allclose(to_np(hts_multi), ref_ht2_multi)

            p_multi = interplevel(to_np(p), to_np(hts),
                                  [500., 2500., 5000., 10000.])
            p_multi = interplevel(p, hts, [500., 2500., 5000., 10000.])

            nt.assert_allclose(to_np(p_multi), ref_p_multi)
            nt.assert_allclose(to_np(p_multi), ref_p2_multi)

            pblh = getvar(wrfin, "PBLH", timeidx=timeidx)
            p_lev2d = interplevel(to_np(p), to_np(hts), to_np(pblh))
            p_lev2d = interplevel(p, hts, pblh)
            nt.assert_allclose(to_np(p_lev2d), ref_p_lev2d)

            # Just make sure these run below
            wspd_wdir_500 = interplevel(to_np(wspd_wdir), to_np(p), 500)
            wspd_wdir_500 = interplevel(wspd_wdir, p, 500)

            wspd_wdir_multi = interplevel(to_np(wspd_wdir), to_np(p),
                                          [1000, 500, 250])
            wdpd_wdir_multi = interplevel(wspd_wdir, p, [1000, 500, 250])

            wspd_wdir_pblh = interplevel(to_np(wspd_wdir), to_np(hts), pblh)
            wspd_wdir_pblh = interplevel(wspd_wdir, hts, pblh)

            if multi:
                wspd_wdir_pblh_2 = interplevel(to_np(wspd_wdir), to_np(hts),
                                               pblh[0, :])
                wspd_wdir_pblh_2 = interplevel(wspd_wdir, hts, pblh[0, :])

                # Since PBLH doesn't change in this case, it should match
                # the 0 time from previous computation. Note that this
                # only works when the data has 1 time step that is repeated.
                # If you use a different case with multiple times,
                # this will probably fail.
                nt.assert_allclose(to_np(wspd_wdir_pblh_2[:, 0, :]),
                                   to_np(wspd_wdir_pblh[:, 0, :]))

                nt.assert_allclose(to_np(wspd_wdir_pblh_2[:, -1, :]),
                                   to_np(wspd_wdir_pblh[:, 0, :]))

        elif (varname == "vertcross"):
            ref_ht_cross = _get_refvals(referent, "ht_cross", multi)
            ref_p_cross = _get_refvals(referent, "p_cross", multi)
            ref_ht_vertcross1 = _get_refvals(referent, "ht_vertcross1", multi)
            ref_ht_vertcross2 = _get_refvals(referent, "ht_vertcross2", multi)
            ref_ht_vertcross3 = _get_refvals(referent, "ht_vertcross3", multi)

            hts = getvar(wrfin, "z", timeidx=timeidx)
            p = getvar(wrfin, "pressure", timeidx=timeidx)

            pivot_point = CoordPair(hts.shape[-1] / 2, hts.shape[-2] / 2)

            # Beginning in wrf-python 1.3, users can select number of levels.
            # Originally, for pressure, dz was 10, so let's back calculate
            # the number of levels.
            p_max = np.floor(np.amax(p) / 10) * 10  # bottom value
            p_min = np.ceil(np.amin(p) / 10) * 10  # top value

            p_autolevels = int((p_max - p_min) / 10)

            # Make sure the numpy versions work first

            ht_cross = vertcross(to_np(hts),
                                 to_np(p),
                                 pivot_point=pivot_point,
                                 angle=90.,
                                 autolevels=p_autolevels)

            ht_cross = vertcross(hts,
                                 p,
                                 pivot_point=pivot_point,
                                 angle=90.,
                                 autolevels=p_autolevels)

            try:
                nt.assert_allclose(to_np(ht_cross), ref_ht_cross, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(ht_cross) - ref_ht_cross)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            lats = hts.coords["XLAT"]
            lons = hts.coords["XLONG"]

            # Test the manual projection method with lat/lon
            # Only do this for the non-multi case, since the domain
            # might be moving
            if not multi:
                if lats.ndim > 2:  # moving nest
                    lats = lats[0, :]
                    lons = lons[0, :]

                ll_point = ll_points(lats, lons)

                pivot = CoordPair(lat=lats[int(lats.shape[-2] / 2),
                                           int(lats.shape[-1] / 2)],
                                  lon=lons[int(lons.shape[-2] / 2),
                                           int(lons.shape[-1] / 2)])

                v1 = vertcross(hts,
                               p,
                               wrfin=wrfin,
                               pivot_point=pivot_point,
                               angle=90.0)
                v2 = vertcross(hts,
                               p,
                               projection=hts.attrs["projection"],
                               ll_point=ll_point,
                               pivot_point=pivot_point,
                               angle=90.)

                try:
                    nt.assert_allclose(to_np(v1), to_np(v2), atol=.0001)
                except AssertionError:
                    absdiff = np.abs(to_np(v1) - to_np(v2))
                    maxdiff = np.amax(absdiff)
                    print(maxdiff)
                    print(np.argwhere(absdiff == maxdiff))
                    raise

            # Test opposite

            p_cross1 = vertcross(p, hts, pivot_point=pivot_point, angle=90.0)

            try:
                nt.assert_allclose(to_np(p_cross1), ref_p_cross, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(p_cross1) - ref_p_cross)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Test point to point
            start_point = CoordPair(0, hts.shape[-2] / 2)
            end_point = CoordPair(-1, hts.shape[-2] / 2)

            p_cross2 = vertcross(p,
                                 hts,
                                 start_point=start_point,
                                 end_point=end_point)

            try:
                nt.assert_allclose(to_np(p_cross1),
                                   to_np(p_cross2),
                                   atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(p_cross1) - to_np(p_cross2))
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Check the new vertcross routine
            pivot_point = CoordPair(hts.shape[-1] / 2, hts.shape[-2] / 2)
            ht_cross = vertcross(hts,
                                 p,
                                 pivot_point=pivot_point,
                                 angle=90.,
                                 latlon=True)

            try:
                nt.assert_allclose(to_np(ht_cross),
                                   to_np(ref_ht_vertcross1),
                                   atol=.005)
            except AssertionError:
                absdiff = np.abs(to_np(ht_cross) - to_np(ref_ht_vertcross1))
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            levels = [1000., 850., 700., 500., 250.]
            ht_cross = vertcross(hts,
                                 p,
                                 pivot_point=pivot_point,
                                 angle=90.,
                                 levels=levels,
                                 latlon=True)

            try:
                nt.assert_allclose(to_np(ht_cross),
                                   to_np(ref_ht_vertcross2),
                                   atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(ht_cross) - to_np(ref_ht_vertcross2))
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            idxs = (0, slice(None)) if lats.ndim > 2 else (slice(None), )

            start_lat = np.amin(
                lats[idxs]) + .25 * (np.amax(lats[idxs]) - np.amin(lats[idxs]))
            end_lat = np.amin(
                lats[idxs]) + .65 * (np.amax(lats[idxs]) - np.amin(lats[idxs]))

            start_lon = np.amin(
                lons[idxs]) + .25 * (np.amax(lons[idxs]) - np.amin(lons[idxs]))
            end_lon = np.amin(
                lons[idxs]) + .65 * (np.amax(lons[idxs]) - np.amin(lons[idxs]))

            start_point = CoordPair(lat=start_lat, lon=start_lon)
            end_point = CoordPair(lat=end_lat, lon=end_lon)

            ll_point = ll_points(lats[idxs], lons[idxs])

            ht_cross = vertcross(hts,
                                 p,
                                 start_point=start_point,
                                 end_point=end_point,
                                 projection=hts.attrs["projection"],
                                 ll_point=ll_point,
                                 latlon=True,
                                 autolevels=1000)

            try:
                nt.assert_allclose(to_np(ht_cross),
                                   to_np(ref_ht_vertcross3),
                                   atol=.01)
            except AssertionError:
                absdiff = np.abs(to_np(ht_cross) - to_np(ref_ht_vertcross3))
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            if multi:
                ntimes = hts.shape[0]

                for t in range(ntimes):
                    hts = getvar(wrfin, "z", timeidx=t)
                    p = getvar(wrfin, "pressure", timeidx=t)

                    ht_cross = vertcross(hts,
                                         p,
                                         start_point=start_point,
                                         end_point=end_point,
                                         wrfin=wrfin,
                                         timeidx=t,
                                         latlon=True,
                                         autolevels=1000)

                    refname = "ht_vertcross_t{}".format(t)
                    ref_ht_vertcross = _get_refvals(referent, refname, False)

                    try:
                        nt.assert_allclose(to_np(ht_cross),
                                           to_np(ref_ht_vertcross),
                                           atol=.01)
                    except AssertionError:
                        absdiff = np.abs(
                            to_np(ht_cross) - to_np(ref_ht_vertcross))
                        maxdiff = np.amax(absdiff)
                        print(maxdiff)
                        print(np.argwhere(absdiff == maxdiff))
                        raise

        elif (varname == "interpline"):

            ref_t2_line = _get_refvals(referent, "t2_line", multi)
            ref_t2_line2 = _get_refvals(referent, "t2_line2", multi)
            ref_t2_line3 = _get_refvals(referent, "t2_line3", multi)

            t2 = getvar(wrfin, "T2", timeidx=timeidx)
            pivot_point = CoordPair(t2.shape[-1] / 2, t2.shape[-2] / 2)

            # Make sure the numpy version works
            t2_line1 = interpline(to_np(t2),
                                  pivot_point=pivot_point,
                                  angle=90.0)
            t2_line1 = interpline(t2, pivot_point=pivot_point, angle=90.0)

            nt.assert_allclose(to_np(t2_line1), ref_t2_line)

            # Test the new NCL wrf_user_interplevel result
            try:
                nt.assert_allclose(to_np(t2_line1), ref_t2_line2)
            except AssertionError:
                absdiff = np.abs(to_np(t2_line1) - ref_t2_line2)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Test the manual projection method with lat/lon
            lats = t2.coords["XLAT"]
            lons = t2.coords["XLONG"]
            if multi:
                if lats.ndim > 2:  # moving nest
                    lats = lats[0, :]
                    lons = lons[0, :]

            ll_point = ll_points(lats, lons)

            pivot = CoordPair(lat=lats[int(lats.shape[-2] / 2),
                                       int(lats.shape[-1] / 2)],
                              lon=lons[int(lons.shape[-2] / 2),
                                       int(lons.shape[-1] / 2)])

            l1 = interpline(t2,
                            wrfin=wrfin,
                            pivot_point=pivot_point,
                            angle=90.0)

            l2 = interpline(t2,
                            projection=t2.attrs["projection"],
                            ll_point=ll_point,
                            pivot_point=pivot_point,
                            angle=90.)
            try:
                nt.assert_allclose(to_np(l1), to_np(l2))
            except AssertionError:
                absdiff = np.abs(to_np(l1) - to_np(l2))
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Test point to point
            start_point = CoordPair(0, t2.shape[-2] / 2)
            end_point = CoordPair(-1, t2.shape[-2] / 2)

            t2_line2 = interpline(t2,
                                  start_point=start_point,
                                  end_point=end_point)

            try:
                nt.assert_allclose(to_np(t2_line1), to_np(t2_line2))
            except AssertionError:
                absdiff = np.abs(to_np(t2_line1) - t2_line2)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Now test the start/end with lat/lon points

            start_lat = float(
                np.amin(lats) + .25 * (np.amax(lats) - np.amin(lats)))
            end_lat = float(
                np.amin(lats) + .65 * (np.amax(lats) - np.amin(lats)))

            start_lon = float(
                np.amin(lons) + .25 * (np.amax(lons) - np.amin(lons)))
            end_lon = float(
                np.amin(lons) + .65 * (np.amax(lons) - np.amin(lons)))

            start_point = CoordPair(lat=start_lat, lon=start_lon)
            end_point = CoordPair(lat=end_lat, lon=end_lon)

            t2_line3 = interpline(t2,
                                  wrfin=wrfin,
                                  timeidx=0,
                                  start_point=start_point,
                                  end_point=end_point,
                                  latlon=True)

            try:
                nt.assert_allclose(to_np(t2_line3), ref_t2_line3, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(t2_line3) - ref_t2_line3)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Test all time steps
            if multi:
                refnc = NetCDF(referent)
                ntimes = t2.shape[0]

                for t in range(ntimes):
                    t2 = getvar(wrfin, "T2", timeidx=t)

                    line = interpline(t2,
                                      wrfin=wrfin,
                                      timeidx=t,
                                      start_point=start_point,
                                      end_point=end_point,
                                      latlon=True)

                    refname = "t2_line_t{}".format(t)
                    refline = refnc.variables[refname][:]

                    try:
                        nt.assert_allclose(to_np(line),
                                           to_np(refline),
                                           atol=.0001)
                    except AssertionError:
                        absdiff = np.abs(to_np(line) - refline)
                        maxdiff = np.amax(absdiff)
                        print(maxdiff)
                        print(np.argwhere(absdiff == maxdiff))
                        raise

                refnc.close()

            # Test NCLs single time case
            if not multi:
                refnc = NetCDF(referent)
                ref_t2_line4 = refnc.variables["t2_line4"][:]

                t2 = getvar(wrfin, "T2", timeidx=0)
                line = interpline(t2,
                                  wrfin=wrfin,
                                  timeidx=0,
                                  start_point=start_point,
                                  end_point=end_point,
                                  latlon=True)

                try:
                    nt.assert_allclose(to_np(line),
                                       to_np(ref_t2_line4),
                                       atol=.0001)
                except AssertionError:
                    absdiff = np.abs(to_np(line) - ref_t2_line4)
                    maxdiff = np.amax(absdiff)
                    print(maxdiff)
                    print(np.argwhere(absdiff == maxdiff))
                    raise
                finally:
                    refnc.close()

        elif (varname == "vinterp"):
            # Tk to theta
            fld_tk_theta = _get_refvals(referent, "fld_tk_theta", multi)
            fld_tk_theta = np.squeeze(fld_tk_theta)

            tk = getvar(wrfin, "temp", timeidx=timeidx, units="k")

            interp_levels = [200, 300, 500, 1000]

            # Make sure the numpy version works
            field = vinterp(wrfin,
                            field=to_np(tk),
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = vinterp(wrfin,
                            field=tk,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 0 / 100.
            atol = 0.0001

            field = np.squeeze(field)

            try:
                nt.assert_allclose(to_np(field), fld_tk_theta)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_tk_theta)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Tk to theta-e
            fld_tk_theta_e = _get_refvals(referent, "fld_tk_theta_e", multi)
            fld_tk_theta_e = np.squeeze(fld_tk_theta_e)

            interp_levels = [200, 300, 500, 1000]

            field = vinterp(wrfin,
                            field=tk,
                            vert_coord="theta-e",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            try:
                nt.assert_allclose(to_np(field), fld_tk_theta_e, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_tk_theta_e)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Tk to pressure
            fld_tk_pres = _get_refvals(referent, "fld_tk_pres", multi)
            fld_tk_pres = np.squeeze(fld_tk_pres)

            interp_levels = [850, 500]

            field = vinterp(wrfin,
                            field=tk,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            try:
                nt.assert_allclose(to_np(field), fld_tk_pres, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_tk_pres)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Tk to geoht_msl
            fld_tk_ght_msl = _get_refvals(referent, "fld_tk_ght_msl", multi)
            fld_tk_ght_msl = np.squeeze(fld_tk_ght_msl)
            interp_levels = [1, 2]

            field = vinterp(wrfin,
                            field=tk,
                            vert_coord="ght_msl",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            try:
                nt.assert_allclose(to_np(field), fld_tk_ght_msl, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_tk_ght_msl)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Tk to geoht_agl
            fld_tk_ght_agl = _get_refvals(referent, "fld_tk_ght_agl", multi)
            fld_tk_ght_agl = np.squeeze(fld_tk_ght_agl)
            interp_levels = [1, 2]

            field = vinterp(wrfin,
                            field=tk,
                            vert_coord="ght_agl",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            try:
                nt.assert_allclose(to_np(field), fld_tk_ght_agl, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_tk_ght_agl)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Hgt to pressure
            fld_ht_pres = _get_refvals(referent, "fld_ht_pres", multi)
            fld_ht_pres = np.squeeze(fld_ht_pres)

            z = getvar(wrfin, "height", timeidx=timeidx, units="m")
            interp_levels = [500, 50]
            field = vinterp(wrfin,
                            field=z,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="ght",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            try:
                nt.assert_allclose(to_np(field), fld_ht_pres, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_ht_pres)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Pressure to theta
            fld_pres_theta = _get_refvals(referent, "fld_pres_theta", multi)
            fld_pres_theta = np.squeeze(fld_pres_theta)

            p = getvar(wrfin, "pressure", timeidx=timeidx)
            interp_levels = [200, 300, 500, 1000]
            field = vinterp(wrfin,
                            field=p,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="pressure",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            try:
                nt.assert_allclose(to_np(field), fld_pres_theta, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_pres_theta)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise

            # Theta-e to pres
            fld_thetae_pres = _get_refvals(referent, "fld_thetae_pres", multi)
            fld_thetae_pres = np.squeeze(fld_thetae_pres)

            eth = getvar(wrfin, "eth", timeidx=timeidx)
            interp_levels = [850, 500, 5]
            field = vinterp(wrfin,
                            field=eth,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="theta-e",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            try:
                nt.assert_allclose(to_np(field), fld_thetae_pres, atol=.0001)
            except AssertionError:
                absdiff = np.abs(to_np(field) - fld_thetae_pres)
                maxdiff = np.amax(absdiff)
                print(maxdiff)
                print(np.argwhere(absdiff == maxdiff))
                raise
Пример #10
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from matplotlib.colors import from_levels_and_colors
from cartopy import crs
from cartopy.feature import NaturalEarthFeature, COLORS
from netCDF4 import Dataset
from wrf import (getvar, to_np, get_cartopy, latlon_coords, vertcross,
                 cartopy_xlim, cartopy_ylim, interpline, CoordPair)

root_dir = '/data/mac/giyoung/MAC_WRFThompson/'
nc = Dataset(root_dir +
             '2_Nisg80_ThompsonDefault/wrfout_d01_2015-11-27_00:00:00')

# Define the cross section start and end points
start_point = CoordPair(lat=-77.0, lon=-25.0)
end_point = CoordPair(lat=-72.0, lon=-25.0)

# Get the WRF variables
ht = getvar(nc, "z", timeidx=-1)
ter = getvar(nc, "ter", timeidx=-1)
dbz = getvar(nc, "dbz", timeidx=-1)
max_dbz = getvar(nc, "mdbz", timeidx=-1)
Z = 10**(dbz / 10.)  # Use linear Z for interpolation

# Compute the vertical cross-section interpolation.  Also, include the
# lat/lon points along the cross-section in the metadata by setting latlon
# to True.
z_cross = vertcross(Z,
                    ht,
                    wrfin=nc,
Пример #11
0
from cartopy.feature import NaturalEarthFeature
from netCDF4 import Dataset

from wrf import to_np, getvar, CoordPair, vertcross

# Open the NetCDF file
root_dir = '/data/mac/giyoung/MAC_WRFThompson/'
nc = Dataset(root_dir +
             '2_Nisg80_ThompsonDefault/wrfout_d02_2015-11-27_00:00:00')

# Extract the model height and wind speed
z = getvar(nc, "z")
wspd = getvar(nc, "uvmet_wspd_wdir", units="kt")[0, :]

# Create the start point and end point for the cross section
start_point = CoordPair(lat=-74.0, lon=-27.0)
end_point = CoordPair(lat=-75.0, lon=-27.0)

# Compute the vertical cross-section interpolation.  Also, include the
# lat/lon points along the cross-section.
wspd_cross = vertcross(wspd,
                       z,
                       wrfin=nc,
                       start_point=start_point,
                       end_point=end_point,
                       latlon=True,
                       meta=True)

# Create the figure
fig = plt.figure(figsize=(7, 6.5))
ax = plt.axes()
Пример #12
0
    # Necessary check because if non-WRF files are present in the directory, it will try to plot them and break
    if fnmatch.fnmatch(wrffile, '*[d]*'):
        print "Evaluating file " + wrffile
        ncfile = Dataset(wrffile)

        # Get the WRF variables
        slp = getvar(ncfile, "slp")
        smooth_slp = smooth2d(slp, 3)
        ctt = getvar(ncfile, "ctt")
        z = getvar(ncfile, "z")
        dbz = getvar(ncfile, "dbz")
        Z = 10**(dbz / 10.)
        wspd = getvar(ncfile, "wspd_wdir", units="m/s")[0, :]

        # Set the start point and end point for the cross section
        start_point = CoordPair(lat=36.3134, lon=-82.3535)
        end_point = CoordPair(lat=35.9132, lon=-79.0558)

        # Compute the vertical cross-section interpolation.  Also, include the lat/lon
        # points along the cross-section in the metadata by setting latlon to True.
        z_cross = vertcross(Z,
                            z,
                            wrfin=ncfile,
                            start_point=start_point,
                            end_point=end_point,
                            latlon=True,
                            meta=True)
        wspd_cross = vertcross(wspd,
                               z,
                               wrfin=ncfile,
                               start_point=start_point,
Пример #13
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from netCDF4 import Dataset

from wrf import to_np, getvar, CoordPair, vertcross

# Open the NetCDF file
ncfile = Dataset("H:/Output_scenarios/2100/ref/wrfout_d03_2099-07-23_13_00_00.nc")

# Extract the model height and wind speed
z = getvar(ncfile, "z")[0:9]
wspd =  getvar(ncfile, "uvmet_wspd_wdir")[0:9]

# Create the start point and end point for the cross section
start_point = CoordPair(lat=39, lon=-78.5)
end_point = CoordPair(lat=39, lon=-75.7)

# Compute the vertical cross-section interpolation.  Also, include the
# lat/lon points along the cross-section.
wspd_cross = vertcross(wspd, z, wrfin=ncfile, start_point=start_point,
                       end_point=end_point, latlon=True, meta=True)

# Create the figure
fig = plt.figure(figsize=(12,6))
ax = plt.axes()

# Make the contour plot
wspd_contours = ax.contourf(to_np(wspd_cross), cmap=get_cmap("jet"))

# Add the color bar
def cross_section(variable_name,
                  date,
                  time,
                  start_lat,
                  start_lon,
                  end_lat,
                  end_lon,
                  save=False):
    '''This function plots a vertical cross section of the chosen 
    variable. Supported variables for plotting procedure are 
    vertical_velocity, rh, omega, absolute_vorticity, theta_e and
    reflectivity.'''

    ### Predefine some variables ###
    # Define data filename
    data_dir = '/scratch3/thomasl/work/data/casestudy_baden/'
    filename = '{}wrfout_d02_{}_{}:00'.format(data_dir, date, time)

    # Define save directory
    save_dir = '/scratch3/thomasl/work/retrospective_part/' 'casestudy_baden/cross_section/'

    # Create the start point and end point for the cross section
    start_point = CoordPair(lat=start_lat, lon=start_lon)
    end_point = CoordPair(lat=end_lat, lon=end_lon)

    ### Start plotting procedure ###
    # Open NetCDF file
    ncfile = Dataset(filename)

    # Extract the model height, terrain height and variables
    ht = getvar(ncfile, 'z') / 1000  # change to km
    ter = getvar(ncfile, 'ter') / 1000

    if variable_name == 'vertical_velocity':
        variable = getvar(ncfile, 'wa', units='kt')
        title_name = 'Vertical Velocity'
        colorbar_label = 'Vertical Velocity [$kn$]'
        variable_min = -2
        variable_max = 2

    elif variable_name == 'rh':
        variable = getvar(ncfile, 'rh')
        title_name = 'Relative Humidity'
        colorbar_label = 'Relative Humidity [$pct$]'
        variable_min = 0
        variable_max = 100

    elif variable_name == 'omega':
        variable = getvar(ncfile, 'omega')
        title_name = 'Vertical Motion (Omega)'
        colorbar_label = 'Omega [$Pa$ $s^-$$^1$]'
        variable_min = -5
        variable_max = 5

    elif variable_name == 'absolute_vorticity':
        variable = getvar(ncfile, 'avo')
        title_name = 'Absolute Vorticity'
        colorbar_label = 'Absolute Vorticity [$10^{-5}$' '$s^{-1}$]'
        variable_min = -50
        variable_max = 100

    elif variable_name == 'theta_e':
        variable = getvar(ncfile, 'theta_e')
        title_name = 'Theta-E'
        colorbar_label = 'Theta-E [$K$]'
        variable_min = 315
        variable_max = 335

    elif variable_name == 'reflectivity':
        variable = getvar(ncfile, 'dbz')  #, timeidx=-1
        title_name = 'Reflectivity'
        colorbar_label = 'Reflectivity [$dBZ$]'
        variable_min = 5
        variable_max = 75

    # Linear Z for interpolation
    Z = 10**(variable / 10)

    # Compute the vertical cross-section interpolation
    z_cross = vertcross(Z,
                        ht,
                        wrfin=ncfile,
                        start_point=start_point,
                        end_point=end_point,
                        latlon=True,
                        meta=True)

    # Convert back after interpolation
    variable_cross = 10.0 * np.log10(z_cross)

    # Make a copy of the z cross data
    variable_cross_filled = np.ma.copy(to_np(variable_cross))

    # For each cross section column, find the first index with
    # non-missing values and copy these to the missing elements below
    for i in range(variable_cross_filled.shape[-1]):
        column_vals = variable_cross_filled[:, i]
        first_idx = int(np.transpose((column_vals > -200).nonzero())[0])
        variable_cross_filled[0:first_idx,
                              i] = variable_cross_filled[first_idx, i]

    ter_line = interpline(ter,
                          wrfin=ncfile,
                          start_point=start_point,
                          end_point=end_point)

    # Get latitude and longitude points
    lats, lons = latlon_coords(variable)

    # Create the figure
    fig = plt.figure(figsize=(15, 10))
    ax = plt.axes()

    ys = to_np(variable_cross.coords['vertical'])
    xs = np.arange(0, variable_cross.shape[-1], 1)

    # Make contour plot
    if variable_name == 'reflectivity':
        levels = np.arange(variable_min, variable_max, 5)

        # Create the dbz color table found on NWS pages.
        dbz_rgb = np.array(
            [[4, 233, 231], [1, 159, 244], [3, 0, 244], [2, 253, 2],
             [1, 197, 1], [0, 142, 0], [253, 248, 2], [229, 188, 0],
             [253, 149, 0], [253, 0, 0], [212, 0, 0], [188, 0, 0],
             [248, 0, 253], [152, 84, 198]], np.float32) / 255.0

        dbz_cmap, dbz_norm = from_levels_and_colors(levels,
                                                    dbz_rgb,
                                                    extend='max')

    else:
        levels = np.linspace(variable_min, variable_max, 11)

    if variable_name == 'omega' or variable_name == 'vertical_velocity':

        def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
            new_cmap = colors.LinearSegmentedColormap.from_list(
                'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name,
                                                    a=minval,
                                                    b=maxval),
                cmap(np.linspace(minval, maxval, n)))
            return new_cmap

        old_cmap = plt.get_cmap('RdYlBu')
        cmap = truncate_colormap(old_cmap, 0.05, 0.9)

        norm = colors.DivergingNorm(vmin=variable_min,
                                    vcenter=0,
                                    vmax=variable_max)

    else:
        cmap = ListedColormap(sns.cubehelix_palette(20, start=.5, rot=-.75))

    if variable_name == 'omega' or variable_name == 'vertical_velocity':
        variable_contours = ax.contourf(xs,
                                        ys,
                                        to_np(variable_cross_filled),
                                        levels=levels,
                                        cmap=cmap,
                                        extend='both',
                                        norm=norm)

    elif variable_name == 'rh':
        variable_contours = ax.contourf(xs,
                                        ys,
                                        to_np(variable_cross_filled),
                                        levels=levels,
                                        cmap=cmap,
                                        extend='max')
    elif variable_name == 'reflectivity':
        variable_contours = ax.contourf(xs,
                                        ys,
                                        to_np(variable_cross_filled),
                                        levels=levels,
                                        cmap=dbz_cmap,
                                        norm=dbz_norm,
                                        extend='both')

    else:
        variable_contours = ax.contourf(xs,
                                        ys,
                                        to_np(variable_cross_filled),
                                        levels=levels,
                                        cmap=cmap,
                                        extend='both')
    # Plot wind barbs
    if variable_name == 'vertical_velocity':
        u = getvar(ncfile, 'ua', units='kt')

        U = 10**(u / 10)

        u_cross = vertcross(U,
                            ht,
                            wrfin=ncfile,
                            start_point=start_point,
                            end_point=end_point,
                            latlon=True,
                            meta=True)

        u_cross = 10.0 * np.log10(u_cross)

        u_cross_filled = np.ma.copy(to_np(u_cross))

        for i in range(u_cross_filled.shape[-1]):
            column_vals = u_cross_filled[:, i]
            first_idx = int(np.transpose((column_vals > -200).nonzero())[0])
            u_cross_filled[0:first_idx, i] = u_cross_filled[first_idx, i]

        ax.barbs(xs[::3],
                 ys[::3],
                 to_np(u_cross_filled[::3, ::3]),
                 to_np(variable_cross_filled[::3, ::3]),
                 length=7,
                 zorder=1)

    if variable_name == 'omega':
        u = getvar(ncfile, 'ua', units='kt')

        U = 10**(u / 10)

        u_cross = vertcross(U,
                            ht,
                            wrfin=ncfile,
                            start_point=start_point,
                            end_point=end_point,
                            latlon=True,
                            meta=True)

        u_cross = 10.0 * np.log10(u_cross)

        u_cross_filled = np.ma.copy(to_np(u_cross))

        for i in range(u_cross_filled.shape[-1]):
            column_vals = u_cross_filled[:, i]
            first_idx = int(np.transpose((column_vals > -200).nonzero())[0])
            u_cross_filled[0:first_idx, i] = u_cross_filled[first_idx, i]

        w = getvar(ncfile, 'wa', units='kt')

        W = 10**(w / 10)

        w_cross = vertcross(W,
                            ht,
                            wrfin=ncfile,
                            start_point=start_point,
                            end_point=end_point,
                            latlon=True,
                            meta=True)

        w_cross = 10.0 * np.log10(w_cross)

        w_cross_filled = np.ma.copy(to_np(w_cross))

        for i in range(w_cross_filled.shape[-1]):
            column_vals = w_cross_filled[:, i]
            first_idx = int(np.transpose((column_vals > -200).nonzero())[0])
            w_cross_filled[0:first_idx, i] = w_cross_filled[first_idx, i]

        ax.barbs(xs[::3],
                 ys[::3],
                 to_np(u_cross_filled[::3, ::3]),
                 to_np(w_cross_filled[::3, ::3]),
                 length=7,
                 zorder=1,
                 color='grey')

    # Add color bar
    cbar = mpu.colorbar(variable_contours,
                        ax,
                        orientation='vertical',
                        aspect=40,
                        shrink=.05,
                        pad=0.05)
    cbar.set_label(colorbar_label, fontsize=15)
    cbar.set_ticks(levels)

    # Set x-ticks to use latitude and longitude labels
    coord_pairs = to_np(variable_cross.coords['xy_loc'])
    x_ticks = np.arange(coord_pairs.shape[0])
    x_labels = [
        pair.latlon_str(fmt='{:.2f}, {:.2f}') for pair in to_np(coord_pairs)
    ]

    # Set desired number of x ticks below
    num_ticks = 5
    thin = int((len(x_ticks) / num_ticks) + .5)
    ax.set_xticks(x_ticks[::thin])
    ax.set_xticklabels(x_labels[::thin], rotation=45, fontsize=10)
    ax.set_xlim(x_ticks[0], x_ticks[-1])

    # Set y-ticks and limit the height
    ax.set_yticks(np.linspace(0, 12, 13))
    ax.set_ylim(0, 12)

    # Set x-axis and y-axis labels
    ax.set_xlabel('Latitude, Longitude', fontsize=12.5)
    ax.set_ylabel('Height [$km$]', fontsize=12.5)

    # Fill in mountian area
    ht_fill = ax.fill_between(xs,
                              0,
                              to_np(ter_line),
                              facecolor='saddlebrown',
                              zorder=2)

    # Make nicetime
    xr_file = xr.open_dataset(filename)
    nicetime = pd.to_datetime(xr_file.QVAPOR.isel(Time=0).XTIME.values)

    # Add title
    ax.set_title('Vertical Cross-Section of {}'.format(title_name),
                 fontsize=20,
                 loc='left')
    ax.set_title('Valid time: {} {}'.format(
        nicetime.strftime('%Y-%m-%d %H:%M'), 'UTC'),
                 fontsize=15,
                 loc='right')

    # Add grid for y axis
    ax.grid(axis='y', linestyle='--', color='grey')

    plt.show()

    ### Save figure ###
    if save == True:
        fig.savefig('{}cross_section_{}.png'.format(save_dir, variable_name),
                    bbox_inches='tight',
                    dpi=300)
def lagranto_plotting(traj_variable_name,
                      start_time,
                      end_time,
                      trajs_bunch_level='all',
                      subset=False,
                      save=False):
    '''This function plots the chosen variables for the trajectories 
    calculated with Lagranto. Supported variables for plotting procedure 
    are water_vapor, updraft and height.'''

    ### Predefine some variables ###
    traj_data_dir = '/scratch3/thomasl/work/retrospective_part/lagranto/' 'traj_baden_10000_every1000_area_1200.ll'

    save_dir = '/scratch3/thomasl/work/retrospective_part' '/casestudy_baden/lagranto/'

    start_locations = 'area'  # distinction between single and multiple
    # starting points of trajectories
    number_trajs_plot = 1

    # Location of Initiation
    lat = 47.25
    lon = 7.85
    initiation = CoordPair(lat, lon)

    # Change extent of plot
    subset_extent = [7, 9, 47, 48]

    # Variables for getting PBL height of WRF model data
    date = '2018-05-30'
    time = '16:10'
    wrf_filename = '/scratch3/thomasl/work/data/casestudy_baden/' 'wrfout_d02_{}_{}:00'.format(
        date, time)

    # Variables:
    if traj_variable_name == 'water_vapor':
        traj_variable_name = 'QVAPOR'
        title_name = 'Trajectories of Water Vapor'
        colorbar_label_trajs = 'Water Vapor Mixing Ratio [$g$ $kg^{-1}$]'
        save_name = 'trajectory_water_vapor_{}_{}'.format(start_time, end_time)
        traj_variable_min = 0
        traj_variable_max = 15

    elif traj_variable_name == 'updraft':
        traj_variable_name = 'W_UP_MAX'
        title_name = 'Trajectories of Updraft'
        colorbar_label_trajs = 'Max Z-Wind Updraft [$m$ $s^-$$^1$]'
        save_name = 'trajectory_updraft_{}_{}'.format(start_time, end_time)
        traj_variable_min = 0
        traj_variable_max = 10

    elif traj_variable_name == 'height':
        traj_variable_name = 'z'
        title_name = 'Height of Trajectories'
        colorbar_label_trajs = 'Height of Trajectories [$m$]'
        save_name = 'trajectory_height_{}_{}'.format(start_time, end_time)
        traj_variable_min = 0
        traj_variable_max = 10000

    ### Plotting procedure ###
    trajs = Tra()
    trajs.load_ascii(traj_data_dir)

    # Get PBL out of WRF model data
    ncfile = Dataset(wrf_filename)
    wrf_file = xr.open_dataset(wrf_filename)
    data = wrf_file.PBLH

    location = ll_to_xy(ncfile, lat, lon)
    data_point = data.sel(west_east=location[0], south_north=location[1])
    pbl = data_point.values

    # Separate trajectories in 3 vertical bunches
    # Trajectories of pbl (according to pbl height of WRF model data)
    trajspbl = []
    for t in trajs:
        if (t['z'][0] <= pbl):
            trajspbl.append(t)

    # Trajectories between pbl and 5000 m
    trajs5 = []
    for t in trajs:
        if (t['z'][0] > pbl and t['z'][0] < 5000):
            trajs5.append(t)

    # Trajectories between 5000 m and 10000 m
    trajs10 = []
    for t in trajs:
        if (t['z'][0] > 5000 and t['z'][0] <= 10000):
            trajs10.append(t)

    if trajs_bunch_level == 'pbl':
        trajs_bunch = trajspbl

    elif trajs_bunch_level == '5':
        trajs_bunch = trajs5

    elif trajs_bunch_level == '10':
        trajs_bunch = trajs10

    elif trajs_bunch_level == 'all':
        trajs_bunch = trajs

    # Get terrain height
    terrain_height = getvar(ncfile, 'HGT') / 1000  # change to km

    # Define cart projection
    lats, lons = latlon_coords(terrain_height)
    cart_proj = ccrs.LambertConformal(central_longitude=8.722206,
                                      central_latitude=46.73585)

    # Create figure
    fig = plt.figure(figsize=(15, 10))
    ax = plt.axes(projection=cart_proj)

    ### Set map extent ###
    domain_extent = [3.701088, 13.814863, 43.85472, 49.49499]

    if subset == True:
        ax.set_extent([
            subset_extent[0], subset_extent[1], subset_extent[2],
            subset_extent[3]
        ], ccrs.PlateCarree())

    else:
        ax.set_extent([
            domain_extent[0] + 0.7, domain_extent[1] - 0.7,
            domain_extent[2] + 0.1, domain_extent[3] - 0.1
        ], ccrs.PlateCarree())

    # Plot trajectories
    levels_trajs = np.linspace(traj_variable_min, traj_variable_max, 11)
    rounded_levels_trajs = [round(elem, 1) for elem in levels_trajs]

    cmap = ListedColormap(sns.cubehelix_palette(
        10,
        start=.5,
        rot=-.75,
    ))

    plt_trajs = plot_trajs(ax,
                           trajs_bunch[0::number_trajs_plot],
                           traj_variable_name,
                           linewidth=2,
                           levels=rounded_levels_trajs,
                           cmap=cmap)

    # Plot the terrain height with colorbar
    levels = np.linspace(0, 4, 21)
    terrain = plt.contourf(to_np(lons),
                           to_np(lats),
                           to_np(terrain_height),
                           levels=levels,
                           transform=ccrs.PlateCarree(),
                           cmap=get_cmap('Greys'),
                           alpha=0.75)

    cbar = mpu.colorbar(terrain,
                        ax,
                        orientation='horizontal',
                        aspect=40,
                        shrink=.05,
                        pad=0.075)
    cbar.set_label('Terrain Height [$km$]', fontsize=15)
    cbar.set_ticks(levels)

    # Make only every second color bar tick label visible
    for label in cbar.ax.xaxis.get_ticklabels()[1::2]:
        label.set_visible(False)

    # Add color bar for trajectory variable
    if traj_variable_name == 'QVAPOR':
        extend = 'both'
    else:
        extend = 'max'
    cbar_trajs = mpu.colorbar(plt_trajs,
                              ax,
                              orientation='vertical',
                              aspect=40,
                              shrink=.05,
                              pad=0.05,
                              extend=extend)
    cbar_trajs.set_label(colorbar_label_trajs, fontsize=15)
    cbar_trajs.set_ticks(rounded_levels_trajs)

    # Add borders and coastlines
    ax.add_feature(cfeature.BORDERS.with_scale('10m'), linewidth=0.8)
    ax.add_feature(cfeature.COASTLINE.with_scale('10m'), linewidth=0.8)

    # Add cross for initiation location
    for t in trajs:
        ax.plot(t['lon'][0], t['lat'][0], 'kx', transform=ccrs.PlateCarree())

    # Add gridlines
    lon = np.arange(0, 20, 1)
    lat = np.arange(40, 60, 1)

    gl = ax.gridlines(xlocs=lon, ylocs=lat, zorder=3)

    # Add tick labels
    mpu.yticklabels(lat, ax=ax, fontsize=12.5)
    mpu.xticklabels(lon, ax=ax, fontsize=12.5)

    # Set title
    ax.set_title(title_name, loc='left', fontsize=20)
    ax.set_title('Time Range: {} - {} UTC'.format(start_time, end_time),
                 loc='right',
                 fontsize=15)

    plt.show()

    ### Save figure ###
    if save == True:
        if subset == True:
            if trajs_bunch_level == 'all':
                fig.savefig('{}{}_subset_{}.png'.format(
                    save_dir, save_name, start_locations),
                            bbox_inches='tight',
                            dpi=300)
            else:
                fig.savefig('{}{}_subset_{}_{}.png'.format(
                    save_dir, save_name, trajs_bunch_level, start_locations),
                            bbox_inches='tight',
                            dpi=300)

        else:
            if trajs_bunch_level == 'all':
                fig.savefig('{}{}_{}.png'.format(save_dir, save_name,
                                                 start_locations),
                            bbox_inches='tight',
                            dpi=300)
            else:
                fig.savefig('{}{}_{}_{}.png'.format(save_dir, save_name,
                                                    trajs_bunch_level,
                                                    start_locations),
                            bbox_inches='tight',
                            dpi=300)
Пример #16
0
ncfile = nc.Dataset('D:\\wrf_simulation\\final\\wrfout_d03_2016-07-21_12')

time = 126
ua = getvar(ncfile, 'ua', timeidx=time)
va = getvar(ncfile, 'va', timeidx=time)
wa = getvar(ncfile, 'wa', timeidx=time)
wa = wa * 10
p = getvar(ncfile, 'pressure', timeidx=time)
lat = getvar(ncfile, 'lat')
lon = getvar(ncfile, 'lon')
height = getvar(ncfile, 'height')
hgt = getvar(ncfile, 'HGT')
height2earth = height - hgt
start_lat, start_lon = 31.2, 121.0
end_lat, end_lon = 31.2, 122.0
startpoint = CoordPair(lat=start_lat, lon=start_lon)
endpoint = CoordPair(lat=end_lat, lon=end_lon)
ua_vert = vertcross(ua,
                    p,
                    wrfin=ncfile,
                    start_point=startpoint,
                    end_point=endpoint,
                    latlon=True)
va_vert = vertcross(va,
                    p,
                    wrfin=ncfile,
                    start_point=startpoint,
                    end_point=endpoint,
                    latlon=True)
wa_vert = vertcross(wa,
                    p,
Пример #17
0
import numpy as np
from matplotlib import pyplot
from matplotlib.cm import get_cmap
from matplotlib.colors import from_levels_and_colors
from cartopy import crs
from cartopy.feature import NaturalEarthFeature, COLORS
from netCDF4 import Dataset
from wrf import (getvar, to_np, ll_to_xy, get_cartopy, latlon_coords, vertcross,
                 cartopy_xlim, cartopy_ylim, interpline, CoordPair)

wrf_file = Dataset("wrfout_d04_2020-06-02_09:00:00")

# Define the cross section start and end points
cross_start = CoordPair(lat=66.983306, lon = -136.45)
cross_end   = CoordPair(lat=66.983306, lon = -135.7)
road1 = CoordPair(lat=66.983306, lon = -136.215596)
road2 = CoordPair(lat=66.983, lon = -136.21666666)
# Get the WRF variables
ht = getvar(wrf_file, "z", timeidx=-1)
ter = getvar(wrf_file, "ter", timeidx=-1)
wind = getvar(wrf_file, "wspd_wdir",timeidx=-1)[0,:]
theta = getvar(wrf_file, "th", timeidx=-1)


# Compute the vertical cross-section interpolation.  Also, include the
# lat/lon points along the cross-section in the metadata by setting latlon
# to True.
wind_cross = vertcross(wind, ht, wrfin=wrf_file,
                    start_point=cross_start,
                    end_point=cross_end,
                    latlon=True, meta=True)
Пример #18
0
tc = tc1 - tc2

#file1 = open("C:/Users/Yating/Desktop/output/output_gr100.txt","w")#write mode
#for i in range(tc.shape[0]):
#    for j in range(tc.shape[1]):
#        for k in range(tc.shape[2]):
#             if landmask[j,k]!=0 and landuse[j,k]>21 and landuse[j,k]<26:
#               file1.write(np.array2string(tc[i,j,k]))
#                 file1.write("\n")

#file1.close()

# Create the start point and end point for the cross section
#start_point = CoordPair(lat=39, lon=-78.5)
#end_point = CoordPair(lat=39, lon=-75.7)
start_point = CoordPair(lat=38.9, lon=-77.4)
end_point = CoordPair(lat=38.9, lon=-76.8)

# Compute the vertical cross-section interpolation.  Also, include the
# lat/lon points along the cross-section.
wspd_cross = vertcross(tc,
                       z,
                       wrfin=ncfile,
                       start_point=start_point,
                       end_point=end_point,
                       latlon=True,
                       meta=True)

# Create the figure
#fig = plt.figure(figsize=(7,4))
fig = plt.figure(figsize=(2, 4))
Пример #19
0
    def test(self):
        try:
            from netCDF4 import Dataset as NetCDF
        except:
            pass

        try:
            from PyNIO import Nio
        except:
            pass

        if not multi:
            timeidx = 0
            if not pynio:
                in_wrfnc = NetCDF(wrf_in)
            else:
                # Note: Python doesn't like it if you reassign an outer scoped
                # variable (wrf_in in this case)
                if not wrf_in.endswith(".nc"):
                    wrf_file = wrf_in + ".nc"
                else:
                    wrf_file = wrf_in
                in_wrfnc = Nio.open_file(wrf_file)
        else:
            timeidx = None
            if not pynio:
                nc = NetCDF(wrf_in)
                in_wrfnc = [nc for i in xrange(repeat)]
            else:
                if not wrf_in.endswith(".nc"):
                    wrf_file = wrf_in + ".nc"
                else:
                    wrf_file = wrf_in
                nc = Nio.open_file(wrf_file)
                in_wrfnc = [nc for i in xrange(repeat)]

        if (varname == "interplevel"):
            ref_ht_500 = _get_refvals(referent, "z_500", repeat, multi)
            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)
            hts_500 = interplevel(hts, p, 500)

            nt.assert_allclose(to_np(hts_500), ref_ht_500)

        elif (varname == "vertcross"):
            ref_ht_cross = _get_refvals(referent, "ht_cross", repeat, multi)
            ref_p_cross = _get_refvals(referent, "p_cross", repeat, multi)

            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)

            pivot_point = CoordPair(hts.shape[-1] / 2, hts.shape[-2] / 2)
            ht_cross = vertcross(hts, p, pivot_point=pivot_point, angle=90.)

            nt.assert_allclose(to_np(ht_cross), ref_ht_cross, rtol=.01)

            # Test opposite
            p_cross1 = vertcross(p, hts, pivot_point=pivot_point, angle=90.0)

            nt.assert_allclose(to_np(p_cross1), ref_p_cross, rtol=.01)
            # Test point to point
            start_point = CoordPair(0, hts.shape[-2] / 2)
            end_point = CoordPair(-1, hts.shape[-2] / 2)

            p_cross2 = vertcross(p,
                                 hts,
                                 start_point=start_point,
                                 end_point=end_point)

            nt.assert_allclose(to_np(p_cross1), to_np(p_cross2))

        elif (varname == "interpline"):

            ref_t2_line = _get_refvals(referent, "t2_line", repeat, multi)

            t2 = getvar(in_wrfnc, "T2", timeidx=timeidx)
            pivot_point = CoordPair(t2.shape[-1] / 2, t2.shape[-2] / 2)

            t2_line1 = interpline(t2, pivot_point=pivot_point, angle=90.0)

            nt.assert_allclose(to_np(t2_line1), ref_t2_line)

            # Test point to point
            start_point = CoordPair(0, t2.shape[-2] / 2)
            end_point = CoordPair(-1, t2.shape[-2] / 2)

            t2_line2 = interpline(t2,
                                  start_point=start_point,
                                  end_point=end_point)

            nt.assert_allclose(to_np(t2_line1), to_np(t2_line2))
        elif (varname == "vinterp"):
            # Tk to theta
            fld_tk_theta = _get_refvals(referent, "fld_tk_theta", repeat,
                                        multi)
            fld_tk_theta = np.squeeze(fld_tk_theta)

            tk = getvar(in_wrfnc, "temp", timeidx=timeidx, units="k")

            interp_levels = [200, 300, 500, 1000]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 5 / 100.
            atol = 0.0001

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_theta)))
            nt.assert_allclose(to_np(field), fld_tk_theta, tol, atol)

            # Tk to theta-e
            fld_tk_theta_e = _get_refvals(referent, "fld_tk_theta_e", repeat,
                                          multi)
            fld_tk_theta_e = np.squeeze(fld_tk_theta_e)

            interp_levels = [200, 300, 500, 1000]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="theta-e",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 3 / 100.
            atol = 50.0001

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_theta_e)/fld_tk_theta_e)*100)
            nt.assert_allclose(to_np(field), fld_tk_theta_e, tol, atol)

            # Tk to pressure
            fld_tk_pres = _get_refvals(referent, "fld_tk_pres", repeat, multi)
            fld_tk_pres = np.squeeze(fld_tk_pres)

            interp_levels = [850, 500]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)

            #print (np.amax(np.abs(to_np(field) - fld_tk_pres)))
            nt.assert_allclose(to_np(field), fld_tk_pres, tol, atol)

            # Tk to geoht_msl
            fld_tk_ght_msl = _get_refvals(referent, "fld_tk_ght_msl", repeat,
                                          multi)
            fld_tk_ght_msl = np.squeeze(fld_tk_ght_msl)
            interp_levels = [1, 2]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="ght_msl",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_ght_msl)))
            nt.assert_allclose(to_np(field), fld_tk_ght_msl, tol, atol)

            # Tk to geoht_agl
            fld_tk_ght_agl = _get_refvals(referent, "fld_tk_ght_agl", repeat,
                                          multi)
            fld_tk_ght_agl = np.squeeze(fld_tk_ght_agl)
            interp_levels = [1, 2]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="ght_agl",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_tk_ght_agl)))
            nt.assert_allclose(to_np(field), fld_tk_ght_agl, tol, atol)

            # Hgt to pressure
            fld_ht_pres = _get_refvals(referent, "fld_ht_pres", repeat, multi)
            fld_ht_pres = np.squeeze(fld_ht_pres)

            z = getvar(in_wrfnc, "height", timeidx=timeidx, units="m")
            interp_levels = [500, 50]
            field = vinterp(in_wrfnc,
                            field=z,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="ght",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_ht_pres)))
            nt.assert_allclose(to_np(field), fld_ht_pres, tol, atol)

            # Pressure to theta
            fld_pres_theta = _get_refvals(referent, "fld_pres_theta", repeat,
                                          multi)
            fld_pres_theta = np.squeeze(fld_pres_theta)

            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)
            interp_levels = [200, 300, 500, 1000]
            field = vinterp(in_wrfnc,
                            field=p,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="pressure",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_pres_theta)))
            nt.assert_allclose(to_np(field), fld_pres_theta, tol, atol)

            # Theta-e to pres
            fld_thetae_pres = _get_refvals(referent, "fld_thetae_pres", repeat,
                                           multi)
            fld_thetae_pres = np.squeeze(fld_thetae_pres)

            eth = getvar(in_wrfnc, "eth", timeidx=timeidx)
            interp_levels = [850, 500, 5]
            field = vinterp(in_wrfnc,
                            field=eth,
                            vert_coord="pressure",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="theta-e",
                            timeidx=timeidx,
                            log_p=True)

            field = np.squeeze(field)
            #print (np.amax(np.abs(to_np(field) - fld_thetae_pres)))
            nt.assert_allclose(to_np(field), fld_thetae_pres, tol, atol)
Пример #20
0
file3 = 'wrfout_d03_2012-04-22_23.nc'
mrg = ds[toinclude].to_netcdf(file3)

# Read in the data and extract variables
wrfin = Dataset(('wrfout_d03_2012-04-22_23.nc'))

z = getvar(wrfin, "z")
qv = getvar(wrfin, "QVAPOR")
# Pull lat/lon coords from QVAPOR data using wrf-python tools
lats, lons = latlon_coords(qv)

###############################################################################
# Create vertical cross section using wrf-python tools

# Define start and stop coordinates for cross section
start_point = CoordPair(lat=38, lon=-118)
end_point = CoordPair(lat=40, lon=-115)

qv_cross = vertcross(qv,
                     z,
                     wrfin=wrfin,
                     start_point=start_point,
                     end_point=end_point,
                     latlon=True)

# Close 'wrfin' to prevent PermissionError if code is run more than once locally
wrfin.close()
# Remove created wrfout file from local directory
os.remove('wrfout_d03_2012-04-22_23.nc')

###############################################################################
Пример #21
0
end_i, end_j = find_ind_latlon2d(lat, end_lat, lon, end_lon)
print(start_i, start_j)
print(lat[start_i, start_j], lon[start_i, start_j])
print(end_i, end_j)
print(lat[end_i, end_j], lon[end_i, end_j])
start = (start_j, start_i)
end = (end_j, end_i)

## 2. Compute the vertical cross-section interpolation
xy = xy(PS, start_point=start, end_point=end)
rh_cross = interp2dxy(RH, xy, meta=False)
print(np.nanmin(rh_cross), np.nanmax(rh_cross))

## 3. Interpolate LAT-LON along the cross section and build LAT-LON pairs (to put them on the X-axis in the final plot)
lat_interp = interpline(lat,
                        start_point=CoordPair(x=start_j, y=start_i),
                        end_point=CoordPair(x=end_j, y=end_i),
                        latlon=True,
                        meta=False)
lon_interp = interpline(lon,
                        start_point=CoordPair(x=start_j, y=start_i),
                        end_point=CoordPair(x=end_j, y=end_i),
                        latlon=False,
                        meta=False)
latlon_pairs = np.dstack((lat_interp, lon_interp))
ps_interp = interpline(PS,
                       start_point=CoordPair(x=start_j, y=start_i),
                       end_point=CoordPair(x=end_j, y=end_i),
                       latlon=False,
                       meta=False)
Пример #22
0
plt.show()

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature
from netCDF4 import Dataset

from wrf import to_np, getvar, CoordPair, vertcross

z = getvar(ncfile, "z")
wspd = getvar(ncfile, "uvmet_wspd_wdir", units="kt")[0, :]

# Create the start point and end point for the cross section
start_point = CoordPair(lat=26.76, lon=-80.0)
end_point = CoordPair(lat=26.76, lon=-77.8)

# Compute the vertical cross-section interpolation.  Also, include the lat/lon
# points along the cross-section.
wspd_cross = vertcross(wspd,
                       z,
                       wrfin=ncfile,
                       start_point=start_point,
                       end_point=end_point,
                       latlon=True,
                       meta=True)

# Create the figure
fig = plt.figure(figsize=(12, 6))
ax = plt.axes()