Esempio n. 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")
Esempio n. 2
0
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

# coordenadas estações meteorológicas do INMET
estacoes_met = pd.read_json(
    "estationCities.json")  # tabela com coordenada das estações

# usando um arquivo da PCWRF para obter pontos de grade
arq = nc.Dataset('../saidas/20200520_00/membro01/wrfout_d01_2020-05-20_00')

# obtendo pontos de grade mais próximos das coordenadas LON,LAT fornecidas
# estacoes_met_wrf[0,...] -> valores X (oeste-leste)
# estacoes_met_wrf[1,...] -> valores Y (sul-norte)
estacoes_met_wrf = wrf.ll_to_xy(
    arq,  # coordenadas (X,Y) das estações INMET
    estacoes_met.iloc[:, 1].tolist(),
    estacoes_met.iloc[:, 2].tolist())

# obtendo LON,LAT dos pontos de grade obtidos acima
# lat_lon_gridpoints[0,...] -> valores latitude
# lat_lon_gridpoints[1,...] -> valores longitude
lat_lon_gridpoints = wrf.xy_to_ll(arq, estacoes_met_wrf[0, :],
                                  estacoes_met_wrf[1, :])

# criando mapa com pontos de grade usados para extração e coordenadas das estações INMET
projWRF = wrf.get_cartopy(wrfin=arq)
estados = cfeature.NaturalEarthFeature(category='cultural',
                                       scale='50m',
                                       facecolor='none',
                                       name='admin_1_states_provinces_shp')
Esempio n. 3
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 = [22.0, 25.0, 27.0]
                lons = [-90.0, -87.5, -83.75]

                xy = ll_to_xy(infile, lats[0], lons[0])
                add_to_ncfile(outfile, xy, "xy")
            else:
                # Hardcoded from other unit tests
                x_s = np.asarray([10, 50, 90], int)
                y_s = np.asarray([10, 50, 90], int)

                ll = xy_to_ll(infile, x_s[0], y_s[0])
                add_to_ncfile(outfile, ll, "ll")
Esempio n. 4
0
    #     .sel(TIME=period).sel(LAT=slice(lat_range[0],lat_range[1]), LON=slice(lon_range[0],lon_range[1])) * 3
    # lat, lon = trmm.LAT, trmm.LON

    ### CMFD资料
    file_path = '/home/zzhzhao/code/python/wrf-test-10/data/prec_CMFD_201706.nc'
    cmfd = xr.open_dataset(file_path)['prec'].sel(lat=slice(lat_range[0],lat_range[1]), lon=slice(lon_range[0],lon_range[1])) * 3
    lat, lon =cmfd.lat, cmfd.lon

    ### 站点观测
    df = pd.read_excel('data/纳木错站2017-2018.xlsx', index_col=0)
    obs_NamCo = df.loc[pd.date_range('2017-06-01','2017-06-30')]['降水量']

#%%
    # NamCo station
    NamCo_latlon = (30.75, 90.9)
    NamCo_position = w.ll_to_xy(wrflist, NamCo_latlon[0], NamCo_latlon[1])
    prec1_NamCo = prec1.sel(south_north=NamCo_position[0], west_east=NamCo_position[1]).resample(Time='1D').sum()
    prec2_NamCo = prec2.sel(south_north=NamCo_position[0], west_east=NamCo_position[1]).resample(Time='1D').sum()
    # trmm_NamCo = trmm.sel(LAT=NamCo_latlon[0], LON=NamCo_latlon[1], method='ffill').resample(TIME='1D').sum()
    cmfd_NamCo = cmfd.sel(lat=NamCo_latlon[0], lon=NamCo_latlon[1], method='ffill').resample(time='1D').sum()

#%%
    fig, ax = plt.subplots(figsize=(9,4))
    ax.plot(obs_NamCo.index, obs_NamCo, lw=1.4, c='k', marker='o', mfc=None, markersize=3.5, label='OBS')
    ax.plot(prec1_NamCo.Time, prec1_NamCo, lw=1.4, c='r', marker='o', mfc=None, markersize=3.5, label='Ctrl')
    ax.plot(prec2_NamCo.Time, prec2_NamCo, lw=1.4, c='g', marker='o', mfc=None, markersize=3.5, label='nolake')
    # ax.plot(trmm_NamCo.TIME, trmm_NamCo, lw=1.4, c='b', marker='o', mfc=None, markersize=3.5, label='TRMM')
    ax.plot(cmfd_NamCo.time, cmfd_NamCo, lw=1.4, c='b', marker='o', mfc=None, markersize=3.5, label='CMFD')
    ax.set_title('NamCo Station', loc='left', y=0.9, x=0.02, fontsize=14, weight='bold')
    ax.set_ylabel('Precipitation $\mathrm{mmd^{-1}}$', fontsize=14)
    ax.legend(fontsize=13, loc='upper right', ncol=2, frameon=False)
dewpoint = getvar(ncfile, 'td')
wspd = getvar(ncfile, 'wspd_wdir')[0, :]
wdir = getvar(ncfile, 'wspd_wdir')[1, :]

# Add computed variables to dataset
ds = xr.open_dataset(filename)

ds['pressure'] = (['bottom_top', 'south_north', 'west_east'], pressure)
ds['height'] = (['bottom_top', 'south_north', 'west_east'], height)
ds['temperature'] = (['bottom_top', 'south_north', 'west_east'], temperature)
ds['dewpoint'] = (['bottom_top', 'south_north', 'west_east'], dewpoint)
ds['wspd'] = (['bottom_top', 'south_north', 'west_east'], wspd)
ds['wdir'] = (['bottom_top', 'south_north', 'west_east'], wdir)

