Source

GFED-3.1_global_to_AQMEII-NA / vis_regrid_vis.r

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# R code to 2D-regrid GFED global/unprojected netCDF data to AQMEII-NA, an LCC-projected subdomain

# If running manually in R console, remember to run setup actions: `source ./sum_regrid_retemp_reunit.sh`

# ----------------------------------------------------------------------
# constants
# ----------------------------------------------------------------------

# all the following env vars must be set and exported in driver script
# TODO: pass as args!

### data

## kludge for my clumsy namespacing
my_this_fn <- Sys.getenv('VIS_REGRID_VIS_FN')
this_fn <- my_this_fn
work_dir <- Sys.getenv('WORK_DIR')

## visualization

pdf_er <- Sys.getenv('PDF_VIEWER')
sigdigs <- as.numeric(Sys.getenv('OUTPUT_SIGNIFICANT_DIGITS'))

## projection
global_proj4 <- Sys.getenv('GLOBAL_PROJ4')

## AQMEII-NA template

template_input_fp <- Sys.getenv('TEMPLATE_INPUT_FP')
template_datavar_name <- Sys.getenv('TEMPLATE_DATAVAR_NAME')

## monthly input

monthly_in_fp <- Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_FP')
monthly_in_datavar_name <- Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_DATAVAR_NAME')
monthly_in_datavar_long_name <- Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_DATAVAR_LONG_NAME')
monthly_in_datavar_unit <- Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_DATAVAR_UNIT')
# monthly_in_datavar_na <- as.numeric(Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_DATAVAR_NA'))
monthly_in_time_dim_name <- Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_DIM_TIME_NAME')
# plot it
monthly_in_pdf_fp <- Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_PDF_FP')
monthly_in_pdf_height <- as.numeric(Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_PDF_HEIGHT'))
monthly_in_pdf_width <- as.numeric(Sys.getenv('GFED_GLOBAL_MONTHLY_CONV_PDF_WIDTH'))

## monthly output

monthly_out_fp <- Sys.getenv('GFED_REGRID_MONTHLY_FP')
monthly_out_datavar_name <- Sys.getenv('GFED_REGRID_MONTHLY_DATAVAR_NAME')
monthly_out_datavar_long_name <- Sys.getenv('GFED_REGRID_MONTHLY_DATAVAR_LONG_NAME')
monthly_out_datavar_units <- Sys.getenv('GFED_REGRID_MONTHLY_DATAVAR_UNITS')
# monthly_out_datavar_na <- Sys.getenv('GFED_REGRID_MONTHLY_DATAVAR_NA')
monthly_out_time_dim_name <- Sys.getenv('GFED_REGRID_MONTHLY_DIM_TIME_NAME')
monthly_out_x_var_name <- Sys.getenv('GFED_REGRID_MONTHLY_DIM_X_NAME')
monthly_out_y_var_name <- Sys.getenv('GFED_REGRID_MONTHLY_DIM_Y_NAME')
monthly_out_z_var_name <- Sys.getenv('GFED_REGRID_MONTHLY_DIM_TIME_NAME')
monthly_out_z_var_units <- Sys.getenv('GFED_REGRID_MONTHLY_DIM_TIME_UNITS')
# plot it
monthly_out_pdf_fp <- Sys.getenv('GFED_REGRID_MONTHLY_PDF_FP')
monthly_out_pdf_height <- as.numeric(Sys.getenv('GFED_REGRID_MONTHLY_PDF_HEIGHT'))
monthly_out_pdf_width <- as.numeric(Sys.getenv('GFED_REGRID_MONTHLY_PDF_WIDTH'))

## daily input

daily_in_fp <- Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_FP')
daily_in_datavar_name <- Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_DATAVAR_NAME')
daily_in_datavar_long_name <- Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_DATAVAR_LONG_NAME')
daily_in_datavar_unit <- Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_DATAVAR_UNIT')
# daily_in_datavar_na <- as.numeric(Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_DATAVAR_NA'))
daily_in_time_dim_name <- Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_DIM_TIME_NAME')
# plot it
daily_in_pdf_fp <- Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_PDF_FP')
daily_in_pdf_height <- as.numeric(Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_PDF_HEIGHT'))
daily_in_pdf_width <- as.numeric(Sys.getenv('GFED_GLOBAL_DAILY_FRAC_CONV_PDF_WIDTH'))

## daily output

daily_out_fp <- Sys.getenv('GFED_REGRID_DAILY_FRAC_FP')
daily_out_datavar_name <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DATAVAR_NAME')
daily_out_datavar_long_name <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DATAVAR_LONG_NAME')
daily_out_datavar_units <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DATAVAR_UNITS')
# daily_out_datavar_na <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DATAVAR_NA')
daily_out_time_dim_name <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DIM_TIME_NAME')
daily_out_x_var_name <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DIM_X_NAME')
daily_out_y_var_name <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DIM_Y_NAME')
daily_out_z_var_name <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DIM_TIME_NAME')
daily_out_z_var_units <- Sys.getenv('GFED_REGRID_DAILY_FRAC_DIM_TIME_UNITS')
# plot it
daily_out_pdf_fp <- Sys.getenv('GFED_REGRID_DAILY_FRAC_PDF_FP')
daily_out_pdf_height <- as.numeric(Sys.getenv('GFED_REGRID_DAILY_FRAC_PDF_HEIGHT'))
daily_out_pdf_width <- as.numeric(Sys.getenv('GFED_REGRID_DAILY_FRAC_PDF_WIDTH'))

## 3-hourly input

# 3hourly_in_fp <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_FP')
# not allowed in R; instead,
hour3ly_in_fp <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_FP')
hour3ly_in_datavar_name <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_DATAVAR_NAME')
hour3ly_in_datavar_long_name <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_DATAVAR_LONG_NAME')
hour3ly_in_datavar_unit <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_DATAVAR_UNIT')
# hour3ly_in_datavar_na <- as.numeric(Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_DATAVAR_NA'))
hour3ly_in_time_dim_name <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_DIM_TIME_NAME')
# plot it
hour3ly_in_pdf_fp <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_PDF_FP')
hour3ly_in_pdf_height <- as.numeric(Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_PDF_HEIGHT'))
hour3ly_in_pdf_width <- as.numeric(Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_PDF_WIDTH'))

## working around inability to regrid 4D objects in `raster` (more below)
hour3ly_in_tstep_dim_posn <- as.numeric(Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_CONV_TSTEP_POSN'))
hour3ly_regrid_fp_template <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_FP_TEMPLATE')
hour3ly_template_string <- Sys.getenv('GFED_GLOBAL_3HOURLY_FRAC_TEMPLATE_STRING')

## 3-hourly output

hour3ly_out_fp <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_FP')
hour3ly_out_datavar_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DATAVAR_NAME')
hour3ly_out_datavar_long_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DATAVAR_LONG_NAME')
hour3ly_out_datavar_units <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DATAVAR_UNITS')
# hour3ly_out_datavar_na <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DATAVAR_NA')
hour3ly_out_time_dim_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_TIME_NAME')
hour3ly_out_x_var_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_X_NAME')
hour3ly_out_y_var_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_Y_NAME')
# hour3ly_out_z_var_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_TIME_NAME')
# hour3ly_out_z_var_units <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_TIME_UNITS')
# Can't do 4D regrids, so instead will 3D regrid each TSTEP, so ...
hour3ly_out_z_var_name <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_LAYER_NAME')
hour3ly_out_z_var_units <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_DIM_LAYER_UNITS')
# plot it
hour3ly_out_pdf_fp <- Sys.getenv('GFED_REGRID_3HOURLY_FRAC_PDF_FP')
hour3ly_out_pdf_height <- as.numeric(Sys.getenv('GFED_REGRID_3HOURLY_FRAC_PDF_HEIGHT'))
hour3ly_out_pdf_width <- as.numeric(Sys.getenv('GFED_REGRID_3HOURLY_FRAC_PDF_WIDTH'))

## helpers

stat_funcs_fp <- Sys.getenv('STATS_FUNCS_FP')
viz_funcs_fp <- Sys.getenv('VIS_FUNCS_FP')

# ----------------------------------------------------------------------
# functions
# ----------------------------------------------------------------------

source(stat_funcs_fp) # in script, produces errant error=
#> netCDF.stats.to.stdout.r: no arguments supplied, exiting
source(viz_funcs_fp)

# ----------------------------------------------------------------------
# code
# ----------------------------------------------------------------------

# ----------------------------------------------------------------------
# setup
# ----------------------------------------------------------------------

# accelerate R graphics over SSH, per Adam Wilson
# http://planetflux.adamwilson.us/2012/03/r-graphics-via-ssh.html
X11.options(type="Xlib")

### for input viz
global.crs <- sp::CRS(global_proj4)

### for output viz

# output coordinate reference system:
# use package=M3 to get CRS from template file
library(M3)
out.proj4 <- M3::get.proj.info.M3(template_input_fp)
# cat(sprintf('out.proj4=%s\n', out.proj4)) # debugging
# out.proj4=+proj=lcc +lat_1=33 +lat_2=45 +lat_0=40 +lon_0=-97 +a=6370000 +b=6370000
out.crs <- sp::CRS(out.proj4)

# ----------------------------------------------------------------------
# payload
# ----------------------------------------------------------------------

library(raster)

# ----------------------------------------------------------------------
# (minimally) process monthly input
# ----------------------------------------------------------------------

# # no, will do full visualize.layers below
# # start debugging
# nonplot.vis.layers(
#   nc.fp=monthly_in_fp,
#   datavar.name=monthly_in_datavar_name,
#   layer.dim.name=monthly_in_time_dim_name,
#   sigdigs=sigdigs)
# #   end debugging

monthly.in.raster <- raster::brick(monthly_in_fp, varname=monthly_in_datavar_name)
# something whacks the CRS, so
monthly.in.raster@crs <- global.crs

# start debugging
cat('\nmonthly.in.raster==\n')
monthly.in.raster
# class       : RasterBrick 
# dimensions  : 360, 720, 259200, 12  (nrow, ncol, ncell, nlayers)
# resolution  : 0.5, 0.5  (x, y)
# extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +ellps=WGS84 
# data source : in memory
# names       :       X1,       X2,       X3,       X4,       X5,       X6,       X7,       X8,       X9,      X10,      X11,      X12 
# min values  :        0,        0,        0,        0,        0,        0,        0,        0,        0,        0,        0,        0 
# max values  : 13969387,  5885226,  6427964, 21219698, 33916608, 26628432, 42413160, 44400768, 20038280, 16292042,  7483781, 16257402 
# #   end debugging

# ----------------------------------------------------------------------
# visualize input/global monthly emissions
# ----------------------------------------------------------------------

# "create" world map
library(maps)
map.world.unproj <- maps::map('world', plot=FALSE)
map.world.unproj.shp <-
  maptools::map2SpatialLines(map.world.unproj, proj4string=global.crs)

# # start debugging
# summary(map.world.unproj.shp)
# # Object of class SpatialLines
# # Coordinates:
# #          min       max
# # x -179.95721 190.29080 # ??? why > 180 ???
# # y  -85.44308  83.57391
# # Is projected: FALSE 
# # proj4string : [+proj=longlat +ellps=WGS84]
# #   end debugging

# Why does '=' fail and '<-' succeed in the arg list?
visualize.layers(
  nc.fp=monthly_in_fp,
  datavar.name=monthly_in_datavar_name,
  layer.dim.name=monthly_in_time_dim_name,
  sigdigs=sigdigs,
  brick=monthly.in.raster,
#  map.list=list(map.world.unproj.shp),
  map.list <- list(map.world.unproj.shp),
  pdf.fp=monthly_in_pdf_fp,
  pdf.height=monthly_in_pdf_height,
  pdf.width=monthly_in_pdf_width
)

# ----------------------------------------------------------------------
# get AQMEII-NA template for regridding
# ----------------------------------------------------------------------

# # start debugging
# # long IOAPI schema and I don't care about its layers
# cmd <- sprintf('ncdump -h %s | head -n 13', nc.fp)
# cat(sprintf('\n: template file: %s==\n', cmd))
# system(cmd)
# # netcdf emis_mole_all_20080101_12US1_cmaq_cb05_soa_2008ab_08c.EXTENTS_INPUT {
# # dimensions:
# #       TSTEP = UNLIMITED ; // (25 currently)
# #       LAY = 1 ;
# #       ROW = 299 ;
# #       COL = 459 ;
# # variables:
# #       float emi_n2o(TSTEP, LAY, ROW, COL) ;
# #               emi_n2o:long_name = "XYL             " ;
# #               emi_n2o:units = "moles/s         " ;
# #               emi_n2o:var_desc = "Model species XYL                                                               " ;
# # 
# # // global attributes:
# #   end debugging

# use package=M3 to get extents from template file (thanks CGN!)
extents.info <- M3::get.grid.info.M3(template_input_fp)
extents.xmin <- extents.info$x.orig
extents.xmax <- max(
  M3::get.coord.for.dimension(
    file=template_input_fp, dimension="col", position="upper", units="m")$coords)
extents.ymin <- extents.info$y.orig
extents.ymax <- max(
  M3::get.coord.for.dimension(
    file=template_input_fp, dimension="row", position="upper", units="m")$coords)
grid.res <- c(extents.info$x.cell.width, extents.info$y.cell.width) # units=m

template.extents <-
  raster::extent(extents.xmin, extents.xmax, extents.ymin, extents.ymax)
# template.extents # debugging
# class       : Extent 
# xmin        : -2556000 
# xmax        : 2952000 
# ymin        : -1728000 
# ymax        : 1860000 

template.in.raster <-
  raster::raster(template_input_fp, varname=template_datavar_name)
template.raster <- raster::projectExtent(template.in.raster, crs=out.crs)
#> Warning message:
#> In projectExtent(template.in.raster, out.proj4) :
#>   158 projected point(s) not finite
# is that "projected point(s) not finite" warning important? Probably not, per Hijmans

# without this, extents aren't correct!
template.raster@extent <- template.extents
# should resemble the domain specification @
# https://github.com/TomRoche/cornbeltN2O/wiki/AQMEII-North-American-domain#wiki-EPA

# # start debugging
# cat('\ntemplate.raster==\n')
# template.raster
# # class       : RasterLayer 
# # dimensions  : 299, 459, 137241  (nrow, ncol, ncell)
# # resolution  : 12000, 12000  (x, y)
# # extent      : -2556000, 2952000, -1728000, 1860000  (xmin, xmax, ymin, ymax)
# # coord. ref. : +proj=lcc +lat_1=33 +lat_2=45 +lat_0=40 +lon_0=-97 +a=6370000 +b=6370000 
# #   end debugging

# ----------------------------------------------------------------------
# regrid monthly emissions
# ----------------------------------------------------------------------

# at last: do the regridding
cat(sprintf(  # debugging
  '\n%s: regridding monthly emissions (may take awhile)\n', this_fn))
monthly.out.raster <-
  raster::projectRaster(
    # give a template with extents--fast, but gotta calculate extents
    from=monthly.in.raster, to=template.raster, crs=out.crs,
    # give a resolution instead of a template? no, that hangs
#    from=monthly.in.raster, res=grid.res, crs=out.proj4,
    method='bilinear', overwrite=TRUE, format='CDF',
    # args from writeRaster
#    NAflag=regrid.datavar.na,
    varname=monthly_out_datavar_name, 
    varunit=monthly_out_datavar_units,
    longname=monthly_out_datavar_long_name,
    xname=monthly_out_x_var_name,
    yname=monthly_out_y_var_name,
    # gotta have these, else `ncdump -h` ->
# dimensions:
#         COL = 459 ;
#         ROW = 299 ;
#         value = UNLIMITED ; // (12 currently)
# variables:
# ...
#         int value(value) ;
#                 value:units = "unknown" ;
#                 value:long_name = "value" ;
    zname=monthly_out_z_var_name,
    zunit=monthly_out_z_var_units,
    filename=monthly_out_fp)

# start debugging
cat(sprintf(  # debugging
  '\n\n%s: regridding -> monthly.out.raster==\n', this_fn))
monthly.out.raster
# class       : RasterBrick 
# dimensions  : 299, 459, 137241, 12  (nrow, ncol, ncell, nlayers)
# resolution  : 12000, 12000  (x, y)
# extent      : -2556000, 2952000, -1728000, 1860000  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=lcc +lat_1=33 +lat_2=45 +lat_0=40 +lon_0=-97 +a=6370000 +b=6370000 
# data source : .../GFED-3.1_2008_N2O_monthly_emissions_regrid.nc 
# names       : X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12 
# month       : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 
# varname     : N2O 
#   end debugging

# ----------------------------------------------------------------------
# visualize output/AQMEII monthly emissions
# ----------------------------------------------------------------------

## get projected North American map
NorAm.shp <- project.NorAm.boundaries.for.CMAQ(
  units='m',
  extents.fp=template_input_fp,
  extents=template.extents,
  LCC.parallels=c(33,45),
  CRS=out.crs)
# # start debugging
# class(NorAm.shp)
# bbox(NorAm.shp)
# # compare bbox to (above)
# # > template.extents
# # class       : Extent 
# # xmin        : -2556000 
# # xmax        : 2952000 
# # ymin        : -1728000 
# # ymax        : 1860000 
# #   end debugging

# Why does '=' fail and '<-' succeed in ONE PLACE in the arg list?
visualize.layers(
  nc.fp=monthly_out_fp,
  datavar.name=monthly_out_datavar_name,
  layer.dim.name=monthly_out_time_dim_name,
  sigdigs=sigdigs,
  brick=monthly.out.raster,
  map.list <- list(NorAm.shp),
  pdf.fp=monthly_out_pdf_fp,
  pdf.height=monthly_out_pdf_height,
  pdf.width=monthly_out_pdf_width
)

# ----------------------------------------------------------------------
# (minimally) process daily input
# ----------------------------------------------------------------------

# # nope: too damn many, takes too long
# # start debugging
# nonplot.vis.layers(
#   nc.fp=daily_in_fp,
#   datavar.name=daily_in_datavar_name,
#   layer.dim.name=daily_in_time_dim_name)
#   sigdigs=sigdigs)
# #   end debugging

daily.in.raster <- raster::brick(daily_in_fp, varname=daily_in_datavar_name)
daily.in.raster@crs <- global.crs

# start debugging
cat('\ndaily.in.raster==\n')
daily.in.raster
# class       : RasterBrick 
# dimensions  : 360, 720, 259200, 366  (nrow, ncol, ncell, nlayers)
# resolution  : 1, 1  (x, y)
# extent      : 0.5, 720.5, 0.5, 360.5  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +ellps=WGS84 
# data source : .../GFED-3.1_2008_N2O_daily_fractions.nc 
# names       : X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, ... 
#             : 1, 366 (min, max)
# varname     : Fraction_of_Emissions 
# level       : 1 

# ----------------------------------------------------------------------
# regrid daily fractions (sans visualization)
# ----------------------------------------------------------------------

cat(sprintf(  # debugging
  '\n%s: regridding daily fractions to %s (WILL take awhile)\n', this_fn, daily_out_fp))

daily.out.raster <-
  raster::projectRaster(
    # give a template with extents--fast, but gotta calculate extents
    from=daily.in.raster, to=template.raster, crs=out.crs,
    method='bilinear', overwrite=TRUE, format='CDF',
    # args from writeRaster
    varname=daily_out_datavar_name, 
    varunit=daily_out_datavar_units,
    longname=daily_out_datavar_long_name,
    xname=daily_out_x_var_name,
    yname=daily_out_y_var_name,
    # see need for these (above)
    zname=daily_out_z_var_name,
    zunit=daily_out_z_var_units,
    filename=daily_out_fp)

# start debugging
cat(sprintf(  # debugging
  '\n\n%s: regridding -> daily.out.raster==\n', this_fn))
daily.out.raster

# # nope: too damn many, takes too long
# # start debugging
# nonplot.vis.layers(
#   nc.fp=daily_out_fp,
#   datavar.name=daily_out_datavar_name,
#   layer.dim.name=daily_out_time_dim_name)
#   sigdigs=sigdigs)
# #   end debugging

# ----------------------------------------------------------------------
# (minimally) process 3-hourly input
# ----------------------------------------------------------------------

### Cannot make `raster` preserve all 4 dimensions of the annualized brick in the regridded output: see
### https://stat.ethz.ch/pipermail/r-sig-geo/2013-April/017947.html
### So instead regrid each timestep==month, and reassemble.

# hour3ly.in.raster <- raster::brick(
#   hour3ly_in_fp, varname=hour3ly_in_datavar_name)
# hour3ly.in.raster@crs <- global.crs

# # start debugging
# cat('\nhour3ly.in.raster==\n')
# hour3ly.in.raster
# # class       : RasterBrick 
# # dimensions  : 360, 720, 259200, 12  (nrow, ncol, ncell, nlayers)
# # resolution  : 0.5, 0.5  (x, y)
# # extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# # coord. ref. : +proj=longlat +ellps=WGS84 
# # data source : .../GFED-3.1_2008_N2O_3hourly_fractions.nc 
# # names       : X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12 
# # month       : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 
# # varname     : Fraction_of_Emissions 
# # level       : 1 
# #   end debugging

# ----------------------------------------------------------------------
# regrid 3-hourly fractions
# ----------------------------------------------------------------------

### get data for output files

# always assign when `nc_open`
hour3ly.in.fh <- nc_open(hour3ly_in_fp, write=FALSE, readunlim=TRUE)
hour3ly.in.var <- ncvar_get(hour3ly.in.fh, varid=hour3ly_in_datavar_name)

# # don't actually need these!
# # interrogate `hour3ly.in.fh$var` to discover:
# hour3ly.in.var.obj <- hour3ly.in.fh$var[[1]] # has powers hour3ly.in.var lacks
# hour3ly.in.var.name <- hour3ly.in.var.obj$name
# hour3ly.in.var.prec <- hour3ly.in.var.obj$prec
# hour3ly.in.var.units <- hour3ly.in.var.obj$units
# hour3ly.in.var.longname <- hour3ly.in.var.obj$longname
# hour3ly.in.var.missval <- hour3ly.in.var.obj$missval

# # interrogate `hour3ly.in.fh$dim` to discover:
# hour3ly.in.dim.tstep <- hour3ly.in.fh$dim[[1]]
# hour3ly.in.dim.lay <- hour3ly.in.fh$dim[[2]]
# hour3ly.in.dim.row <- hour3ly.in.fh$dim[[3]]
# hour3ly.in.dim.col <- hour3ly.in.fh$dim[[4]]

# # start debugging
# cat('hour3ly.in.fh==')
# hour3ly.in.fh

# # don't do this!
# # cat('hour3ly.in.var==')
# # hour3ly.in.var

# # this fails: cat(sprintf('hour3ly.in.var$name==%s\n', hour3ly.in.var$name))
# cat(sprintf('hour3ly.in.var.obj$name==%s\n', hour3ly.in.var.name))
# cat(sprintf('hour3ly.in.var.obj$prec==%s\n', hour3ly.in.var.prec))
# cat(sprintf('hour3ly.in.var.obj$units==%s\n', hour3ly.in.var.units))
# cat(sprintf('hour3ly.in.var.obj$longname==%s\n', hour3ly.in.var.longname))
# cat(sprintf('hour3ly.in.var.obj$missval==%s\n', hour3ly.in.var.missval))
# # hour3ly.in.var.obj$name==Fraction_of_Emissions
# # hour3ly.in.var.obj$prec==float
# # hour3ly.in.var.obj$units==unitless
# # hour3ly.in.var.obj$longname==3hourly fraction of monthly N2O emission
# # hour3ly.in.var.obj$missval==9.96920996838687e+36

# cat('dim(hour3ly.in.var)==')
# dim(hour3ly.in.var)
# # [1] 720 360   8  12
# cat(sprintf('hour3ly.in.fh$dim[[1]]$name==%s\n', hour3ly.in.fh$dim[[1]]$name))
# cat(sprintf('hour3ly.in.fh$dim[[2]]$name==%s\n', hour3ly.in.fh$dim[[2]]$name))
# cat(sprintf('hour3ly.in.fh$dim[[3]]$name==%s\n', hour3ly.in.fh$dim[[3]]$name))
# cat(sprintf('hour3ly.in.fh$dim[[4]]$name==%s\n', hour3ly.in.fh$dim[[4]]$name))
# # hour3ly.in.fh$dim[[1]]$name==TSTEP
# # hour3ly.in.fh$dim[[2]]$name==LAY
# # hour3ly.in.fh$dim[[3]]$name==ROW
# # hour3ly.in.fh$dim[[4]]$name==COL
# #   end debugging

hour3ly.in.tstep.n <- dim(hour3ly.in.var)[hour3ly_in_tstep_dim_posn] # Fortran-style indexing
nc_close(hour3ly.in.fh) # close input filehandle

# # "define" schema for output datavars: mostly just copy input datavars, except ...
# hour3ly.out.dim.list <- list(
# #  hour3ly.in.dim.tstep, # outputs will have no TSTEP (until reassembled)
#   hour3ly.in.dim.lay,
#   hour3ly.in.dim.row,
#   hour3ly.in.dim.col)
# hour3ly.out.var.def <- ncvar_def(
#   name=hour3ly_in_datavar_name,
#   units=hour3ly_in_datavar_unit,
#   dim=hour3ly.out.dim.list,
#   missval=hour3ly.in.var.missval,
#   longname=hour3ly.in.var.longname,
#   prec=hour3ly.in.var.prec,
#   shuffle=FALSE, compression=NA, chunksizes=NA)

# cat(sprintf(  # debugging
#   '\n%s: regridding 3-hourly fractions to %s\n', this_fn, hour3ly_out_fp))

for (i.tstep in 1:hour3ly.in.tstep.n) { # iterate over TSTEP=month
  
  cat(sprintf( # debugging
    '\n\t%s: regridding 3-hourly fractions for TSTEP=%i\n', this_fn, i.tstep))

  ### Get brick=ROW X COL X LAY for TSTEP=i.tstep
  regrid.in.raster <- raster::brick(
    hour3ly_in_fp, varname=hour3ly_in_datavar_name,
    # see discussion in thread @ https://stat.ethz.ch/pipermail/r-sig-geo/2013-April/017947.html
    lvar=hour3ly_in_tstep_dim_posn,
    level=i.tstep)
  regrid.in.raster@crs <- global.crs

#   # start debugging
#   cat(sprintf( # debugging
#     '\t\t%s: regridding -> regrid.in.raster==\n', this_fn))
#   regrid.in.raster
# # class       : RasterBrick 
# # dimensions  : 360, 720, 259200, 8  (nrow, ncol, ncell, nlayers)
# # resolution  : 0.5, 0.5  (x, y)
# # extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# # coord. ref. : +proj=longlat +ellps=WGS84 
# # data source : .../GFED-3.1_2008_N2O_3hourly_fractions.nc 
# # names       : X0, X3, X6, X9, X12, X15, X18, X21 
# # 4-digit hour: 0, 3, 6, 9, 12, 15, 18, 21 
# # varname     : Fraction_of_Emissions 
# # level       : 1 
#   #  end debugging

  ### output the regridded raster as netCDF--put them together later :-(
  tstep.string <- sprintf("%0.2i", i.tstep) # '%0.'==left pad zeros
  # string substitution in R
  regrid.out.fp <- sub(
    x=hour3ly_regrid_fp_template,
    pattern=hour3ly_template_string, replacement=tstep.string, fixed=TRUE)

  # start debugging
  cat(sprintf( # debugging
    '\t\t%s: preparing to write regrid.out.raster to regrid.out.fp==%s\n',
    this_fn, regrid.out.fp))
  #  end debugging

  regrid.out.raster <- raster::projectRaster(
    # give a template with extents--fast, but gotta calculate extents
    from=regrid.in.raster, to=template.raster, crs=out.crs,
    method='bilinear', overwrite=TRUE, format='CDF',
    # args from writeRaster
    varname=hour3ly_out_datavar_name,
    varunit=hour3ly_out_datavar_units,
    longname=hour3ly_out_datavar_long_name,
    xname=hour3ly_out_x_var_name,
    yname=hour3ly_out_y_var_name,
    # see need for these (above)
    zname=hour3ly_out_z_var_name,
    zunit=hour3ly_out_z_var_units,
    filename=regrid.out.fp)

#   # start debugging
#   cat(sprintf( # debugging
#     '\t\t%s: regridding -> regrid.out.raster==\n', this_fn))
#   regrid.out.raster
# # class       : RasterBrick 
# # dimensions  : 299, 459, 137241, 8  (nrow, ncol, ncell, nlayers)
# # resolution  : 12000, 12000  (x, y)
# # extent      : -2556000, 2952000, -1728000, 1860000  (xmin, xmax, ymin, ymax)
# # coord. ref. : +proj=lcc +lat_1=33 +lat_2=45 +lat_0=40 +lon_0=-97 +a=6370000 +b=6370000 
# # data source : .../GFED-3.1_2008_N2O_3hourly_fractions_regrid.nc 
# # names       : X1, X2, X3, X4, X5, X6, X7, X8 
# # 4-digit hour: 1, 2, 3, 4, 5, 6, 7, 8 
# # varname     : Fraction_of_Emissions 
# ############## FIXME: why have values(LAY) changed relative to regrid.in.raster ???????
#   nonplot.vis.layer(
#     nc.fp=regrid.out.fp,
#     datavar.name=hour3ly_out_datavar_name,
#     sigdigs=sigdigs)
#   #  end debugging

} # end iterating TSTEP=month