ex3_1_SubseasonalECVHindcast.md 11.7 KB
Newer Older
nperez's avatar
nperez committed
# Weekly ECV Subseasonal Hindcast Verification

nperez's avatar
nperez committed
This is a practical case to compute monthly skill scores for the ECMWF/S2S-ENSForhc subseasonal hindcast using as a reference dataset ERA5. The ECV is air temperature at surface level (tas).
nperez's avatar
nperez committed

Here, we aim to calculate the skill scores of the corresponding hindcast of 2016.

nperez's avatar
nperez committed
Note that to do this, we will detect the Mondays and Thursdays, which are the days of the week in which this model is initialized, during the year 2016 (this is the *$sdate$*).
However, we will analyze the 20 previous years (this is the *$syear$*) of those initializations.
nperez's avatar
nperez committed

nperez's avatar
nperez committed
The figure to see details on the subeasonal hindcasts storage:
nperez's avatar
nperez committed

nperez's avatar
nperez committed
<kbd><img src="inst/doc/figures/subseasonal_1.png" width="600" /></kbd>
nperez's avatar
nperez committed

nperez's avatar
nperez committed
After loading startR package, the paths to the hindcast should be defined, including labels for $var$, $sdate$ and $syear$:
nperez's avatar
nperez committed

nperez's avatar
nperez committed
```r
nperez's avatar
nperez committed
library(startR)

ecmwf_path <- paste0('/esarchive/exp/ecmwf/s2s-monthly_ensforhc/',
                     'weekly_mean/$var$_f24h/$sdate$/$var$_$syear$.nc')
```

nperez's avatar
nperez committed
Now, create the sequence of start dates in 2016 following the scheme in this figure:
nperez's avatar
nperez committed

nperez's avatar
nperez committed
<kbd><img src="inst/doc/figures/subseasonal_2.png" width="600" /></kbd>
nperez's avatar
nperez committed

nperez's avatar
nperez committed
```r
nperez's avatar
nperez committed
forecast.year <- 2016
# Mondays
sdates.seq.mon <- format(seq(as.Date(paste(forecast.year, 01, 04, sep = '-')),
                             as.Date(paste(forecast.year, 12, 31, sep='-')), 
                             by = 'weeks'), format = '%Y%m%d')
# Thursdays (Monday+3days)
sdates.seq.thu <- format(seq(as.Date(paste(forecast.year, 01, 04, sep = '-')) + 3,
                         as.Date(paste(forecast.year, 12, 31, sep = '-')),
                         by = 'weeks'), format = '%Y%m%d')
# Joint dates in order
sdates.seq <- c(sdates.seq.mon, sdates.seq.thu)
ind <- order(as.Date(sdates.seq, format = '%Y%m%d'))  # dates in order
sdates.seq <- sdates.seq[ind]

# Leap years, remove 29th of February:
pos.bis <- which(sdates.seq == paste0(forecast.year,"0229")) 
if(length(pos.bis) != 0) sdates.seq <- sdates.seq[-pos.bis] 

exp <- Start(dat = ecmwf_path, 
              var = 'tas',
              sdate = sdates.seq,
              syear = 'all',     # before hdate
              time = 'all',
              ensemble = "all",
              latitude = indices(1:121),
              longitude = indices(1:240),
              syear_depends = 'sdate',
              return_vars = list(latitude = NULL,
                                 longitude = NULL,
                                 time = c('sdate', 'syear')), 
              retrieve = FALSE)
nperez's avatar
nperez committed
```

The time attributes returned by Start() are then used to define the corresponding dates to load the reference dataset:
nperez's avatar
nperez committed