# Select location of sounding
x_y = ll_to_xy(ncfile, lat, lon)

ds_point = ds.sel(west_east=x_y[0], south_north=x_y[1])

# Get variables for location
p = ds_point['pressure'].values * units.hPa
T = ds_point['temperature'].values * units.degC
Td = ds_point['dewpoint'].values * units.degC
wind_speed = ds_point['wspd'].values * units.knots
wind_dir = ds_point['wdir'].values * units.degrees

# Limit pressure level for wind barbs
p_200 = ds_point['pressure']
p_200 = p_200.where(p_200 > 200)
p_200 = p_200.values * units.hPa
Esempio n. 6
0
def obtain_background_data(nc_f, left_bottom, right_top, 
                           fields):
    background_data = {}
    
    nc_fid = Dataset(nc_f, 'r')
    lats_2d = nc_fid.variables['XLAT'][0, :, :]
    lons_2d = nc_fid.variables['XLONG'][0, :, :]

    left_bottom_xy = wrf.ll_to_xy(nc_fid, left_bottom[0], left_bottom[1])
    right_top_xy = wrf.ll_to_xy(nc_fid, right_top[0], right_top[1])
    
    
    if left_bottom_xy[1].values == right_top_xy[1].values:
        lat_start = left_bottom_xy[1].values
        lat_end = right_top_xy[1].values + 1
    else:
        lat_start = left_bottom_xy[1].values
        lat_end = right_top_xy[1].values

    if left_bottom_xy[0].values == right_top_xy[0].values:
        lon_start = int(left_bottom_xy[0].values)
        lon_end = int(right_top_xy[0].values + 1)
    else:
        lon_start = int(left_bottom_xy[0].values)
        lon_end = int(right_top_xy[0].values)

    background_data['lat'] = lats_2d[
            lat_start:lat_end, lon_start:lon_end]

    background_data['lon'] = lons_2d[
            lat_start:lat_end, lon_start:lon_end]

    for field in fields:
        if not field in ['dbz', 'T', 'U', 'V']:
            raise Exception('{} is not supported'.format(field))
        
        if field == 'dbz':
            pressure = wrf.g_pressure.get_pressure(nc_fid).values
            temperature = wrf.tk(pressure, wrf.g_temp.get_theta(nc_fid))
            water_vapor_mixing_ratio = nc_fid.variables['QVAPOR'][0, :, :, :]
            rain_mixig_ratio = nc_fid.variables['QRAIN'][0, :, :, :]
            snow_mixig_ratio = nc_fid.variables['QSNOW'][0, :, :, :]
            graupel_mixing_ratio = nc_fid.variables['QGRAUP'][0, :, :, :]
            cur_background_data = wrf.dbz(pressure, temperature,
                          water_vapor_mixing_ratio,
                          rain_mixig_ratio, snow_mixig_ratio,
                                graupel_mixing_ratio,
                                use_varint=True, meta=False)[0, lat_start:lat_end, lon_start:lon_end]
        else:
            if field == 'T':
                field_in = 'T2'
            elif field == 'U' or field == 'V':
                field_in = field + '10'
            else:
                field_in = field
                
            cur_background_data = nc_fid.variables[field_in][
                0, lat_start:lat_end, lon_start:lon_end]
        
        background_data[field] = cur_background_data

    return background_data
    qvap = qvap_1[tim_idx, :, :, :]
    qcld = qcld_1[tim_idx, :, :, :]
    thet = thet_1[tim_idx, :, :, :]
    hgt = hgt_1[tim_idx, :, :, :]
    terhgt = terhgt_1[0, :, :]
    ws = u_1[0, tim_idx, :, :, :]
    wd = u_1[1, tim_idx, :, :, :]

    dt = time.strftime("%Y%m%d%H",
                       time.gmtime(p.datetime.data.astype(int) / 1000000000))
    f_date = np.vstack(np.tile(dt, noloc * 44))
    tloc = np.vstack(np.repeat(locs, 44))
    tid = np.vstack(np.repeat(lst_f[:, 0], 44))
    pre_mat = np.concatenate([tid, tloc, f_date], axis=1)

    x_y = wrf.ll_to_xy(wrf_list, points[:, 0], points[:, 1], as_int=True)

    pres = np.array([p[:, i, k] for i, k in x_y.data.T]).T
    temp = np.array([tmp[:, i, k] for i, k in x_y.data.T]).T
    rhum = np.array([rh[:, i, k] for i, k in x_y.data.T]).T
    dtemp = np.array([td[:, i, k] for i, k in x_y.data.T]).T
    mrio = np.array([qvap[:, i, k] for i, k in x_y.data.T]).T
    theta = np.array([thet[:, i, k] for i, k in x_y.data.T]).T
    qcloud = np.array([qcld[:, i, k] for i, k in x_y.data.T]).T
    qrain = np.array([qran[:, i, k] for i, k in x_y.data.T]).T
    wspd = np.array([ws[:, i, k] for i, k in x_y.data.T]).T
    wdir = np.array([wd[:, i, k] for i, k in x_y.data.T]).T
    thgt = np.array([terhgt[i, k] for i, k in x_y.data.T]).T
    mhgt = np.array([hgt[:, i, k] for i, k in x_y.data.T]).T

    pres = np.vstack(pres.flatten('F'))
