コード例 #1
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")
コード例 #2
0
ファイル: fft_process.py プロジェクト: jzanetti/var_blending
    def _smooth_model_error_over_frequencies(lam_err,
                                             glb_err,
                                             total_model_levels,
                                             smooth_number=3):
        """smoothing error matrix over frequencies"""
        for lvl in range(0, total_model_levels):
            lam_err[lvl, :, :] = smooth2d(deepcopy(lam_err[lvl, :, :]),
                                          smooth_number)
            glb_err[lvl, :, :] = smooth2d(deepcopy(glb_err[lvl, :, :]),
                                          smooth_number)

        return lam_err, glb_err
コード例 #3
0
def smooth_and_plot(var, passes, interp=False, height=False, doplot=True):

    X = getdata(var, interp=interp, height=height)

    yvals = getdata('lat')
    xvals = getdata('lon')

    print("Smoothing...")
    Xsmooth = wrf.smooth2d(X, passes)
    print("done")
    X = wrf.to_np(X)
    Xsmooth = wrf.to_np(Xsmooth)
    dX = X - Xsmooth

    yvals = wrf.to_np(yvals)
    xvals = wrf.to_np(xvals)

    nanwarning(X)
    nanwarning(Xsmooth)

    plottitle = str(passes) + "times smoothed " + var
    plotname = "Smooth" + str(passes) + "_" + var

    if not (interp == False):
        plottitle = plottitle + " at height " + str(height) + "km"
        plotname = plotname + "_height_" + str(height)

    if doplot:
        plotsmooth(X, Xsmooth, yvals, xvals, plottitle, plotname)

    return X, Xsmooth, dX, yvals, xvals
コード例 #4
0
def readdiag(nvar):
	var = getvar(ncfile, nvar)
	smooth_var = smooth2d(var, 3)
	lats, lons = latlon_coords(smooth_var)
	lons = to_np(lons)
	lats = to_np(lats)
	cart_proj = get_cartopy(var)
	return lons,lats
コード例 #5
0
    def set_smoothness(self, passes, update=True):
        """
        passes (int) :: number of times to apply smoothing to field.

        """
        if passes == None:
            passes = 1000

        filename = datapath + 'smooth_files_' + self.whichdata + '/' + self.str_id + "_" + str(
            passes)

        if self.derived:
            self.U.set_smoothness(passes, update=False)
            self.V.set_smoothness(passes, update=False)
            self.Xsmooth = switch[self.str_id](self.U.Xsmooth, self.V.Xsmooth)
        else:
            try:
                f = open(filename + '.npy')
                f.close()
            except:
                print("Smoothing " + self.str_id + " " + str(passes) +
                      " times...")
                self.Xsmooth = wrf.smooth2d(self.X, passes)
                print("Done.")
                np.save(filename, self.Xsmooth)
            else:
                print("Reading data from " + filename)
                Xsmooth = np.load(filename + '.npy')
                self.Xsmooth = wrf.smooth2d(self.X, 1)
                self.Xsmooth[:, ] = Xsmooth

        self.passes = passes

        self.dXall = self.X - self.Xsmooth
        self.turb_ratio = self.dXall / self.Xsmooth

        if update:
            self.update(1)

        return
コード例 #6
0
def compute_PSL(filename, inputinf=None):
    """ Function to calculate PSL using wrf-python diagnostics
        It also provides variable attribute CF-Standard
        Note: this function was also coded manually for in compute_vars.py
    """

    ncfile = nc.Dataset(filename, 'r')

    # Get the sea level pressure using wrf-python
    psl = wrf.getvar(ncfile, "slp", wrf.ALL_TIMES)

    # Smooth the sea level pressure since it tends to be noisy near the mountains
    smooth_psl = wrf.smooth2d(psl, 3)

    atts = {
        "standard_name": "air_pressure_at_mean_sea_level",
        "long_name": "Sea Level Pressure",
        "units": "Pa",
    }

    ncfile.close()
    return smooth_psl, atts
コード例 #7
0
def pmdbz(wrf_file,times,m,save_dir,drawclb):
    for time in range(times.shape[0]):
        mdbz = getvar(wrf_file, "mdbz",timeidx=time)
        lats, lons = latlon_coords(mdbz)
        x, y = m(to_np(lons), to_np(lats))
        mdbz = to_np(mdbz)
        smooth_mdbz = smooth2d(mdbz, 3)
        smooth_mdbz = to_np(smooth_mdbz)

        mask = smooth_mdbz <= 0
        smooth_mdbz[mask] = np.nan

        bounds = np.arange(0,80,5)
        colors = ['#00FFFF','#009DFF','#0000FF','#0982AF','#00FF00',\
        '#08AF14','#FFD600','#FF9800','#FF0000','#DD001B','#BC0036',\
        '#79006D','#7933A0','#C3A3D4','#FFFFFF']

        im = m.contourf(x,y, smooth_mdbz,10,levels=bounds,colors=colors)

        if drawclb:
            cax = fig.add_axes([0.9, 0.1, 0.02, 0.78])
            clb = fig.colorbar(im,shrink=0.75,ticks=bounds,pad=0.05,cax=cax)
            clb.ax.tick_params(labelsize=15)
            clb.solids.set_edgecolor("face")
            for l in clb.ax.yaxis.get_ticklabels():
                l.set_family('Arial')
            clb.set_label('Reflectivity (dBZ)',fontsize=15)

        name = str(times[time])[:10] + '_' + str(times[time])[11:16] + 'UTC'
        plt.title(str(times[time])[11:13]+str(times[time])[14:16] + ' UTC WRF-Chem',{'size':28},x=0.02,y=0.91,loc='left',bbox=dict(facecolor=(1,1,1,0.5),edgecolor=(0,0,0,0)))
        plt.savefig(save_dir+name+'.png',bbox_inches = 'tight')
        
        # remove elements if times.shape[0] > 1
        if drawclb:
            cax.remove()
        for im in im.collections:
            im.remove()