nperez's avatar
nperez committed
```r
nperez's avatar
nperez committed
# Corresponding ERA5 
## Generate the syears from the sdates.seq
syears <- t(sapply(sdates.seq, function(x) {
                   year <- as.numeric(substr(x, 1, 4))
                   syears <- paste0((year-20):(year-1), substr(x, 5, 8))
       }))
names(dim(syears)) <- c('sdate', 'syear')

## Generate the times from the syears
Sys.setenv(TZ='UTC') # this helps to get UTC times
times <- lapply(syears, function(x) {
                x <- as.Date(x, format = "%Y%m%d", tz = "UTC")
                x <- seq(x, x + 25, by = 'week')
               format(x, "%Y%m%d")
              })
times <- Reduce(c, times)
dim(times) <- c(time = 4, sdate = 103, syear = 20)
times <- s2dv::Reorder(times, c(2,3,1))
nperez's avatar
nperez committed

obs_path <- paste0("/esarchive/recon/ecmwf/era5/weekly_mean/",
                   "$var$_f1h-240x121/$var$_$file_date$.nc")

nperez's avatar
nperez committed
obs <- Start(dat = obs_path,
             var = 'tas',
nperez's avatar
nperez committed
             latitude = indices(1:121),
             longitude = indices(1:240),
             split_multiselected_dims = TRUE,
             return_vars = list(latitude = NULL,
                                longitude = NULL,
                                time = 'file_date'),
nperez's avatar
nperez committed
             retrieve = FALSE)
```

The next step is to define our function to calculate scores:

nperez's avatar
nperez committed
<kbd><img src="inst/doc/figures/subseasonal_3.png" width="600" /></kbd>


nperez's avatar
nperez committed

nperez's avatar
nperez committed
```r 
nperez's avatar
nperez committed
score_calc <- function(hindcast, reference, sdates.seq,
nperez's avatar
nperez committed
                       scores = 'all') {
  library(easyVerification)
nperez's avatar
nperez committed
  
  # Anomaly computation
nperez's avatar
nperez committed
  reference <- s2dv::InsertDim(reference, pos = 3, len = 1, name = 'ensemble')
nperez's avatar
nperez committed
  clim <- s2dv:::.Clim(hindcast, reference, time_dim = 'syear',
                       memb_dim = 'ensemble', memb = FALSE)
  hindcast <- Ano(hindcast, clim$clim_exp)
  reference <- Ano(reference, clim$clim_obs)
nperez's avatar
nperez committed
      
  # create objects to store the outputs
  Scores <- NULL
  Skill_Scores <- NULL

  for(month in 1:12) {
    # take only data of 1 month (indices of each month in start_dates)
    startdates <- which(as.integer(substr(sdates.seq, 5,6)) == month)
nperez's avatar
nperez committed
    hindcast_month <- s2dverification::Subset(hindcast, 'sdate', 
nperez's avatar
nperez committed
                                              list(startdates))
    reference_month <- s2dverification::Subset(reference, 'sdate',
                                               list(startdates))
nperez's avatar
nperez committed
    hindcast_month_reshaped <- array(hindcast_month, 
	          c(dim(hindcast_month)['sdate'] * dim(hindcast_month)['syear'],
                    dim(hindcast_month)['ensemble']))
nperez's avatar
nperez committed
    reference_month_reshaped <- array(reference_month, 
nperez's avatar
nperez committed
	                              c(dim(reference_month)['sdate'] * 
                                        dim(reference_month)['syear'],
	                                dim(reference_month)['ensemble']))
nperez's avatar
nperez committed
    if (any(c('fairrpss', 'frpss', 'all') %in% tolower(scores))) {
      Scores <- c(Scores, unlist(easyVerification::veriApply("FairRpss",
nperez's avatar
nperez committed
                  fcst = hindcast_month_reshaped, obs = reference_month_reshaped,
nperez's avatar
nperez committed
                  prob = c(1/3, 2/3), tdim = 1, ensdim = 2)))
    } 
    if (any(c('faircrpss', 'fcrpss', 'all') %in% tolower(scores))) {
      Scores <- c(Scores, unlist(easyVerification::veriApply("FairCrpss",
nperez's avatar
nperez committed
                  fcst = hindcast_month_reshaped, obs = reference_month_reshaped,
nperez's avatar
nperez committed
                  tdim = 1, ensdim = 2)))
    } 
    if (any(c('enscorr', 'corr', 'all') %in% tolower(scores))) {
nperez's avatar
nperez committed
      fcst_mean <- Apply(hindcast_month_reshaped, 'ensemble', mean)[[1]]
nperez's avatar
nperez committed
      Scores <- c(Scores,
                  cor = cor(fcst_mean, reference_month_reshaped,
                            use = "complete.obs"),
                  cor.pv = cor.test(fcst_mean, reference_month_reshaped,
                           use = "complete.obs")$p.value)
    }
    if (any(c('bss10', 'fbss10', 'all') %in% scores)) {
      Scores <- c(Scores, unlist(easyVerification::veriApply("FairRpss",
nperez's avatar
nperez committed
                  fcst = hindcast_month_reshaped, obs = reference_month_reshaped, 
nperez's avatar
nperez committed
                  prob = (1/10), tdim = 1, ensdim = 2)))
    }
    if (any(c('bss90', 'fbss90', 'all') %in% scores)) {
      Scores <- c(Scores, unlist(easyVerification::veriApply("FairRpss",
nperez's avatar
nperez committed
                            fcst = hindcast_month_reshaped, 
nperez's avatar
nperez committed
                            obs = reference_month_reshaped,
                            prob = (9/10), tdim = 1, ensdim = 2)))
nperez's avatar
nperez committed
    }
    Skill_Scores <- cbind(Skill_Scores, Scores)
nperez's avatar
nperez committed
    Scores <- NULL
nperez's avatar
nperez committed
  }
  return(Skill_Scores)
}
```