Esempio n. 8
0
# 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, colors="blue",
#             transform=crs.PlateCarree())
# plt.contourf(to_np(lons), to_np(lats), to_np(smooth_slp), 10,
#              transform=crs.PlateCarree(),
#              cmap=get_cmap("Blues"))

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

# plot markers for San Francisco, Santa Cruz

dummy = np.zeros(slp.shape)
for here in [SanFrancisco, SantaCruz]:
    xu, yu = to_np(ll_to_xy(ncfile, *here, stagger='U'))
    xv, yv = to_np(ll_to_xy(ncfile, *here, stagger='V'))
    x, y = to_np(ll_to_xy(ncfile, *here, stagger=None))
    print((xu, yu, xv, yv, x, y))
    dummy[yv, xv] = 500
# dummy = ma.masked_less(dummy, 500)

mylons = (lons[:, :-1] - (np.diff(lons, axis=1) / 2))[:-1, :]
mylats = (lats[:-1, :] - (np.diff(lats, axis=0) / 2))[:, :-1]

fig, ax = prepare_figure(smooth_slp)
ax.imshow(dummy,
          alpha=0.5,
          extent=(*cartopy_xlim(slp), *cartopy_ylim(slp)),
          transform=get_cartopy(slp),
          origin='lower')
Esempio n. 9
0
archivos = ls(Direccion + '*wrfout_d0'+Dominio+'_'+Fecha+'*')

# Open the NetCDF file
index = archivos[0].find("wrfout_d0")
filename = Direccion+archivos[0][index:]   # el programa debe estar en la misma carpeta de las extensiones .nc

print(filename)
ncfile = netCDF4.Dataset(filename)
altura = ncfile.variables['HGT'][:]
print(altura.shape)
z = getvar(ncfile,'z',meta=False) 
wspd =  getvar(ncfile, "uvmet_wspd_wdir",meta=False)[0,:]
lats = getvar(ncfile, 'lat',meta=False)
lons = getvar(ncfile, 'lon',meta=False)
UU, VV = wrf.g_uvmet.get_uvmet(ncfile,meta= False)
coor = wrf.ll_to_xy(ncfile, -17.6290737, -65.2842807, timeidx=0, meta=False, as_int=True) # Lat Lon cerca de Qollpana
ncfile.close()

print(lons[coor[1],coor[0]])
print(lats[coor[1],coor[0]])


#   Extrayendo los datos con MFdataset
Fecha = Anio+'-'+Mes
archivos = ls(Direccion + 'wrfout_d0'+Dominio+'_'+Fecha+'*')
# print(archivos)
index = archivos[0].find("wrfout_d0")
lista = archivos[:][index:]
print(coor)
start = time.time()
# f = netCDF4.MFDataset("D:/WRF/WRF15-08-19/wrfout_d04*")
        max_long = np1[1]

minLat = np.asscalar(min_lat)
maxLat = np.asscalar(max_lat)
minLon = np.asscalar(min_long)
maxLon = np.asscalar(max_long)

print("minLat: " + str(minLat))
print("maxLat: " + str(maxLat))
print("minLon: " + str(minLon))
print("maxLon: " + str(maxLon))

minimo = ll_to_xy(ncfile,
                  minLat,
                  minLon,
                  timeidx=0,
                  squeeze=True,
                  meta=True,
                  stagger=None,
                  as_int=True)

massimo = ll_to_xy(ncfile,
                   maxLat,
                   maxLon,
                   timeidx=0,
                   squeeze=True,
                   meta=True,
                   stagger=None,
                   as_int=True)

# Interpolazione Per la visualizzazione in stile windy devi avere u10, v10, t2c, rh2, pslp .
Esempio n. 11
0
# Open wrfouts
wrfin = [Dataset(x) for x in wrf_filenames]
# Define variables
#vars = ("tc","td","ua","va","pressure")
#for var in vars:
#    v = getvar(wrfin, var, timeidx=timex)

tc = wrf.getvar(wrfin, "tc", timeidx=timex)
td = wrf.getvar(wrfin, "td", timeidx=timex)
ua = wrf.getvar(wrfin, "ua", timeidx=timex)
va = wrf.getvar(wrfin, "va", timeidx=timex)
pressure = wrf.getvar(wrfin, "pressure", timeidx=timex)

# Find coordinate location on domain
sonde_loc = wrf.ll_to_xy(wrfin, lat, lon, timeidx=timex, squeeze=True, meta=True, stagger=None, as_int=True)

jj = sonde_loc[0]-1 
ii = sonde_loc[1]-1  

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p[:], T[:], 'black',label='Observation')
skew.plot(p[:], Td[:], 'black',linestyle='--',label='')
skew.plot_barbs(p[::5], u[::5], v[::5], y_clip_radius=0.03)


# plot WRF on Skew-T diagram
skew.plot(pressure[::3,ii,jj], td[::3,ii,jj], 'r',linestyle='--',label='')
skew.plot(pressure[::3,ii,jj], tc[::3,ii,jj], 'r',label='WRF')
skew.plot_barbs(to_np(pressure[::5,ii,jj]),to_np(ms_to_kt(ua[::5,ii,jj])),to_np(ms_to_kt(va[::5,ii,jj])),y_clip_radius=0.03,color='r')
Esempio n. 12
0
 def get_indexes(self, lat, lon, height):
     i_lon, i_lat = ll_to_xy(self.input_file, lat, lon)
     i_h = np.searchsorted(self.heights, height) - 1
     i_lat = i_lat - self.min_i_lat
     i_lon = i_lon - self.min_i_lon
     return i_lat, i_lon, i_h