コード例 #8
0
def modfields(passes):

    fnew = Dataset("wrfinput_d01_new.nc", 'r+')

    filenames = [datapath+f for f in os.listdir(datapath) \
                if f.startswith('wrfout_xhka')]

    f0 = Dataset(filenames[0])
    f2 = Dataset(filenames[-1])

    scalingdict = {
        'U': 0.75,
        'V': 0.75,
        'U10': 0.75,
        'V10': 0.75,
        'T': 0.5,
        'TH2': 1.0,
        'QVAPOR': 0.5,
    }

    for str_id in ['U', 'V', 'T', 'QVAPOR']:

        Xnew = fnew.variables[str_id][0]

        X0 = wrf.getvar(f0, str_id, meta=False)
        X2 = wrf.getvar(f2, str_id, meta=False)

        filename = "../data/" + str_id + "_final_time_" + str(passes)
        try:
            f = open(filename + '.npy')
            f.close()
        except:
            print("Smoothing " + str_id + " " + str(passes) + " times...")
            Xsmooth = wrf.smooth2d(X2, passes)
            print("Done.")
            np.save(filename, Xsmooth)
        else:
            print("Reading data from " + filename)
            Xsmooth = np.load(filename + '.npy')
            print('done')

        dX = X2 - Xsmooth

        mu = scalingdict[str_id]

        print('calculating new field...')

        turb = dX / np.max(np.abs(Xsmooth))

        newfield = X0 * (1 + 2 * mu * turb)

        del turb

        Xnew[:, ] = 0

        Xnew[:, ] = newfield[:, ]

        del newfield

        print('done')

    fnew.close()

    return
