Example #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)
Example #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")
Example #3
0
def cross_3d_vars(cross_line, d3_vars, ds, end_point, start_point, z, ncfile
                  )->xr.Dataset:
    ver_cross = xr.Dataset()
    for v in d3_vars:
        ver_cross[v] = wrf.vertcross(ds[v], ds[z], wrfin=ncfile, start_point=start_point,
                                     end_point=end_point, latlon=True, meta=True)
    ver_cross = ver_cross.rename(**{'cross_line_idx': cross_line})
    return ver_cross
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
Example #5
0
File: util.py Project: B4dWo1f/RUN
def cross_path(start, end):
    # start = 41.260096661378306, -3.6981749563104716
    # end = 40.78691893349439, -3.6903966736445306
    # cross_path(start,end)
    start = wrf.ll_to_xy(ncfile, start[0], start[1])
    end = wrf.ll_to_xy(ncfile, end[0], end[1])

    start_point = wrf.CoordPair(x=start[0], y=start[1])
    end_point = wrf.CoordPair(x=end[0], y=end[1])

    levels = np.linspace(900, 3000, 100)
    p_vert = wrf.vertcross(wspd,
                           heights,
                           start_point=start_point,
                           end_point=end_point,
                           levels=levels,
                           latlon=True)
    fig, ax = plt.subplots()
    dx = 0, p_vert.shape[1]
    ax.imshow(p_vert, origin='lower', extent=[*dx, 900, 3000])
    ax.set_aspect(1 / 100)
    ax.set_title('Wind speed')
    fig.tight_layout()
    plt.show()
Example #6
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
Example #7
0
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)
theta_cross = vertcross(theta, ht, wrfin=wrf_file,
		    start_point=cross_start,
		    end_point=cross_end,
		    latlon=True, meta=True)

# Add back the attributes that xarray dropped from the operations above
wind_cross.attrs.update(wind_cross.attrs)
wind_cross.attrs["description"] = "wind speed cross section"
wind_cross.attrs["units"] = "m s-1"

theta_cross.attrs.update(theta_cross.attrs)
theta_cross.attrs["description"] = "potential temperature cross section"
theta_cross.attrs["units"] = 'degC'
Example #8
0
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,
                    wrfin=ncfile,
                    start_point=startpoint,
                    end_point=endpoint,
                    latlon=True)
Example #9
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")
# Open the NetCDF file
filename = "/home/lnx/MODELS/WRF/3_testdata/Urbania/Tair_d03.nc"
ncfile = Dataset(filename)

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

# Create the start point and end point for the cross section
start_point = CoordPair(lat=48.19833, lon=16.36694)
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()

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

# Add the color bar
plt.colorbar(wspd_contours, ax=ax)

# Set the x-ticks to use latitude and longitude labels.
coord_pairs = to_np(wspd_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)]
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)
Example #12
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)
Example #13
0
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')

###############################################################################
# Plot the data

fig = plt.figure(figsize=(10, 8))
ax = plt.axes()

# Set the x-ticks to use latitude and longitude labels.
Example #14
0
#                 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))
ax = plt.axes()

# Make the contour plot
clevs = np.arange(-2.6, 2.8, 0.2)
wspd_contours = ax.contourf(to_np(wspd_cross), clevs, cmap=get_cmap("bwr"))
#wspd_contours = ax.contourf(to_np(wspd_cross), cmap=get_cmap("jet"))

# Add the color bar
Example #15
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,
                    start_point=start_point,
                    end_point=end_point,
                    latlon=True,
                    meta=True)

# Convert back to dBz after interpolation
dbz_cross = 10.0 * np.log10(z_cross)

# Add back the attributes that xarray dropped from the operations above
dbz_cross.attrs.update(z_cross.attrs)
dbz_cross.attrs["description"] = "radar reflectivity cross section"
dbz_cross.attrs["units"] = "dBZ"

# To remove the slight gap between the dbz contours and terrain due to the
# contouring of gridded data, a new vertical grid spacing, and model grid
# staggering, fill in the lower grid cells with the first non-missing value
# Extract the model height and wind speed
z_wrs    = getvar(ncfile_wrs, "z")
temp_wrs = getvar(ncfile_wrs, "tc", timeidx=timeidx)


z_wr    = getvar(ncfile_wr, "z")
temp_wr = getvar(ncfile_wr, "tc", timeidx=timeidx)