Esempio n. 13
0
    def test(self):
        try:
            from netCDF4 import Dataset as NetCDF
        except:
            pass

        try:
            import Nio
        except:
            pass

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

        refnc = NetCDF(referent)
        try:
            refnc.set_always_mask(False)
        except:
            pass

        wrfin = []
        for fname in wrf_files:
            if not pynio:
                f = NetCDF(fname)
                try:
                    f.set_auto_mask(False)
                except:
                    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 testid == "xy":

            # Lats/Lons taken from NCL script, just hard-coding for now
            lats = [22.0, 25.0, 27.0]
            lons = [-90.0, -87.5, -83.75]

            # Just call with a single lat/lon
            if single:
                timeidx = 8
                ref_vals = refnc.variables["xy2"][:]

                xy = ll_to_xy(wrfin,
                              lats[0],
                              lons[0],
                              timeidx=timeidx,
                              as_int=True)
                ref = ref_vals[:, 0]

                nt.assert_allclose(to_np(xy), ref)

                # Next make sure the 'proj' version works
                projparams = extract_proj_params(wrfin, timeidx=timeidx)
                xy_proj = ll_to_xy_proj(lats[0],
                                        lons[0],
                                        as_int=True,
                                        **projparams)

                nt.assert_allclose(to_np(xy_proj), to_np(xy))

            else:
                ref_vals = refnc.variables["xy1"][:]
                xy = ll_to_xy(wrfin, lats, lons, timeidx=None, as_int=False)

                ref = ref_vals[:]

                nt.assert_allclose(to_np(xy), ref)

                if xy.ndim > 2:
                    # Moving nest
                    is_moving = True
                    numtimes = xy.shape[-2]
                else:
                    is_moving = False
                    numtimes = 1

                for tidx in range(9):

                    # Next make sure the 'proj' version works
                    projparams = extract_proj_params(wrfin, timeidx=tidx)
                    xy_proj = ll_to_xy_proj(lats,
                                            lons,
                                            as_int=False,
                                            **projparams)

                    if is_moving:
                        idxs = (slice(None), tidx, slice(None))
                    else:
                        idxs = (slice(None), )

                    nt.assert_allclose(to_np(xy_proj), to_np(xy[idxs]))

        else:
            # i_s, j_s taken from NCL script, just hard-coding for now
            # NCL uses 1-based indexing for this, so need to subtract 1
            x_s = np.asarray([10, 50, 90], int)
            y_s = np.asarray([10, 50, 90], int)

            if single:
                timeidx = 8
                ref_vals = refnc.variables["ll2"][:]
                ll = xy_to_ll(wrfin, x_s[0], y_s[0], timeidx=timeidx)
                ref = ref_vals[::-1, 0]

                nt.assert_allclose(to_np(ll), ref)

                # Next make sure the 'proj' version works
                projparams = extract_proj_params(wrfin, timeidx=8)
                ll_proj = xy_to_ll_proj(x_s[0], y_s[0], **projparams)

                nt.assert_allclose(to_np(ll_proj), to_np(ll))

            else:
                ref_vals = refnc.variables["ll1"][:]
                ll = xy_to_ll(wrfin, x_s, y_s, timeidx=None)
                ref = ref_vals[::-1, :]

                nt.assert_allclose(to_np(ll), ref)

                if ll.ndim > 2:
                    # Moving nest
                    is_moving = True
                    numtimes = ll.shape[-2]
                else:
                    is_moving = False
                    numtimes = 1

                for tidx in range(numtimes):
                    # Next make sure the 'proj' version works
                    projparams = extract_proj_params(wrfin, timeidx=tidx)
                    ll_proj = xy_to_ll_proj(x_s, y_s, **projparams)

                    if is_moving:
                        idxs = (slice(None), tidx, slice(None))
                    else:
                        idxs = (slice(None), )

                    nt.assert_allclose(to_np(ll_proj), to_np(ll[idxs]))
def lagranto_plotting(traj_variable_name,
                      start_time,
                      end_time,
                      trajs_bunch_level='all',
                      subset=False,
                      save=False):
    '''This function plots the chosen variables for the trajectories 
    calculated with Lagranto. Supported variables for plotting procedure 
    are water_vapor, updraft and height.'''

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if trajs_bunch_level == 'pbl':
        trajs_bunch = trajspbl

    elif trajs_bunch_level == '5':
        trajs_bunch = trajs5

    elif trajs_bunch_level == '10':
        trajs_bunch = trajs10

    elif trajs_bunch_level == 'all':
        trajs_bunch = trajs

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    plt.show()

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

        else:
            if trajs_bunch_level == 'all':
                fig.savefig('{}{}_{}.png'.format(save_dir, save_name,
                                                 start_locations),
                            bbox_inches='tight',
                            dpi=300)
            else:
                fig.savefig('{}{}_{}_{}.png'.format(save_dir, save_name,
                                                    trajs_bunch_level,
                                                    start_locations),
                            bbox_inches='tight',
                            dpi=300)
Esempio n. 15
0
g, maps = salem.geogrid_simulator(fpath)
maps[0].set_rgb(natural_earth='hr')
maps[0].visualize(ax=ax_map, title='Domains')