コード例 #9
0
ファイル: functions.py プロジェクト: thenickdude/raspuri
def postprocessing(filename, outputdir, utch):
    # postprocessing(filename,outputdir,utch)
    # Function compute and save in outputdir all the variables named in
    # RASPURI/postprocessing/file_index in form of matrix ready to plot.
    # ---INPUTS:
    # filename="wrfout_d02_2020-01-11_15_00_00"#filename to get the data
    # outputdir='data/' #output directory
    # utch string utc time for filename
    # ---OUTPUTS:
    # matrix data on output dir

    #########################################################################
    ##################   OPEN FILE
    #########################################################################
    try:
        ncfile = Dataset(filename)
        #outputdir='aaaaa/'
    except Exception as e:
        print('****Error opening file postprocessing , functions.py****')
        print(e)
    #########################################################################
    ##################   GET VARS
    #########################################################################
    try:

        slp = getvar(ncfile, "slp")  # Sea Level Pressure

        z = getvar(ncfile, "z")  # Geopotential Height
        p = getvar(ncfile, "pressure")  # Pressure (hPa)
        t = getvar(ncfile, "tc")  # temperature in Celsius
        ua = getvar(ncfile, "ua")  # winds
        va = getvar(ncfile, "va")
        wa = getvar(ncfile, "wa")
        wspd_wdir = getvar(ncfile, "wspd_wdir")
        #uv10 = getvar(ncfile, "uvmet10")
        wspd_wdir10 = getvar(ncfile, "wspd_wdir10")
        cape_2d = getvar(ncfile, "cape_2d")
        cloudfrac = getvar(ncfile, "cloudfrac")  # clouds
        ctt = getvar(ncfile, "ctt")  # Cloud Top Temperature
        pw = getvar(ncfile, "pw")  # Precipitable water
        bldepth = getvar(ncfile, "PBLH")  #bl depth (metres)
        ter = getvar(ncfile, "HGT")  #Terrain Height (metres)
        qcloud = getvar(ncfile, "QCLOUD")  #"Cloud water mixing ratio"
        t2 = getvar(ncfile, "T2")  # TEMP at 2 M
        uv = getvar(ncfile, "uvmet")  # u,v NOT rotated to grid   in m/s
        p = getvar(ncfile, "P")  #"perturbation pressure"
        pb = getvar(ncfile, "PB")  #"BASE STATE PRESSURE"
        hfx = getvar(ncfile,
                     "HFX")  #for sfc. sensible heat flux in w/m2    142
        thetac = getvar(
            ncfile,
            "T") + 26.85  #"perturbation potential temperature theta-t0"
        qvapor = getvar(ncfile, "QVAPOR")  #"Water vapor mixing ratio"
        vhf = getvar(ncfile, "LH")  #"LATENT HEAT FLUX AT THE SURFACE"
        td = getvar(ncfile, "td")  #dew point temperature (C)
        td2 = getvar(ncfile, "td2")  #dew point temperature at 2 M (C)
        snow = getvar(ncfile, "SNOW")  #"SNOW WATER EQUIVALENT"
        rainc = getvar(ncfile,
                       "RAINC")  #"ACCUMULATED TOTAL CUMULUS PRECIPITATION"
        rainnc = getvar(
            ncfile, "RAINNC")  #"ACCUMULATED TOTAL GRID SCALE PRECIPITATION"
        snowh = getvar(ncfile, "SNOWH")  #"PHYSICAL SNOW DEPTH"

        pblh = bldepth
        #lats, lons = latlon_coords(slp)
        lats = getvar(ncfile, "XLAT")
        lons = getvar(ncfile, "XLONG")
        dx = slp.projection.dx
        dy = slp.projection.dy
    except Exception as e:
        print('****Error reading vars postprocessing , functions.py****')
        print(e)
    #########################################################################
    ##################   VARS TRANSFORMATIONS
    #########################################################################
    try:
        ###
        wspd_all = wspd_wdir[0, :]
        wdir_all = wspd_wdir[1, :]

        # Interpolate geopotential height, u, and v winds to 500 hPa ->5000m
        ht_500 = interplevel(z, p, 500.)
        wdir_500 = interplevel(wdir_all, p, 500)
        wspd_500 = interplevel(wspd_all, p, 500)
        t_500 = interplevel(t, p, 500)

        # Interpolate geopotential height, u, and v winds to 700 hPa ->3000m
        ht_700 = interplevel(z, p, 700.)
        wdir_700 = interplevel(wdir_all, p, 700)
        wspd_700 = interplevel(wspd_all, p, 700)
        t_700 = interplevel(t, p, 700)

        # Interpolate geopotential height, u, and v winds to 925 hPa ->762m
        ht_925 = interplevel(z, p, 925.)
        wdir_925 = interplevel(wdir_all, p, 925)
        wspd_925 = interplevel(wspd_all, p, 925)
        t_925 = interplevel(t, p, 925)

        # Clouds
        cloudfrac_low = cloudfrac[0, :, :]  #300m
        cloudfrac_mid = cloudfrac[1, :, :]  #2000m
        cloudfrac_high = cloudfrac[2, :, :]  #6000m

        # Surface
        smooth_slp = smooth2d(
            slp, 7, cenweight=3
        )  # Smooth the sea level pressure since it tends to be noisy near the mountains
        sfctemp = t2 - 273.16  #Surface temp
        hbl_mag = pblh.values + ter.values  #"Height of BL Top
        wspd10 = wspd_wdir10[0, :]  #Surface wind speed
        wdir10 = wspd_wdir10[1, :]  #Surface wind dir
        mcape = cape_2d[0, :, :]
        mcin = cape_2d[1, :, :]
        lcl = cape_2d[2, :, :]
        lfc = cape_2d[3, :, :]
        rainTot = rainc + rainnc

        # Aux dr jack
        uEW = uv[0, :, :]
        vNS = uv[1, :, :]
        pmb = var = 0.01 * (p.values + pb.values
                            )  # press is vertical coordinate in mb
        vhf = np.clip(vhf.values, a_min=0, a_max=np.max(vhf.values))
        vhf = hfx + 0.000245268 * (t[0, :, :] + 273.16) * vhf
    except Exception as e:
        print('****Error transforming vars postprocessing , functions.py****')
        print(e)
    #########################################################################
    ##################   SAVE
    #########################################################################
    try:
        np.save(outputdir + 'lons', (lons.values))
        np.save(outputdir + 'lats', (lats.values))
        np.save(outputdir + 'ter', (ter.values))
        np.save(outputdir + 'mcape' + utch, mcape.values)
        np.save(outputdir + 'mcin' + utch, mcin.values)
        np.save(outputdir + 'lcl' + utch, lcl.values)
        np.save(outputdir + 'lfc' + utch, lfc.values)
        np.save(outputdir + 'sfctemp' + utch, (sfctemp.values))
        np.save(outputdir + 'bldepth' + utch, (bldepth.values))
        np.save(outputdir + 'wspd10' + utch, (wspd10.values))
        np.save(outputdir + 'wdir10' + utch, (wdir10.values))
        np.save(outputdir + 'pw' + utch, (pw.values))
        np.save(outputdir + 'ctt' + utch, ctt.values)
        np.save(outputdir + 'hbl' + utch, hbl_mag)
        np.save(outputdir + 'cloudfrac_low' + utch, cloudfrac_low.values)
        np.save(outputdir + 'cloudfrac_mid' + utch, cloudfrac_mid.values)
        np.save(outputdir + 'cloudfrac_high' + utch, cloudfrac_high.values)
        np.save(outputdir + 'slp' + utch, (smooth_slp.values))
        np.save(outputdir + 'hfx' + utch, (hfx.values))
        np.save(outputdir + 'snow' + utch, (snow.values))
        np.save(outputdir + 'rainTot' + utch, (rainTot.values))
        np.save(outputdir + 'snowh' + utch, (snowh.values))
        np.save(outputdir + 'td2' + utch, td2.values)

        np.save(outputdir + 'ht_500' + utch, ht_500.values)
        np.save(outputdir + 'wdir_500' + utch, wdir_500.values)
        np.save(outputdir + 'wspd_500' + utch, wspd_500.values)
        np.save(outputdir + 't_500' + utch, t_500.values)

        np.save(outputdir + 'ht_700' + utch, ht_700.values)
        np.save(outputdir + 'wdir_700' + utch, wdir_700.values)
        np.save(outputdir + 'wspd_700' + utch, wspd_700.values)
        np.save(outputdir + 't_700' + utch, t_700.values)

        np.save(outputdir + 'ht_925' + utch, ht_925.values)
        np.save(outputdir + 'wdir_925' + utch, wdir_925.values)
        np.save(outputdir + 'wspd_925' + utch, wspd_925.values)
        np.save(outputdir + 't_925' + utch, t_925.values)
    except Exception as e:
        print('****Error saving vars postprocessing , functions.py****')
        print(e)
    #########################################################################
    ##################   DR jack transf
    #########################################################################
    try:
        # Variables
        size = (z.values).shape
        nz = size[0]
        ny = size[1]
        nx = size[2]
        # Transforms
        '''For NCL arrays, the fastest-varying dimension is the rightmost, while for Fortran it is the leftmost dimension. Therefore, if XA is a Fortran array dimensioned idim x jdim, this array will be dimensioned jdim x idim in NCL'''
        pblh = np.transpose(pblh.values)
        ter = np.transpose(ter.values)
        wa = np.transpose(wa.values)
        z = np.transpose(z.values)
        qcloud = np.transpose(qcloud.values)
        uEW = np.transpose(uEW.values)
        vNS = np.transpose(vNS.values)
        qvapor = np.transpose(qvapor.values)
        tc = np.transpose(t.values)
        pmb = np.transpose(pmb)
        vhf = np.transpose(vhf.values)
        td = np.transpose(td.values)
        thetac = np.transpose(thetac.values)
        ua = np.transpose(ua.values)
        va = np.transpose(va.values)
        # Other Constants
        time = 0  # Seems time is always 0 for DrJack's code
        cdbl = 0.003  # Coefficient of Drag for Boundary Layer
        cwbasecriteria = 0.000010  # Cloud Water criterion

        #"BL Max. Up/Down Motion"
        wblMxMn = ncl_jack_fortran.calc_wblmaxmin(0, wa, z, ter, pblh)
        #"BL Explicit Cloud Base [AGL]"
        laglcwbase = 1
        criteriondegc = 1.0
        maxcwbasem = 5486.40
        blcwbase = ncl_jack_fortran.calc_blcloudbase(qcloud, z, ter, pblh,
                                                     cwbasecriteria,
                                                     maxcwbasem, laglcwbase)
        #"BL Avg Wind"
        ublavgwind = ncl_jack_fortran.calc_blavg(uEW, z, ter, pblh)
        vblavgwind = ncl_jack_fortran.calc_blavg(vNS, z, ter, pblh)
        blavgwindspeed = np.sqrt(
            np.power(ublavgwind, 2) + np.power(vblavgwind, 2))
        #"Wind at BL Top"
        utop, vtop = ncl_jack_fortran.calc_bltopwind(uEW, vNS, z, ter, pblh)
        bltopwindspeed = np.sqrt(np.power(utop, 2) + np.power(vtop, 2))
        #"BL Cloud Cover"
        blcldpct = ncl_jack_fortran.calc_subgrid_blcloudpct_grads(
            qvapor, qcloud, tc, pmb, z, ter, pblh, cwbasecriteria)
        #"Thermal Updraft Velocity"
        wstar = ncl_jack_fortran.calc_wstar(vhf, pblh, 0)
        #"Height of Critical Updraft Strength"
        hwcrit = ncl_jack_fortran.calc_hcrit(wstar, ter, pblh)
        #"Cu Cloudbase ~I~where Cu Potential > 0~P~"
        zsfclcl = ncl_jack_fortran.calc_sfclclheight(pmb, tc, td, z, ter, pblh)
        #"OvercastDevelopment Cloudbase"
        qvaporblavg = ncl_jack_fortran.calc_blavg(qvapor, z, ter, pblh)
        zblcl = ncl_jack_fortran.calc_blclheight(pmb, tc, qvaporblavg, z, ter,
                                                 pblh)
        #"Thermalling Height"
        hglider_aux = np.minimum(hwcrit, zsfclcl)
        hglider = np.minimum(hglider_aux, zblcl)
        #"BL Top Uncertainty/Variability"
        bltopvariab = ncl_jack_fortran.calc_bltop_pottemp_variability(
            thetac, z, ter, pblh, criteriondegc)
        #"BL Vertical Wind Shear"
        blwindshear = ncl_jack_fortran.calc_blwinddiff(ua, va, z, ter, pblh)
    except Exception as e:
        print(
            '****Error computing dr jack vars postprocessing , functions.py****'
        )
        print(e)

    # Save
    try:
        np.save(outputdir + 'wblMxMn' + utch, np.transpose(wblMxMn))
        np.save(outputdir + 'blcwbase' + utch, np.transpose(blcwbase))
        np.save(outputdir + 'ublavgwind' + utch, np.transpose(ublavgwind))
        np.save(outputdir + 'vblavgwind' + utch, np.transpose(vblavgwind))
        np.save(outputdir + 'blavgwindspeed' + utch,
                np.transpose(blavgwindspeed))
        np.save(outputdir + 'utop' + utch, np.transpose(utop))
        np.save(outputdir + 'vtop' + utch, np.transpose(vtop))
        np.save(outputdir + 'bltopwindspeed' + utch,
                np.transpose(bltopwindspeed))
        np.save(outputdir + 'blcldpct' + utch, np.transpose(blcldpct))
        np.save(outputdir + 'wstar' + utch, np.transpose(wstar))
        np.save(outputdir + 'hwcrit' + utch, np.transpose(hwcrit))
        np.save(outputdir + 'zsfclcl' + utch, np.transpose(zsfclcl))
        np.save(outputdir + 'zblcl' + utch, np.transpose(zblcl))
        np.save(outputdir + 'hglider' + utch, np.transpose(hglider))
        np.save(outputdir + 'bltopvariab' + utch, np.transpose(bltopvariab))
        np.save(outputdir + 'blwindshear' + utch, np.transpose(blwindshear))
    except Exception as e:
        print(
            '****Error saving dr jacks vars postprocessing , functions.py****')
        print(e)
    return dx, dy