The workflow is created with Step() and AddStep()

nperez's avatar
nperez committed
<kbd><img src="inst/doc/figures/subseasonal_4.png" width="600" /></kbd>
nperez's avatar
nperez committed


nperez's avatar
nperez committed
```r
nperez's avatar
nperez committed
step <- Step(fun = score_calc, 
nperez's avatar
nperez committed
             target_dims = list(hindcast = c('sdate','syear','ensemble'),
nperez's avatar
nperez committed
                                reference = c('sdate', 'syear')),
             output_dims = list(c('scores', 'month')),
             use_libraries = c('easyVerification',
                               'SpecsVerification',
                               's2dverification'))
# Workflow:
wf <- AddStep(list(exp,obs), step, sdates.seq = sdates.seq, scores = 'all')
```

Finally, execute the analysis, for instance, in Nord3:


nperez's avatar
nperez committed
```r
nperez's avatar
nperez committed
#-----------modify according to your personal info---------
nperez's avatar
nperez committed
  queue_host = 'nord4'   #your own host name for Nord3v2
nperez's avatar
nperez committed
  temp_dir =  '/gpfs/scratch/bsc32/bsc32339/startR_hpc/'
  ecflow_suite_dir = '/home/Earth/nperez/startR_local/'  #your own local directory
#------------------------------------------------------------
nperez's avatar
nperez committed
result <- Compute(wf,
nperez's avatar
nperez committed
               chunks = list(time = 4, longitude = 2, latitude = 2),
nperez's avatar
nperez committed
               threads_load = 2,
nperez's avatar
nperez committed
               threads_compute = 12,
               cluster = list(queue_host = queue_host,
nperez's avatar
nperez committed
                              queue_type = 'slurm',
nperez's avatar
nperez committed
                              cores_per_job = 12,
                              temp_dir = temp_dir,
                              polling_period = 10,
nperez's avatar
nperez committed
                              job_wallclock = '03:00:00',
nperez's avatar
nperez committed
                              max_jobs = 16,
                              bidirectional = FALSE),
               ecflow_suite_dir = ecflow_suite_dir,
               wait = TRUE)
```
*Notice that the execution of `Compute` may last for ~2 hours each chunk. Consider set `wait` as false (see [practical guide](https://earth.bsc.es/gitlab/es/startR/-/blob/master/inst/doc/practical_guide.md#collect-and-the-ec-flow-gui)).*
nperez's avatar
nperez committed

If 'all' scores are requested the order in the 'scores' dimension of the output will be:
nperez's avatar
nperez committed
  - FairRpss_skillscore (1), FairRpss_sd (2), 
  - FairCrpss_skillscore (3), FairCrpss_sd (4), 
  - EnsCorr (5), EnsCorr_pv (6)
  - FairBSS10 (7), FairBSS10_pv (8)
  - FairBSS90 (9), FairBSS90_pv (10)
nperez's avatar
nperez committed

nperez's avatar
nperez committed
If you choose a subset of 'scores', it will follow the same order omitting the non-declared scores. It is useful to display the dimension names to understand the order of the output to create the plots. The significance can be also calculated using the standard deviation. Here, it is shown a simplified method:

nperez's avatar
nperez committed

nperez's avatar
nperez committed
```r
nperez's avatar
nperez committed
dim(result$output1)
nperez's avatar
nperez committed
library(multiApply) # to use Apply and calculate significance
library(ClimProjDiags) # to use ArrayToList facilitating the use of PlotLayout
library(s2dv) # to use PlotLayout combined with PlotEquiMap
nperez's avatar
nperez committed
FRPSS.pv <- Apply(result$output1, target_dims = c('scores'), 
                  fun = function(x, my.pvalue) {
                  (x[1] > 0) & (x[1] > x[2] * qnorm(1 - my.pvalue))},
                  my.pvalue = 0.05, ncores = 4)$output1


sig <- ArrayToList(FRPSS.pv[,1,1,1,,], 1, names = 'dots',
                    level = 'sublist')
nperez's avatar
nperez committed
vars <- ArrayToList(result$output1[1,,1,1,1,,], 1, names = '')
nperez's avatar
nperez committed
PlotLayout(fun = PlotEquiMap, 
           plot_dims = c('latitude', 'longitude'),
           var = vars,
           lon = attributes(exp)$Variables$common$longitude,
           lat = attributes(exp)$Variables$common$latitude,
           brks = seq(-1, 1, 0.2),
           filled.continents = FALSE, sizetit = NULL, dot_symbol = '/',
           special_args = sig, 
           toptitle = 'S2S FairRPSS - Hindcast 2016 - sweek 1',
           title_scale = 0.7,
           titles = month.name, bar_scale = 0.8,
           fileout = 'startR/inst/doc/figures/subseasonal_5.png')
nperez's avatar
nperez committed
```

nperez's avatar
nperez committed

<kbd><img src="inst/doc/figures/subseasonal_5.png" width="600" /></kbd>


nperez's avatar
nperez committed
This multipanel plot shows the monthly skill score FairRPSS corresponding to the first lead time (i.e. first week of each month) of the 20 years hindcast of 2016. Blue (red) grid points correspond to low (high) values of the Fair RPSS in which the predictability is low (high).  The highest values are found in tropical regions. However, the predictability is different for each month.
nperez's avatar
nperez committed

nperez's avatar
nperez committed
Given the high number of significant gridpoints, an alternative to display this information could be to filter the data for the non-significant points.
nperez's avatar
nperez committed

nperez's avatar
nperez committed
*References*

Wilks, D. S. (2011). Statistical methods in the atmospheric sciences. Elsevier/Academic Press.

Vitart, F., Buizza, R., Alonso Balmaseda, M., Balsamo, G., Bidlot, J.-R., Bonet, A., Fuentes, M., Hofstadler, A., Molteni, F., & Palmer, T. N. (2008). The new VarEPS-monthly forecasting system: A first step towards seamless prediction. Quarterly Journal of the Royal Meteorological Society, 134(636), 1789–1799. https://doi.org/10.1002/qj.322

nperez's avatar
nperez committed
*Credits to*
  - *Original code: Andrea Manrique*
  - *Adaptation: Núria Pérez-Zanón*