# export the figure
fig_map.set_size_inches(6, 6)
fig_map.savefig('fig/map.png')


# load WRF results
fl_WRF = sorted(glob('wrfout*'))
ds = salem.open_mf_wrf_dataset(fl_WRF)


dswrf = nc.Dataset(fl_WRF[0])
x_pos, y_pos = wrf.ll_to_xy(dswrf, latitude=[51.], longitude=[-0.1])

# ds.HFX[:, y_pos, x_pos].time
# ds.HFX[:, y_pos, x_pos].plot.line(add_legend=True)
ds_sel = ds[['HFX', 'LH', 'GRDFLX', 'SWDOWN', 'GLW']].resample(
    time='1h', label='left').mean()

# Facet plotting
ds_grp_clm = ds_sel.HFX.load().groupby('time.hour').median(axis=0)
fig_spatial_clm = ds_grp_clm.plot(
    x='west_east', y='south_north', col='hour',
    col_wrap=4, robust=True).fig

fig_spatial_clm.savefig('figures/QH_map.pdf')

# print ds_sel.resample.__doc__
Esempio n. 16
0
def temporal_evolution_trajectories(variable_name,
                                    trajs_bunch_level='all',
                                    save=False):
    '''This function plots the temporal evolution of trajectories 
    from the chosen variables. Trajectories can be divided in 
    bunches corresponding to different height levels (pbl, 5, 10).
    Supported variables are water_vapor, height and updraft.'''

    ### Predefine some variables ###
    number_trajs_plot = 1
    dt = 5  # delta time between data files

    traj_data_dir = '/scratch3/thomasl/work/retrospective_part/lagranto/' 'traj_baden_10000_1200.ll'

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

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

    # Define plotting variables
    if variable_name == 'water_vapor':
        variable = 'QVAPOR'
        title_name = 'Water Vapor'
        y_label = 'Water Vapor Mixing Ratio [$g$ $kg^{-1}$]'

    elif variable_name == 'height':
        variable = 'z'
        title_name = 'Height'
        y_label = 'Height of Trajectories [$m$]'

    elif variable_name == 'updraft':
        variable = 'W_UP_MAX'
        title_name = 'Updraft'
        y_label = 'Max Z-Wind Updraft [$m$ $s^-$$^1$]'

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

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

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

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

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

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

    trajs = np.array(trajspbl)

    # Get time delta
    xtime = np.arange(-len(trajs['time'][0]) * dt, 0, dt) + dt

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

    # Plot (bunch of) trajectories
    if trajs_bunch_level == 'pbl':
        for t in trajs[::number_trajs_plot]:
            ax.plot(xtime,
                    np.flipud(t[variable][:]),
                    '-',
                    color='grey',
                    lw=0.5)

        ax.plot(xtime,
                np.flipud(np.percentile(trajs[:][variable][:], 90, axis=0)),
                '--',
                color='blue',
                lw=2)
        ax.plot(xtime,
                np.flipud((np.percentile(trajs[:][variable][:], 10, axis=0))),
                '--',
                color='blue',
                lw=2)
        ax.plot(xtime,
                np.flipud(np.mean(trajs[:][variable][:], 0)),
                '-',
                color='blue',
                lw=2)

    elif trajs_bunch_level == '5':
        trajs = np.array(trajs5)
        for t in trajs[::number_trajs_plot]:
            ax.plot(xtime,
                    np.flipud(t[variable][:]),
                    '-',
                    color='grey',
                    lw=0.5)

        ax.plot(xtime,
                np.flipud(np.percentile(trajs[:][variable][:], 90, axis=0)),
                '--',
                color='orange',
                lw=2)
        ax.plot(xtime,
                np.flipud((np.percentile(trajs[:][variable][:], 10, axis=0))),
                '--',
                color='orange',
                lw=2)
        ax.plot(xtime,
                np.flipud(np.mean(trajs[:][variable][:], 0)),
                '-',
                color='orange',
                lw=2)

    elif trajs_bunch_level == '10':
        trajs = np.array(trajs10)
        for t in trajs[::number_trajs_plot]:
            ax.plot(xtime,
                    np.flipud(t[variable][:]),
                    '-',
                    color='grey',
                    lw=0.5)

        ax.plot(xtime,
                np.flipud(np.percentile(trajs[:][variable][:], 90, axis=0)),
                '--',
                color='red',
                lw=2)
        ax.plot(xtime,
                np.flipud((np.percentile(trajs[:][variable][:], 10, axis=0))),
                '--',
                color='red',
                lw=2)
        ax.plot(xtime,
                np.flipud(np.mean(trajs[:][variable][:], 0)),
                '-',
                color='red',
                lw=2)

    elif trajs_bunch_level == 'all':
        for t in trajs[::number_trajs_plot]:
            ax.plot(xtime,
                    np.flipud(t[variable][:]),
                    '-',
                    color='grey',
                    lw=0.5)

        ax.plot(xtime,
                np.flipud(np.percentile(trajs[:][variable][:], 90, axis=0)),
                '--',
                color='blue',
                lw=2)
        ax.plot(xtime,
                np.flipud((np.percentile(trajs[:][variable][:], 10, axis=0))),
                '--',
                color='blue',
                lw=2)
        ax.plot(xtime,
                np.flipud(np.mean(trajs[:][variable][:], 0)),
                '-',
                color='blue',
                lw=2)

        trajs = np.array(trajs5)
        for t in trajs[::number_trajs_plot]:
            ax.plot(xtime,
                    np.flipud(t[variable][:]),
                    '-',
                    color='grey',
                    lw=0.5)

        ax.plot(xtime,
                np.flipud(np.percentile(trajs[:][variable][:], 90, axis=0)),
                '--',
                color='orange',
                lw=2)
        ax.plot(xtime,
                np.flipud((np.percentile(trajs[:][variable][:], 10, axis=0))),
                '--',
                color='orange',
                lw=2)
        ax.plot(xtime,
                np.flipud(np.mean(trajs[:][variable][:], 0)),
                '-',
                color='orange',
                lw=2)

        trajs = np.array(trajs10)
        for t in trajs[::number_trajs_plot]:
            ax.plot(xtime,
                    np.flipud(t[variable][:]),
                    '-',
                    color='grey',
                    lw=0.5)

        ax.plot(xtime,
                np.flipud(np.percentile(trajs[:][variable][:], 90, axis=0)),
                '--',
                color='red',
                lw=2)
        ax.plot(xtime,
                np.flipud((np.percentile(trajs[:][variable][:], 10, axis=0))),
                '--',
                color='red',
                lw=2)
        ax.plot(xtime,
                np.flipud(np.mean(trajs[:][variable][:], 0)),
                '-',
                color='red',
                lw=2)

    # Add y- and x-axis label
    ax.set_ylabel(y_label, fontsize=12.5)
    ax.set_ylim(0, trajs[variable].max())

    ax.set_xlabel('Time [$min$]', fontsize=12.5)
    ax.set_xlim(xtime[0], 0)

    # Add horizontal gridlines according to height levels
    plt.grid(axis='y', linestyle='--', color='grey')

    # Plot legend
    if trajs_bunch_level == 'pbl':
        line_mean = mlines.Line2D([], [],
                                  color='k',
                                  linestyle='-',
                                  linewidth=2,
                                  label='Mean')
        line_percentiles = mlines.Line2D([], [],
                                         color='k',
                                         linestyle='--',
                                         linewidth=2,
                                         label='10th and 90th Percentile')
        line_mean_col_pbl = mlines.Line2D([], [],
                                          color='b',
                                          linestyle='-',
                                          linewidth=2,
                                          label='Planetary Boundary Layer')
        ax.legend(handles=[line_mean, line_percentiles, line_mean_col_pbl],
                  loc='upper left',
                  fontsize=10)

    elif trajs_bunch_level == '5':
        line_mean = mlines.Line2D([], [],
                                  color='k',
                                  linestyle='-',
                                  linewidth=2,
                                  label='Mean')
        line_percentiles = mlines.Line2D([], [],
                                         color='k',
                                         linestyle='--',
                                         linewidth=2,
                                         label='10th and 90th Percentile')
        line_mean_col_5 = mlines.Line2D([], [],
                                        color='orange',
                                        linestyle='-',
                                        linewidth=2,
                                        label='PBL until 5 km')
        ax.legend(handles=[line_mean, line_percentiles, line_mean_col_5],
                  loc='upper left',
                  fontsize=10)

    elif trajs_bunch_level == '10':
        line_mean = mlines.Line2D([], [],
                                  color='k',
                                  linestyle='-',
                                  linewidth=2,
                                  label='Mean')
        line_percentiles = mlines.Line2D([], [],
                                         color='k',
                                         linestyle='--',
                                         linewidth=2,
                                         label='10th and 90th Percentile')
        line_mean_col_10 = mlines.Line2D([], [],
                                         color='r',
                                         linestyle='-',
                                         linewidth=2,
                                         label='5 km until 10 km')
        ax.legend(handles=[line_mean, line_percentiles, line_mean_col_10],
                  loc='upper left',
                  fontsize=10)

    else:
        line_mean = mlines.Line2D([], [],
                                  color='k',
                                  linestyle='-',
                                  linewidth=2,
                                  label='Mean')
        line_percentiles = mlines.Line2D([], [],
                                         color='k',
                                         linestyle='--',
                                         linewidth=2,
                                         label='10th and 90th Percentile')
        line_mean_col_pbl = mlines.Line2D([], [],
                                          color='b',
                                          linestyle='-',
                                          linewidth=2,
                                          label='Planetary Boundary Layer')
        line_mean_col_5 = mlines.Line2D([], [],
                                        color='orange',
                                        linestyle='-',
                                        linewidth=2,
                                        label='PBL until 5 km')
        line_mean_col_10 = mlines.Line2D([], [],
                                         color='r',
                                         linestyle='-',
                                         linewidth=2,
                                         label='5 km until 10 km')
        ax.legend(handles=[
            line_mean, line_percentiles, line_mean_col_pbl, line_mean_col_5,
            line_mean_col_10
        ],
                  loc='upper left',
                  fontsize=10)

    # Add title
    ax.set_title('Temporal Evolution of {} along Trajectories\n'
                 '@ Location of Thunderstorm Initiation ({}, {})'.format(
                     title_name, lat, lon),
                 fontsize=15)

    plt.show()

    ### Save figure ###
    if save == True:
        fig.savefig('{}lagranto_evo_{}_{}_{}_{}.png'.format(
            save_dir, variable_name, trajs_bunch_level, lat, lon),
                    bbox_inches='tight',
                    dpi=300)