コード例 #10
0
u = getvar(files, 'ua', timeidx=params['time_index'], units="kt")
v = getvar(files, 'va', timeidx=params['time_index'], units="kt")

ter_3d=np.tile(ter.values,[41,1,1])
z.values=z.values-ter.values
u2 = interplevel(u, z, 1000)
v2 = interplevel(v, z, 1000)
uvmet = getvar(files, 'uvmet10', timeidx=params['time_index'], units='kt')
ufld = uvmet.isel(u_v=0)
vfld = uvmet.isel(u_v=1)

u2.values=u2.values-ufld.values
v2.values=v2.values-vfld.values

lfield = uvmet10.isel(wspd_wdir=0)
lfield.values=smooth2d(np.sqrt(u2.values**2.+v2.values**2.),3)

lfield2 = getvar(files, 'ter', timeidx=params['time_index'], units='m')

sounding_parameters=getvar(files, 'cape_2d', timeidx=params['time_index'])
cffield = sounding_parameters.isel(mcape_mcin_lcl_lfc=3)

cffield.attrs['description']='lcl, 0-1 km bulk wind difference'
cffield.attrs['units']='m; kt'
uvmet = getvar(files, 'uvmet10', timeidx=params['time_index'], units='kt')
ufld = u2
vfld = v2