z_wrf    = getvar(ncfile_wrf, "z")
temp_wrf = getvar(ncfile_wrf, "tc", timeidx=timeidx)


# Compute the vertical cross-section interpolation.  Also, include the lat/lon
# points along the cross-section.
temp_cross_wrs = vertcross(temp_wrs, z_wrs, wrfin=ncfile_wrs, start_point=start_point, end_point=end_point,
                       latlon=True, meta=True,levels=levels)

temp_cross_wr = vertcross(temp_wr, z_wr, wrfin=ncfile_wr, start_point=start_point, end_point=end_point,
                       latlon=True, meta=True,levels=levels)

temp_cross_wrf = vertcross(temp_wrf, z_wrf, wrfin=ncfile_wrf, start_point=start_point, end_point=end_point,
                       latlon=True, meta=True,levels=levels)

# Differences
#temp_cross_wrf_wrs = temp_cross_wrf-temp_cross_wrs
#temp_cross_wrf_wr  = temp_cross_wrf-temp_cross_wr
temp_cross_wrs_wr  = temp_cross_wrf-temp_cross_wrs


# Create the figure
fig = plt1.figure(1,figsize=(12,6))
Example #17
0
if __name__ == '__main__':
    data_dir1 = '/home/zzhzhao/Model/wrfout/test-10'
    data_dir2 = '/home/zzhzhao/Model/wrfout/test-10-removelake'
    u1, v1, w1, qv1, h, ter, lats, lons, time, wrflist = load_wrfdata_windspeed(
        data_dir1)

    NamCo_ll = (30.75, 90.9)
    # NamCo_xy = w.ll_to_xy(wrflist, NamCo_ll[0], NamCo_ll[1])

    start_point = w.CoordPair(lat=NamCo_ll[0] + 0.5, lon=NamCo_ll[1] - 0.5)
    end_point = w.CoordPair(lat=NamCo_ll[0] - 0.5, lon=NamCo_ll[1] + 0.5)

    u1_cross = w.vertcross(u1,
                           h,
                           wrfin=wrflist,
                           start_point=start_point,
                           end_point=end_point,
                           latlon=True,
                           meta=True)
    v1_cross = w.vertcross(v1,
                           h,
                           wrfin=wrflist,
                           start_point=start_point,
                           end_point=end_point,
                           latlon=True,
                           meta=True)
    w1_cross = w.vertcross(w1,
                           h,
                           wrfin=wrflist,
                           start_point=start_point,
                           end_point=end_point,
Example #18
0
# Extract the model height and wind speed
z_wrs = getvar(ncfile_wrs, "z")
temp_wrs = getvar(ncfile_wrs, "tc", timeidx=timeidx)

z_wr = getvar(ncfile_wr, "z")
temp_wr = getvar(ncfile_wr, "tc", timeidx=timeidx)

z_wrf = getvar(ncfile_wrf, "z")
temp_wrf = getvar(ncfile_wrf, "tc", timeidx=timeidx)

# Compute the vertical cross-section interpolation.  Also, include the lat/lon
# points along the cross-section.
temp_cross_wrs = vertcross(temp_wrs,
                           z_wrs,
                           wrfin=ncfile_wrs,
                           start_point=start_point,
                           end_point=end_point,
                           latlon=True,
                           meta=True,
                           levels=levels)

temp_cross_wr = vertcross(temp_wr,
                          z_wr,
                          wrfin=ncfile_wr,
                          start_point=start_point,
                          end_point=end_point,
                          latlon=True,
                          meta=True,
                          levels=levels)

temp_cross_wrf = vertcross(temp_wrf,
                           z_wrf,
Example #19
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)
        cmap = 'seismic'
        # Se hace la interpolacion de la variable con el terreno
        var_cross = vertcross(var, ht, wrfin=wrf_file,
                            start_point=cross_start,
                            end_point=cross_end,
                            latlon=True, meta=True)
        w_cross = vertcross(w, ht, wrfin=wrf_file,
                            start_point=cross_start,
                            end_point=cross_end,
                            latlon=True, meta=True)
        # Para agregar los atributos a la variable (opcional) 
        var_cross.attrs.update(var_cross.attrs)
        w_cross.attrs.update(w_cross.attrs)
        
        # Se hace un interpolado entre los valores 
        # proximos a la topografia y los NaN para que
        # quede mas lindo el grafico.
        var_cross_filled = np.ma.copy(to_np(var_cross))
        w_cross_filled = np.ma.copy(to_np(w_cross))
        
Example #20
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)