Esempio n. 17
0
    t_diff_list = dict()
    tsk_list = dict()
    t2_list = dict()

    lat = 30.75
    lon = 90.75

    for testname in testname_list:
        data_path = os.path.join(data_dir, testname)
        domain = 1
        tsk, lats, lons, time, wrflist = load_wrfdata1(data_path, domain)
        t2, lats, lons, time = load_wrfdata2(data_path, domain)
        tsk = xr.where(tsk > 0, tsk, np.nan)
        t2 = xr.where(t2 > 0, t2, np.nan)

        x, y = w.ll_to_xy(wrflist, lat, lon)

        t2_list[testname] = t2.sel(west_east=x, south_north=y)
        tsk_list[testname] = tsk.sel(west_east=x, south_north=y)

#%%
    labels = [
        'CTL_285K',
        'CTL',
        # 'WY',
        # 'WY2',
        # 'WY3',
        'WY4',
        'CTL3_285K',
    ]
Esempio n. 18
0
from __future__ import print_function
from netCDF4 import Dataset
from wrf import getvar, interpline, CoordPair, xy_to_ll, ll_to_xy

ncfile = Dataset("coa_I_t01.nc")
lat_lon = xy_to_ll(ncfile, [400,105], [200,205])
print(lat_lon)
x_y = ll_to_xy(ncfile, lat_lon[0,:], lat_lon[1,:])
print (x_y)
Esempio n. 19
0
    if i == inittime:
        rainc = nc_file.variables['RAINC'][i, :, :]
        rainnc = nc_file.variables['RAINNC'][i, :, :]
        rain = rainc + rainnc
    if i > inittime:
        rainc1 = nc_file.variables['RAINC'][i, :, :]
        rainnc1 = nc_file.variables['RAINNC'][i, :, :]
        rainc = nc_file.variables['RAINC'][i - 1, :, :] - rainc1
        rainnc = nc_file.variables['RAINNC'][i - 1, :, :] - rainnc1
        rain = rainc1 + rainnc1

    # Calculate the XY location throught the specified latitude and longitude coordinates.
    latlon = ll_to_xy(nc_file,
                      lat,
                      lon,
                      timeidx=i,
                      squeeze=True,
                      meta=False,
                      as_int=True,
                      stagger='m')

    # Store the data from the desired location.
    rh = rh[latlon[0], latlon[1]]
    uvmet = uvmet[0, latlon[0], latlon[1]]
    slp = slp[latlon[0], latlon[1]]
    tc = tc[latlon[0], latlon[1]]
    tc = tc - 273.15
    rain = rain[latlon[0], latlon[1]]
    tc_list[i] = round(tc, 1)
    rh_list[i] = round(rh, 0)
    slp_list[i] = round(slp, 1)
    uvmet_list[i] = round(uvmet, 1)