make_plot(cffield,lfield,lfield2,ufld,vfld,params)

コード例 #11
0
from matplotlib.cm import get_cmap
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature

from wrf import ALL_TIMES, to_np, getvar, smooth2d, get_cartopy, cartopy_xlim, cartopy_ylim, latlon_coords

# Open the NetCDF file
ncfile = Dataset(
    "/Users/zhenkunli/Dropbox/share/results/wrfout_d01_2014-07-01_00:00:00")

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

# Smooth the sea level pressure since it tends to be noisy near the mountains
T2 = smooth2d(T2, 3)

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

# Get the cartopy mapping object
cart_proj = get_cartopy(T2)
print cart_proj

# Create a figure
fig = plt.figure(figsize=(8, 6))
# Set the GeoAxes to the projection used by WRF
ax = plt.axes(projection=cart_proj)

# Download and add the states and coastlines
states = NaturalEarthFeature(category='cultural',
コード例 #12
0
ファイル: lh_uvmet10_slp.py プロジェクト: uesleisutil/python
_modified_ = datetime(2017, 07, 20)
_version_  = "0.1"
_status_   = "Development"

# Open the NetCDF file.
ncfile = Dataset("/media/uesleisutil/Ueslei/INPE/2014/Outputs/wrf_I_t01.nc")

# Get the data.
slp     = getvar(ncfile, "slp", timeidx=78)
uvmet10 = getvar(ncfile, "uvmet10", units="km h-1", timeidx=78)
u10     = uvmet10[1,:,:]
v10     = uvmet10[0,:,:]
lh      = getvar(ncfile, "LH", timeidx=78)

# Smooth the sea level pressure since it tends to be noisy near the mountains.
smooth_slp = smooth2d(slp, 5)

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

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

# Create a figure.
fig = plt.figure(figsize=(12,9))

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

# Download and add the states and coastlines.
states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',name='admin_0_countries')
コード例 #13
0
if ncidp.horizontal == 1: horizontal = "2D"
else: horizontal = "3D"

for it in range(0, ntime):  # ntime

    print(ptime_convert[it], end='\r', flush=True)

    lons = data[it, :, 0]
    lats = data[it, :, 1]
    hgts = data[it, :, 2] / 1000

    itt = np.where(ztime_convert == ptime_convert[it])[0].tolist()
    if itt != []:
        z = ncidz.variables["z"][itt, level, :, :]
        smooth_z = smooth2d(z[0, :, :], 6, cenweight=4)
        del z

    fig = plt.figure(figsize=(6, 4), dpi=300)
    plt.rcParams.update({'font.size': 6})

    m.drawcoastlines(linewidth=0.1)
    m.drawparallels(np.arange(-90., 91., 5.), linestyle='--', linewidth=0.1)
    m.drawmeridians(np.arange(-180, 180., 5.), linestyle='--', linewidth=0.1)
    # m.drawparallels(np.arange(0,80,15),labels=[False,True,False,False])
    m.drawmeridians(np.arange(-180, 180., 5.), linestyle='--', linewidth=0.1)
    m.fillcontinents('tab:gray', alpha=0.7)

    titlestrL = "%s" % (ptime_convert[it])
    titlestrR = "%4.1f%%" % (
        (float(lons.count()) / float(lons.shape[0]) * 100.))
コード例 #14
0
from matplotlib.cm import get_cmap
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature

from wrf import ALL_TIMES, to_np, getvar, smooth2d, get_cartopy, cartopy_xlim, cartopy_ylim, latlon_coords

# Open the NetCDF file
ncfile = Dataset(
    "/Users/zhenkunli/Dropbox/share/results/wrfout_d01_2014-07-01_00:00:00")

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

# Smooth the sea level pressure since it tends to be noisy near the mountains
HFX = smooth2d(HFX, 3)

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

# Get the cartopy mapping object
cart_proj = get_cartopy(HFX)
print cart_proj

# Create a figure
fig = plt.figure(figsize=(8, 6))
# Set the GeoAxes to the projection used by WRF
ax = plt.axes(projection=cart_proj)

# Download and add the states and coastlines
states = NaturalEarthFeature(category='cultural',
コード例 #15
0
def plot_spatial_wrf_surf_press(file_path, case_name, timeidx):

    # Open the NetCDF file
    ncfile = Dataset(file_path)

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

    # print(slp)

    # Smooth the sea level pressure since it tends to be noisy near the
    # mountains
    smooth_slp = smooth2d(slp, 3, cenweight=4)

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

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

    # Create the figure
    fig = plt.figure(figsize=(12,6))
    fig.subplots_adjust(hspace=0.3)
    fig.subplots_adjust(wspace=0.2)

    plt.rcParams['text.usetex']     = False
    plt.rcParams['font.family']     = "sans-serif"
    plt.rcParams['font.serif']      = "Helvetica"
    plt.rcParams['axes.linewidth']  = 1.5
    plt.rcParams['axes.labelsize']  = 14
    plt.rcParams['font.size']       = 14
    plt.rcParams['legend.fontsize'] = 12
    plt.rcParams['xtick.labelsize'] = 12
    plt.rcParams['ytick.labelsize'] = 14

    almost_black = '#262626'
    # change the tick colors also to the almost black
    plt.rcParams['ytick.color']     = almost_black
    plt.rcParams['xtick.color']     = almost_black

    # change the text colors also to the almost black
    plt.rcParams['text.color']      = almost_black

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

    # Download and add the states and coastlines
    states = NaturalEarthFeature(category="cultural", scale="50m",
                                         facecolor="none",
                                         name="admin_1_states_provinces_shp")
    ax.add_feature(states, linewidth=.5, edgecolor="black")
    ax.coastlines('50m', linewidth=0.8)

    # Make the contour outlines and filled contours for the smoothed sea level
    # pressure.
    plt.contour(to_np(lons), to_np(lats), to_np(smooth_slp), 10, vmin=980, vmax=1020,  colors="black",
                        transform=crs.PlateCarree())
    plt.contourf(to_np(lons), to_np(lats), to_np(smooth_slp), 10, vmin=980, vmax=1020,
                         transform=crs.PlateCarree(), cmap=get_cmap("rainbow")) #"jet"

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

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

    # Add the gridlines
    ax.gridlines(color="black", linestyle="dotted")

    plt.title("Sea Level Pressure (hPa) of timestep-"+str(timeidx))

    fig.savefig("./plots/spatial_wrf_slp_"+case_name+"_"+str(timeidx), bbox_inches='tight', pad_inches=0.1)

    return ax
コード例 #16
0
    img_plot.yformatter = LATITUDE_FORMATTER
    return fig, ax


projection = ccrs.PlateCarree()
fig, ax = brazil()
states = NaturalEarthFeature(category='cultural',
                             scale='50m',
                             facecolor='none',
                             name='admin_1_states_provinces_shp',
                             linewidth=0.4)
states = ax.add_feature(states, edgecolor='black')

prnm = sgl['msl'][0][:][:]
prnm = prnm / 100
smooth_press = smooth2d(prnm, 10, cenweight=0.5)
t_850 = ps['t'][0][4][:][:] - 273.15

hgt_500 = ps['z'][0][0][:][:]
hgt_1000 = ps['z'][0][2][:][:]
thk = (hgt_500 - hgt_1000) / 10

plt.title(
    '{} \n PRNM (hPa), Temperatura em 850 hPa  e \n Espessura de Geopotencial (m)'
    .format(tempo),
    fontsize=14)

img_plot = plt.contourf(lons,
                        lats,
                        t_850,
                        transform=projection,
コード例 #17
0
from matplotlib.cm import get_cmap
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature

from wrf import to_np, getvar, smooth2d, get_cartopy, cartopy_xlim, cartopy_ylim, latlon_coords

# Open the NetCDF file
ncfile = Dataset(
    '/Users/sunt05/Documents/20180813WRF-SUEWS-London/wrfout_d03_2014-07-01_00:00:00'
)

# Get the sea level pressure
slp = getvar(ncfile, "T2", 10)

# Smooth the sea level pressure since it tends to be noisy near the mountains
smooth_slp = smooth2d(slp, 3)

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

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

# Create a figure
fig = plt.figure(figsize=(12, 9))
# Set the GeoAxes to the projection used by WRF
ax = plt.axes(projection=cart_proj)

# Download and add the states and coastlines
states = NaturalEarthFeature(category='cultural',
                             scale='50m',
コード例 #18
0
def makesmooth(str_id, passes):

    X = getdata(str_id)
    Xsmooth = wrf.smooth2d(X, passes)

    return Xsmooth
コード例 #19
0
def metpy_read_wrf(fwrf, fout, lons_out, lats_out):

    wrfin = Dataset(fwrf)
    ds = xr.Dataset()

    slp = getvar(wrfin, "slp", timeidx=ALL_TIMES)
    ds['slp'] = smooth2d(slp, 3, cenweight=4)

    lats, lons = latlon_coords(slp)
    ds['lats'] = lats
    ds['lons'] = lons

    rainc = []
    for tidx in range(len(ds.Time)):
        rainc0 = extract_vars(wrfin, timeidx=tidx,
                              varnames=["RAINNC"]).get("RAINNC")
        if tidx > 0:
            rainc0 -= extract_vars(wrfin,
                                   timeidx=tidx - 1,
                                   varnames=["RAINNC"]).get("RAINNC")
        rainc.append(smooth2d(rainc0, 3, cenweight=4))
    ds['rain'] = xr.DataArray(rainc, ds.slp.coords, ds.slp.dims, ds.slp.attrs)
    ds['latent'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                                varnames=["LH"]).get("LH")
    ds['u10'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                             varnames=["U10"]).get("U10")
    ds['v10'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                             varnames=["V10"]).get("V10")
    ds['t2m'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                             varnames=["T2"]).get("T2")
    ds['q2m'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                             varnames=["Q2"]).get("Q2")
    ds['sst'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                             varnames=["SST"]).get("SST")
    ds['td2'] = getvar(wrfin, "td2", timeidx=ALL_TIMES)
    ds['th2'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                             varnames=["TH2"]).get("TH2")
    ds['mask'] = extract_vars(wrfin, timeidx=ALL_TIMES,
                              varnames=["LANDMASK"]).get("LANDMASK")

    ds['p'] = getvar(wrfin, "pressure", timeidx=ALL_TIMES)
    ds['z'] = getvar(wrfin, "geopt", timeidx=ALL_TIMES)
    ds['u'] = getvar(wrfin, "ua", timeidx=ALL_TIMES)
    ds['v'] = getvar(wrfin, "va", timeidx=ALL_TIMES)
    ds['w'] = getvar(wrfin, "wa", timeidx=ALL_TIMES)
    ds['omega'] = getvar(wrfin, "omega", timeidx=ALL_TIMES)
    ds['tk'] = getvar(wrfin, "tk", timeidx=ALL_TIMES)
    ds['th'] = getvar(wrfin, "th", timeidx=ALL_TIMES, units='K')
    ds['eth'] = getvar(wrfin, "eth", timeidx=ALL_TIMES, units='K')
    ds['avo'] = getvar(wrfin, "avo", timeidx=ALL_TIMES)
    ds['pvo'] = getvar(wrfin, "pvo", timeidx=ALL_TIMES)
    ds['wspd'] = getvar(wrfin, "wspd_wdir", timeidx=ALL_TIMES,
                        units="m/s")[0, :]

    ds = ds.rename({'south_north': 'eta_rho', 'west_east': 'xi_rho'})
    ds = ds.rename({"XLAT": "lat", "XLONG": "lon"})
    ds = ds.drop(['wspd_wdir'])

    interp_method = 'bilinear'
    ds_out = xr.Dataset({
        'lat': (['lat'], lats_out),
        'lon': (['lon'], lons_out)
    })
    regridder = xe.Regridder(ds, ds_out, interp_method)
    regridder.clean_weight_file()
    ds = regridder(ds)
    ds = ds.squeeze()

    #accrain = ds.rain.rolling(Time=6, center=True).sum()
    #acclatent = ds.latent.rolling(Time=6, center=True).sum()
    #ds = ds.rolling(Time=6, center=True).mean()
    accrain = ds.rain.rolling(Time=12, center=False).sum()
    acclatent = ds.latent.rolling(Time=12, center=False).sum()
    #ds = ds.rolling(Time=6, center=True).mean()
    ds['accrain'] = accrain
    ds['acclatent'] = acclatent

    ds.to_netcdf(fout)

    return ds
コード例 #20
0
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from mpl_toolkits.basemap import *

from wrf import to_np, getvar, smooth2d, get_basemap, latlon_coords

# Open the NetCDF file
ncfile = Dataset("wrfout_d01_2019-01-26_12_00_00")

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

# Smooth the sea level pressure since it tends to be noisy near the
# mountains
smooth_slp = smooth2d(slp, 3, cenweight=4)

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

# Get the basemap object
bm = get_basemap(slp)

# Create a figure
fig = plt.figure(figsize=(12,9))

# Add geographic outlines
bm.drawcoastlines(linewidth=0.25)
bm.drawstates(linewidth=0.25)
bm.drawcountries(linewidth=0.25)
コード例 #21
0
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature

from wrf import ALL_TIMES, to_np, getvar, smooth2d, get_cartopy, cartopy_xlim, cartopy_ylim, latlon_coords

# Open the NetCDF file
ncfile = Dataset("/Users/zhenkunli/Dropbox/share/results/wrfout_d01_2014-07-01_00:00:00")

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

# Smooth the sea level pressure since it tends to be noisy near the mountains
LH = smooth2d(LH, 3)

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

# Get the cartopy mapping object
cart_proj = get_cartopy(LH)
print cart_proj

# Create a figure
fig = plt.figure(figsize=(8,6))
# Set the GeoAxes to the projection used by WRF
ax = plt.axes(projection=cart_proj)

# Download and add the states and coastlines
states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',
コード例 #22
0
    'llevels2': [1000],
    'llevels3': None,
    'time_index': tindex,
    'times': times,
    'zoom': zoom,
    'skip': 17
}

uvmet10 = getvar(files,
                 'wspd_wdir10',
                 timeidx=params['time_index'],
                 units="kt")

cffield = uvmet10.isel(wspd_wdir=0)
cffield.attrs['description'] = '10 m wind'
lfield = smooth2d(
    getvar(files, 'slp', timeidx=params['time_index'], units='hPa'), 3)
lfield2 = getvar(files, 'ter', timeidx=params['time_index'], units='m')
lfield3 = None
uvmet = getvar(files, 'uvmet10', timeidx=params['time_index'], units='kt')
ufld = uvmet.isel(u_v=0)
vfld = uvmet.isel(u_v=1)

make_plot(cffield, lfield, lfield2, lfield3, ufld, vfld, params)

# In[415]:

#=====================0-1 KM WIND=========================
params = {
    'outpath': outpath,
    'modname': modname,
    'modfld': 'Lifting_Condensation_Level',
コード例 #23
0
def metpy_read_wrf(tidx, froms, froms0, fwrf, lons_out, lats_out):

    wrfin = Dataset(fwrf)

    ds = xr.Dataset()

    slp = getvar(wrfin, "slp", timeidx=tidx)
    ds['slp'] = smooth2d(slp, 3, cenweight=4)

    lats, lons = latlon_coords(slp)
    ds['lats'] = lats
    ds['lons'] = lons
    landmask = extract_vars(wrfin, timeidx=tidx,
                            varnames=["LANDMASK"]).get("LANDMASK")
    u10 = extract_vars(wrfin, timeidx=tidx, varnames=["U10"]).get("U10")
    v10 = extract_vars(wrfin, timeidx=tidx, varnames=["V10"]).get("V10")
    ds['u10'] = u10.where(landmask == 0)
    ds['v10'] = v10.where(landmask == 0)
    latent = extract_vars(wrfin, timeidx=tidx, varnames=["LH"]).get("LH")
    ds['latent'] = smooth2d(latent, 3, cenweight=4)  #latent.where(landmask==0)
    t2m = extract_vars(wrfin, timeidx=tidx, varnames=["T2"]).get("T2") - 273.15
    ds['t2m'] = smooth2d(t2m, 3, cenweight=4)
    sst = extract_vars(wrfin, timeidx=tidx, varnames=["SST"]).get("SST")
    ds['sst'] = sst.where(landmask == 0)

    romsin = xr.open_dataset(froms)
    romsin = romsin.rename({"lat_rho": "lat", "lon_rho": "lon"})
    romsin = romsin.isel(ocean_time=tidx)

    ds['sst_5m'] = romsin.isel(z_r=0).temp
    ds['water_temp'] = romsin.temp
    ds['water_ucur'] = romsin.ucur / 100
    ds['water_vcur'] = romsin.vcur / 100
    ds.water_ucur.attrs['units'] = 'm/s'
    ds.water_vcur.attrs['units'] = 'm/s'

    romsin = xr.open_dataset(froms0)
    romsin = romsin.rename({"lat_rho": "lat", "lon_rho": "lon"})
    romsin = romsin.isel(ocean_time=tidx)
    ds['h'] = romsin.h

    mld = get_oml_depth(froms0, t_in=tidx)
    mld = smooth2d(mld, 3, cenweight=4)
    ds['oml_depth'] = xr.DataArray(mld, ds.sst_5m.coords, ds.sst_5m.dims,
                                   ds.sst_5m.attrs)
    ds['oml_depth2'] = ds.oml_depth.where(ds.h > 20)

    ds = ds.drop(['XLONG', 'XLAT', 'XTIME', 'Time'])
    ds = ds.rename({'south_north': 'eta_rho', 'west_east': 'xi_rho'})

    interp_method = 'bilinear'
    ds_out = xr.Dataset({
        'lat': (['lat'], lats_out),
        'lon': (['lon'], lons_out)
    })
    regridder = xe.Regridder(ds, ds_out, interp_method)
    regridder.clean_weight_file()
    ds = regridder(ds)
    ds = ds.squeeze()

    dxy = 10000.

    ds = ds.metpy.parse_cf().squeeze()

    utau, vtau = wind_stress(to_np(ds.u10), to_np(ds.v10))
    ds['u_tau'] = xr.DataArray(utau, ds.u10.coords, ds.u10.dims, ds.u10.attrs)
    ds['v_tau'] = xr.DataArray(vtau, ds.v10.coords, ds.v10.dims, ds.v10.attrs)
    curl = mpcalc.vorticity(utau * units('m/s'),
                            utau * units('m/s'),
                            dx=dxy * units.meter,
                            dy=dxy * units.meter)
    ds['wind_stress_curl'] = xr.DataArray(np.array(curl), ds.u10.coords,
                                          ds.u10.dims, ds.u10.attrs)

    div = []
    for z in range(len(ds.z_r)):
        div0 = mpcalc.divergence(ds.water_ucur.isel(z_r=z) * units('m/s'),
                                 ds.water_vcur.isel(z_r=z) * units('m/s'),
                                 dx=dxy * units.meter,
                                 dy=dxy * units.meter)
        div.append(div0)
    ds['cur_div'] = xr.DataArray(div, ds.water_ucur.coords, ds.water_ucur.dims,
                                 ds.water_ucur.attrs)

    div = mpcalc.divergence(ds.water_ucur.isel(z_r=2) * units('m/s'),
                            ds.water_vcur.isel(z_r=2) * units('m/s'),
                            dx=dxy * units.meter,
                            dy=dxy * units.meter)
    ds['surf_cur_div'] = xr.DataArray(np.array(div), ds.u10.coords,
                                      ds.u10.dims, ds.u10.attrs)

    print(ds)
    return ds
コード例 #24
0
def get_sea_level_pressure(wrf_data):
    slp = getvar(wrf_data, "slp")  # sea level pressure (2D)
    slp = smooth2d(slp, 3)  # Smooth sea level pressure
    return slp