Skip to content
Prev 24745 / 29559 Next

Set up raster data in WRF Mercator projection

Same process, just different projection.

with this folder structure:
project_dir
- data
- scripts

the following script in 'scripts', nc file in 'data'


library(ncdf4)
library(raster)

# open the nc file for reading
ncid=nc_open('../data/geo_em.d01.nc')

#check which grid the variable of interest is on
ncatt_get(ncid,'LANDMASK')#stagger=M

# domain corner grids. see
http://www2.mmm.ucar.edu/wrf/users/docs/user_guide_V3/users_guide_chap3.htm
cornerlat=ncatt_get(ncid,0)$corner_lats
cornerlong=ncatt_get(ncid,0)$corner_lons

# projected grid resolution
dx=ncatt_get(ncid,0)$DX
dy=ncatt_get(ncid,0)$DY

# the coordinates are on a sphere in longlat
proj1=CRS('+proj=longlat +towgs84=0,0,0 +a=6370000 +b=6370000 +units=m
+no_defs')

# But the data is in projected space. for a more general script, you would
build this programmatically from the attributes in geo file
wrfproj=CRS("+proj=merc +lat_ts=30 +lon_0=290 +a=6370000.0 +b=6370000.0
+units=m +no_defs")

# create spatial points
# using the extreme corners of the data since raster uses extreme
coordinates. page 3,
https://cran.r-project.org/web/packages/raster/vignettes/Raster.pdf
# there are 16 corner coordinates. 1:4 are cell centers. 13:16 are cell
extremes (see wrf user_guide linked above)
# these coordinates are in longlat so assign geographic system from above
spext <-
SpatialPoints(
list( x=cornerlong[13:16],
y=cornerlat[13:16]),
proj4string = proj1)

# convert to projected space
spext.wrf <- spTransform(spext,wrfproj)

# read the variable wanted
r=raster('../data/geo_em.d01.nc',varname='LANDMASK')
# assign projection detailed in the geo file (defined above as wrfproj)
projection(r)=wrfproj
# change extent to that of the projected spatialpoints
extent(r) <- extent(spext.wrf)
# check the raster.
r
# seem to be missing a couple meters in extent. might be a floating point
issue? you can force the resolution since you know it, but this will change
the bottom right corner of the extent
res(r)=c(dx,dy)
r
On Wed, Aug 3, 2016 at 11:51 AM, David Wang <dw2116 at outlook.com> wrote:

            

  
  
Message-ID: <CAF1jk_mB7J9bQ9J4cyY+Nuu4L29mMbLx8CGqRTUMvC0ZRNTDJQ@mail.gmail.com>
In-Reply-To: <DM5PR11MB159347CF8F3194CA92AC062ACB060@DM5PR11MB1593.namprd11.prod.outlook.com>