Esempio n. 20
0
def main(folder, append, extract_yr, extract_wrf, extract_met):
    #sourceIDlist = ["424242"]
    sourceIDlist = [
        '424242',  #Frankfurt airport
        '2925507',  #Fränkisch-Crumbach
        '2926120',  #Flörsheim
        '2925533',  #Frankfurt am Main
        '2926300',  #Fleisbach
        '7290400',  #Airport Frankfurt Main
        '2926419',  #Flacht
        '2925550',  #Frankenthal
        '3220966',  #Landkreis Darmstadt-Dieburg
        '2925665',  #Frammersbach
        '7290401',  #Niederrad
        'SN18700',  # OSLO - BLINDERN          
        'SN6700',  # RV3 Svingen - Elverum
        'SN71900',  # Bessaker
        'SN71990',  # Buholmråsa fyr
        'SN76914'
    ]  # ITASMOBAWS1 - Rikshospitalet i Oslo
    for sourceID in sourceIDlist:
        ########################################################################
        # Get coordinates for observation point (lon,lat)
        if sourceID[0:2] == 'SN':  # Assume Norwegian station number format
            endpoint = 'https://frost.met.no/sources/v0.jsonld'
            parameters = {
                'ids': sourceID,
            }

            data_source = getMetdata(endpoint, parameters, 'data')
            masl = data_source[0]['masl']
            lon = data_source[0]['geometry']['coordinates'][0]
            lat = data_source[0]['geometry']['coordinates'][1]
        else:
            masl = np.NAN
            df = pd.read_json(home + '/kode/wrfStudies/city.list.json')
            lon = df[df.id == float(sourceID)].coord.item()['lon']
            lat = df[df.id == float(sourceID)].coord.item()['lat']

        ########################################################################
        # Get data from met file
        if extract_met:
            print('Not implemented')

        ########################################################################
        # Get data from WRF file
        if extract_wrf:
            print('Extracting wrf data')
            i_domain = 10
            isOutside = True
            while isOutside:
                if i_domain < 0:
                    print('The observation station ' + str(sourceID) +
                          ' is not inside the solution domain')
                    break

                i_domain -= 1
                try:
                    ncfile = Dataset('wrfout_d0' + str(i_domain) + '.nc')
                except:
                    continue

                xy = wrf.ll_to_xy(ncfile, lat, lon, as_int=False)

                if ncfile.MAP_PROJ_CHAR == 'Cylindrical Equidistant' and i_domain == 1:
                    xy[0] += 360 / 0.25

                #HGT = getvar(ncfile, "HGT")
                #maslg = HGT.interp(west_east=xy[0], south_north=xy[1])
                #lat_lon = wrf.xy_to_ll(ncfile,xy[0],xy[1])
                df_wrf = pd.DataFrame(
                    {'time': wrf.getvar(ncfile, 'Times', wrf.ALL_TIMES)})
                df_wrf['air_temperature'] = wrf.to_np(
                    wrf.getvar(ncfile, 'T2', wrf.ALL_TIMES).interp(
                        west_east=xy[0], south_north=xy[1])) - 273.15
                if df_wrf.isnull().values.any():
                    continue
                else:
                    isOutside = False

                df_wrf['wind_speed'] = wrf.g_uvmet.get_uvmet10_wspd_wdir(
                    ncfile, wrf.ALL_TIMES).interp(west_east=xy[0],
                                                  south_north=xy[1])[0]
                df_wrf[
                    'wind_from_direction'] = wrf.g_uvmet.get_uvmet10_wspd_wdir(
                        ncfile, wrf.ALL_TIMES).interp(west_east=xy[0],
                                                      south_north=xy[1])[1]

                df_wrf['time'] = pd.to_datetime(df_wrf['time'])
                df_wrf = df_wrf.reset_index()

                if path.exists(folder + 'df_wrf_' + sourceID +
                               '.csv') and append:
                    df_wrf_hist = pd.read_csv(folder + 'df_wrf_' + sourceID +
                                              '.csv')
                    if datetime.strptime(
                            df_wrf_hist['time'].iloc[-1],
                            "%Y-%m-%d %H:%M:%S") < df_wrf['time'].iloc[-1]:
                        df_wrf_hist = df_wrf_hist[
                            df_wrf_hist['time'] <= str(df_wrf['time'][0])]
                        df_wrf_hist = df_wrf_hist.append(df_wrf)
                        df_wrf_hist.to_csv(folder + 'df_wrf_' + sourceID +
                                           '.csv',
                                           index=False)
                else:
                    df_wrf.to_csv(folder + 'df_wrf_' + sourceID + '.csv',
                                  index=False)

                print('Sucessfully extracted wrf data')

        ########################################################################
        # Get YR forecast
        if extract_yr:
            endpoint = 'https://api.met.no/weatherapi/locationforecast/2.0/complete'
            endpoint = 'https://api.met.no/weatherapi/locationforecast/2.0/compact'
            parameters = {
                'lon': str(lon),
                'lat': str(lat),
            }
            if not np.isnan(masl):
                parameters['altitude'] = masl

            fields = [
                'time', 'air_temperature', 'wind_speed', 'wind_from_direction'
            ]
            data_YR = getYRdata(endpoint, parameters, 'properties')

            data_YR = data_YR['timeseries']

            df = pd.DataFrame()
            for i in range(len(data_YR)):
                row = pd.DataFrame({'time': [data_YR[i]['time']]})
                for j in range(1, len(fields)):
                    row[fields[j]] = data_YR[i]['data']['instant']['details'][
                        fields[j]]
                df = df.append(row)

            df_YR = df[fields].copy()
            # Convert the time value to something Python understands
            df_YR['time'] = pd.to_datetime(df_YR['time']).dt.tz_convert(None)
            df_YR = df_YR.reset_index()

            if path.exists(folder + 'df_YR_' + sourceID + '.csv') and append:
                df_YR_hist = pd.read_csv(folder + 'df_YR_' + sourceID + '.csv')
                df_YR_hist = df_YR_hist[
                    df_YR_hist['time'] <= str(df_YR['time'][0])]
                df_YR_hist = df_YR_hist.append(df_YR)
                df_YR_hist.to_csv(folder + 'df_YR_' + sourceID + '.csv',
                                  index=False)
            else:
                df_YR.to_csv(folder + 'df_YR_' + sourceID + '.csv',
                             index=False)

            print('Sucessfully extracted YR data')
