metno / esd

An R-package designed for climate and weather data analysis, empirical-statistical downscaling, and visualisation.
88 stars 30 forks source link

Extract values for specific points #275

Closed BenCretois closed 1 year ago

BenCretois commented 1 year ago

I have a set of coordinates (reg1, example dataframe below) that I use to retrieve values from a netcdf file hosted on senorge:

  longitude latitude       date
1  11.95501 65.67812 2006-03-26
2  11.95501 65.67814 2006-03-26
3  11.95498 65.67821 2006-03-26
4  11.95493 65.67808 2006-03-26
5  11.95487 65.67809 2006-03-26
6  11.95497 65.67810 2006-03-26
rr <- retrieve(file="https://thredds.met.no/thredds/dodsC/senorge/seNorge_2018/Archive/seNorge2018_2006.nc", 
               param = "rr", lon=reg1$longitude, lat=reg1$latitude, it=reg1$date, verbose=TRUE)

As I understand rr is a zoo object containing the values for the temperate for the different dates specified.

I have no experience working with zoo objects and I was wondering if the esd package has a function for extracting the values contained in rr for a specific point? That would be the equivalent of extract from the raster package.

brasmus commented 1 year ago

Yes. But retrieve assumes a range of longitudes, latitudes and times. Also, the netCDF file uses a different convention to the CF.

You can use ```r2 library(esd) seNorge.thredds <- "https://thredds.met.no/thredds/dodsC/senorge/seNorge_2018/Archive/seNorge2018_2006.nc" ncid <- nc_open(seNorge.thredds) names(ncid$var) lon <- ncvar_get(ncid,"longitude") lat <- ncvar_get(ncid,"latitude") tim <- ncvar_get(ncid,"time") image(lon) image(lat)

Need to select right start index and counts...

...



We have not managed to complete `retrieve` for reading rotated grids or UTM.
BenCretois commented 1 year ago

Thanks for your answer! I also found another way which might be a bit more straightforward and avoid working with zoo objects. The solution relies on the stars package. I am pasting it the snippet here in case it can be useful for others:


# fetch the ncdf file for a specific year
  url=paste0('NETCDF:/vsicurl/https://thredds.met.no/thredds/fileServer/senorge/seNorge_2018/Archive/seNorge2018_', year,'.nc')
  
  # Read the netcdf file from the url
  netcdf_file=stars::read_stars(url, sub='rr', proxy=TRUE) 
  
  # Transform the dataset into an sf object
  data_st <- data %>% st_as_sf(.,
                               coords = c("longitude", "latitude"), 
                               crs=4326)
  
  # Reproject the CRS to match the CRS of the netcdf
  data_st <- st_transform(data_st, crs=st_crs(netcdf_file))
  data_st$rr <- st_extract(netcdf_file, data_st, time_column="date")