# Núria Pérez-Zanón
# Loading and plotting data in rotated coordinates
# Monarch-dustclim
# Required modules in workstation: R 3.6.1 and GDAL/2.2.1-foss-2015a-GEOS-3.8.0
#-------------------------------
library(startR)

path <- '/esarchive/oper/thredds-dust/monarch-dustclim/3hourly/$var$-av_an/$var$_$date$03_av_an.nc'

date <- c('20131229', '20131230')
# two temporal dimensions: one for days and another four hours
data_split <- Start(dataset = path,
              var = 'od550du',
              lev = 'all',
              date = date,
              time = 'all',
              rlat = 'all',
              rlon = 'all',
              return_vars = list(lev = NULL, time = NULL,
                                 rlat = NULL, rlon = NULL,
                                 lat = NULL, lon = NULL),
              retrieve = TRUE, num_procs = 1)
# one temporal dimension
data <- Start(dataset = path,
              var = 'od550du',
              lev = 'all',
              date = date,
              time = 'all',
              rlat = 'all',
              rlon = 'all',
              time_across = 'date',
              merge_across_dims = TRUE,
              return_vars = list(lev = NULL, time = 'date',
                                 rlat = NULL, rlon = NULL,
                                 lat = NULL, lon = NULL),
              retrieve = TRUE, num_procs = 1)
# check both are consistent:
all(data[1,1,1,1:8,,]==data_split[1,1,1,1,,,])

# Save important information from attributes
lat <- attributes(data)$Variables$common$lat
lon <- attributes(data)$Variables$common$lon
rlat <- attributes(data)$Variables$common$rlat
rlon <- attributes(data)$Variables$common$rlon
# Or check information:
attributes(data)$Variables$common$lev
attributes(data)$Variables$common$time


# PLOT:
map <- data[1,1,1,1,,] # Time-step 1
library(sf)
library(ggplot2)
map <- data.frame(rlat = rep(rlat, length(rlon)),
                 rlon = sort(rep(rlon, length(rlat))), datos = as.vector(map))
dat_map <- st_as_sf(map, coords = c("rlon", "rlat"), crs = 4326)
x <- lwgeom::st_transform_proj(dat_map, c(st_crs(4326)$proj4string, "+proj=ob_tran +o_proj=longlat +o_lon_p=-160 +o_lat_p=55 +lon_0=180 +to_meter=0.01745329"))
plot(x)
bbox <- st_bbox(x)
borders <- st_as_sf(maps::map('world', plot = FALSE, fill = TRUE))
st_crs(x) = NA # ?! (!)
st_crs(x) = 4326
ggplot() + 
  geom_sf(data=x, aes(color=datos)) +
  geom_sf(data = borders, fill=NA, colour="black") + coord_sf(xlim = bbox[c(1,3)],ylim = bbox[c(2,4)]) 