Esempio n. 21
0
def getXeY(wrf_file: str, lat: float, lon: float):
    """ Obtiene los x e y del lat long
    """
    (x, y) = ll_to_xy(wrf_file, lat, lon)

    return int(x), int(y)
Esempio n. 22
0
month = input('month (e.g., 09): ')
year = input('year: ')
scenario = input('scenario: ')
wrfout = [Dataset(i) for i in sorted(glob.glob('../wrfout_diss/wrfout_d02_'+year+'-'+month+'-*'))]

print("Extracting RAINC and RAINNC variables, named as rainc and rainnc")
rainc = wrf.getvar(wrfout,'RAINC',timeidx=wrf.ALL_TIMES, method='cat')
rainnc = wrf.getvar(wrfout,'RAINNC',timeidx=wrf.ALL_TIMES, method='cat')

print("Reading file with station location points")
cetesb_stations = pd.read_csv('./cetesb2017_latlon.dat')
print(cetesb_stations)

# Locating stations in west_east (x) and north_south (y) coordinates
stations_xy = wrf.ll_to_xy(wrfout,
                           latitude=cetesb_stations.lat,
                           longitude=cetesb_stations.lon)
cetesb_stations['x'] = stations_xy[0]
cetesb_stations['y'] = stations_xy[1]

# Filter stations inside WRF domain
filter_dom = (cetesb_stations.x > 0) & (cetesb_stations.x < rainc.shape[2]) & (cetesb_stations.y > 0) & \
 (cetesb_stations.y < rainc.shape[1])
cetesb_dom = cetesb_stations[filter_dom]

# Function to retrieve variables from WRF-Chem
def cetesb_from_wrf(i, to_local=True):
    wrf_est = pd.DataFrame({
        'date': rainc.Time.values,
        'rainc': rainc.sel(south_north=cetesb_dom.y.values[i],
                           west_east=cetesb_dom.x.values[i]).values,