Source

regrid_utils / netCDF.stats.to.stdout.r

Full commit
  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
# R code to write simple stats (min, mean, quartiles, max) for an input file.
# Run this like
# $ Rscript ./netCDF.stats.to.stdout.r netcdf.fp=./GEIA_N2O_oceanic.nc data.var.name=emi_n2o
# or
# > source('./netCDF.stats.to.stdout.r')
# > netCDF.stats.to.stdout(...)

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

this.fn <- 'netCDF.stats.to.stdout.r'      # TODO: get like $0

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

# syntactic sugar
q1 <- function(vec) { quantile(vec, 0.25) } # first quartile
q3 <- function(vec) { quantile(vec, 0.75) } # third quartile

# the main event
netCDF.stats.to.stdout <- function(
  netcdf.fp, # /path/to/netcdf/file, can be relative or FQ
  data.var.name,   # name of data variable (datavar) of interest
  stats.precision=3 # sigdigs to use for min, median, max of obs  
) {
  fn.name <- 'netCDF.stats.to.stdout' # TODO: derive from environment?
  # TODO: test arguments!

#  # start debug
#  cat(sprintf(
#    '%s: netcdf.fp==%s, data.var.name==%s\n',
#    this.fn, netcdf.fp, data.var.name))
#  system(sprintf('ls -alth %s', netcdf.fp))
#  system(sprintf('ncdump -h %s', netcdf.fp))
#  #   end debug

  # create strings for use in output below (far below)
  # double-sprintf-ing to set precision by constant: cool or brittle?
  stat.str.template <- sprintf('%%.%ig', stats.precision)
  # use these in function=subtitle.stats as sprintf inputs
  sum.str.template <- sprintf('sum=%s', stat.str.template)
  max.str.template <- sprintf('max=%s', stat.str.template)
  mea.str.template <- sprintf('mean=%s', stat.str.template)
  med.str.template <- sprintf('med=%s', stat.str.template)  # median==2nd quartile
  min.str.template <- sprintf('min=%s', stat.str.template)
  q1.str.template <- sprintf('q1=%s', stat.str.template)    # 1st quartile
  q3.str.template <- sprintf('q3=%s', stat.str.template)    # 3rd quartile

  # needed to parse netCDF
  library(ncdf4)

  # open netCDF file, uncautiously
  # NOTE: you must assign when you nc_open!
  netcdf.file <- ncdf4::nc_open(
    filename=netcdf.fp,
    write=FALSE,    # will only read below
    readunlim=TRUE) # it's a small file

  # uncautiously get the data out of the datavar
  data.var.data <- ncvar_get(
    nc=netcdf.file,
    varid=data.var.name)

#  # start debug
#  cat(sprintf('%s: data.var.name==%s has size==\n',
#    this.fn, data.var.name))
#  print(dim(data.var.data))
#  #   end debug

  if (is.numeric(data.var.data) && sum(!is.na(data.var.data))) {
    stats.to.stdout(
      data=data.var.data,
      sig.digs=stats.precision,
      title=sprintf('From %s datavar=%s:', netcdf.fp, data.var.name)
    )
  } else {
    cat(sprintf('%s::%s: %s var=%s has no numeric non-NA data\n',
      this.fn, fn.name, netcdf.fp, data.var.name))
  }

  # teardown
  nc_close(netcdf.file)
} # end function netCDF.stats.to.stdout

stats.to.stdout <- function(
  data,          # numeric array, may include NAs
  sig.digs=3,    # significant digits for numeric fields
  title=''       # one line identifying data source
) {
  fn.name <- 'stats.to.stdout' # TODO: derive from environment?
  # TODO: test arguments!
  if (is.numeric(data) && sum(!is.na(data))) {
    # collapse its structure
    unsparse.data <- c(data[!is.na(data)])
    obs.n <- length(unsparse.data)
    if (obs.n > 0) {
      unsparse.stats.to.stdout(
        data.nonNA=unsparse.data,
        data.nonNA.n=obs.n,
        data.raw.n=length(data),
        sig.digs=sig.digs,
        title=title
      )
    } else {
      cat(sprintf('%s::%s: no non-NA data\n', this.fn, fn.name))
    }
  } else {
    cat(sprintf('%s::%s: no non-NA numeric data\n', this.fn, fn.name))
  }
} # end function stats.to.stdout

unsparse.stats.to.stdout <- function(
  data.nonNA,    # numeric array minus NAs, no other requirements (?)
  data.nonNA.n,  # its length
  data.raw.n,    # length of data from which data.nonNA was derived
  sig.digs=3,    # significant digits for numeric fields
  title=''       # one line identifying data source
) {
  # TODO: test arguments!

  # create strings for use in output
  # double-sprintf-ing to set precision by constant: cool or brittle?
  stat.template <- sprintf('%%.%ig', sig.digs)
  # use these in function=subtitle.stats as sprintf inputs
  sum.template <- sprintf('sum=%s', stat.template)
  max.template <- sprintf('max=%s', stat.template)
  mea.template <- sprintf('mean=%s', stat.template)
  med.template <- sprintf('med=%s', stat.template)  # median==2nd quartile
  min.template <- sprintf('min=%s', stat.template)
  q1.template <- sprintf('q1=%s', stat.template)    # 1st quartile
  q3.template <- sprintf('q3=%s', stat.template)    # 3rd quartile

  cells.str <- sprintf('cells=%i', data.raw.n)
  obs.str <- sprintf('obs=%i', data.nonNA.n)
  min.str <- sprintf(min.template, min(data.nonNA))
  q1.str <- sprintf(q1.template, q1(data.nonNA))
  mea.str <- sprintf(mea.template, mean(data.nonNA))
  med.str <- sprintf(med.template, median(data.nonNA))
  q3.str <- sprintf(q3.template, q3(data.nonNA))
  max.str <- sprintf(max.template, max(data.nonNA))
  sum.str <- sprintf(sum.template, sum(data.nonNA))

  # at last: output!
  cat(sprintf('%s\n', title))
  cat(sprintf('\t%s\n', cells.str))
  cat(sprintf('\t%s\n', obs.str))
  # 6-number summary
  cat(sprintf('\t%s\n', min.str))
  cat(sprintf('\t%s\n', q1.str))
  cat(sprintf('\t%s\n', med.str))
  cat(sprintf('\t%s\n', mea.str))
  cat(sprintf('\t%s\n', q3.str))
  cat(sprintf('\t%s\n', max.str))
  cat(sprintf('\t%s\n', sum.str))
} # end function unsparse.stats.to.stdout

netCDF.stats.to.stdout.by.timestep <- function(
  netcdf.fp, # /path/to/netcdf/file, can be relative or FQ
  data.var.name,   # name of data variable (datavar) of interest
  time.dim.name='time', # of time dimension in datavar args
  stats.precision=3 # sigdigs to use for min, median, max of obs
) {

  # TODO: test arguments!

#  # start debug
#  cat(sprintf(
#    '%s: netcdf.fp==%s, data.var.name==%s, time.dim.name=%s\n',
#    this.fn, netcdf.fp, data.var.name, time.dim.name))
#  system(sprintf('ls -alth %s', netcdf.fp))
#  system(sprintf('ncdump -h %s', netcdf.fp))
#  #   end debug

  # needed to parse netCDF
  library(ncdf4)

  # open netCDF file, uncautiously
  # NOTE: you must assign when you nc_open!
  netcdf.file <- ncdf4::nc_open(
    filename=netcdf.fp,
    write=FALSE,    # will only read below
    readunlim=TRUE) # it's a small file? TODO: read by timestep!

  # Find the index of the datavar of interest
  # (in the list of all non-coordinate variables).
  netcdf.file.vars.n <- netcdf.file$nvars
  data.var.index <- -1 # an invalid index
  for (i in 1:netcdf.file.vars.n) {
    netcdf.file.var <- netcdf.file$var[[i]]
    if (netcdf.file.var$name == data.var.name) {
      data.var.index <- i
    }
  }
  if (data.var.index == -1) {
    stop(sprintf('%s: ERROR: failed to find data.var.index\n', this.fn))
  }

#  # start debug
#  cat(sprintf('%s: data.var.name==%s has var posn=%i and size==\n',
#    this.fn, data.var.name, data.var.index))
#  print(dim(data.var.data))
#  #   end debug

  # can only compute n.timesteps once we have the datavar's dims ...
  data.var <- netcdf.file$var[[data.var.index]]
  data.var.dims <- data.var$size
  data.var.dims.n <- data.var$ndims
  # ... and particularly the position of dimension$name==time.dim.name
  time.dim.index <- -1 # an invalid index
  for (i in 1:data.var.dims.n) {
    data.var.dim <- data.var$dim[[i]]
    if (data.var.dim$name == time.dim.name) {
      time.dim.index <- i
    }
  }
  if (time.dim.index == -1) {
    stop(sprintf("%s: ERROR: failed to find time.dim.index for time.dim.name='%s'\n",
      this.fn, time.dim.name))
  } # else
  n.timesteps <- data.var.dims[time.dim.index]

#  # start debug
#  cat(sprintf('%s: time.dim.name==%s has dim posn=%i and size=%i\n',
#    this.fn, time.dim.name, time.dim.index, n.timesteps))
#  #   end debug

# TODO: ncdf4 bug?
#  # compute read vectors for use in `ncvar_get`: read all timestep values
#  vec.start.template <- rep(1, data.var.dims.n)   # ASSERT: constant
##  vec.count.template <- rep(-1, data.var.dims.n)  # ASSERT: constant
#  # see bug below, try instead
#  vec.count.template <- data.var.dims             # ASSERT: constant

  # iterate over the timesteps
  for (i in 1:n.timesteps) {

#    vec.start <- vec.start.template
#    vec.start[time.dim.index] <- i # only get the i'th timestep
#    vec.count <- vec.count.template
#    vec.count[time.dim.index] <- i # only get the i'th timestep
#
#    # start debug
#    cat(sprintf('%s: vec.start==\n', this.fn))
#    print(vec.start)
#    cat(sprintf('%s: vec.count==\n', this.fn))
#    print(vec.count)
#    #   end debug

    data.var.data <- ncdf4::ncvar_get(
      nc=netcdf.file,
      varid=data.var.name
# TODO: {debug, bug report} why this fails
#      varid=data.var.name,
#      start=vec.start,
#      count=vec.count
    )
# each loop call increases time dimension! e.g.,
# > netCDF.stats.to.stdout.r: dim(data.var.data)==
# > [1] 144  96
# ...
# > netCDF.stats.to.stdout.r: dim(data.var.data)==
# > [1] 144  96   2
# ...
# > netCDF.stats.to.stdout.r: dim(data.var.data)==
# > [1] 144  96   3
    # workaround: read unlimited (above), then just take the slice of interest
    # TODO: handle dimensions more generically
    data.var.data.dim.len <- length(dim(data.var.data))
    if        (data.var.data.dim.len == 3) {
      data.var.timestep <- data.var.data[,,i]
    } else if (data.var.data.dim.len == 4) {
      data.var.timestep <- data.var.data[,,,i]
    }
                                  
#    # start debug
#    cat(sprintf('%s: dim(data.var.timestep)==\n', this.fn))
#    print(dim(data.var.timestep))
#    cat(sprintf('%s: summary(data.var.timestep)==\n', this.fn))
#    print(summary(c(data.var.timestep))) # collapse its structure
#    #   end debug

    if (is.numeric(data.var.timestep) && sum(!is.na(data.var.timestep))) {
#      unsparse.data <- data.var.timestep[!is.na(data.var.timestep)]
      # collapse its structure
      unsparse.data <- c(data.var.timestep[!is.na(data.var.timestep)])
      obs.n <- length(unsparse.data)
      if (obs.n > 0) {
        unsparse.stats.to.stdout(
          data.nonNA=unsparse.data,
          data.nonNA.n=obs.n,
          data.raw.n=length(data.var.timestep),
          sig.digs=stats.precision,
          title=sprintf('For %s datavar=%s, timestep=%i of %i', netcdf.fp, data.var.name, i, n.timesteps)
        )
      } else {
        cat(sprintf('%s: %s data.var=%s has no non-NA data',
          this.fn, data.var.name, netcdf.fp))
      }
    } else {
      cat(sprintf('%s: %s data.var=%s has no numeric non-NA data',
        this.fn, data.var.name, netcdf.fp))
    } # end if (is.numeric(data.var.timestep) && sum(!is.na(data.var.timestep)))

    rm( # debugging why output is same for each timestep
#      data.var.data,
      data.var.timestep,
      unsparse.data)

  } # end for (i in 1:n.timesteps)

  # teardown
  ncdf4::nc_close(netcdf.file)
  rm(this.fn) # hopefully prevents overwriting `this.fn` in prior namespaces
} # end function netCDF.stats.to.stdout.by.timestep

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

# if this is called as a script, provide a main(): see
# https://stat.ethz.ch/pipermail/r-help/2012-September/323551.html
# https://stat.ethz.ch/pipermail/r-help/2012-September/323559.html
if (!interactive()) {

# start debug
#  cat(sprintf('%s: interactive()==TRUE\n', this.fn))
#   end debug
  
  # TODO: fix `strsplit` regexp below to make this unnecessary
  library(stringr)

  # pass named arguments: var above separated by '='

  args <- commandArgs(TRUE)
  # args is now a list of character vectors
  # First check to see if any arguments were passed, then evaluate each argument:
  # assign val (RHS) to key (LHS) for arguments of the (required) form 'key=val'
  if (length(args)==0) {
    cat(sprintf('%s: no arguments supplied, exiting\n', this.fn))
#    q(status=1) # KLUDGE:
# Currently this is not seeing arguments when called from Rscript,
# so this exit also exits the caller :-(    
  } else {
  # simple positional args work
  # TODO: also support positional usage
  #  netcdf.fp <- args[1]
  #  data.var.name <- args[2]
    # TODO: test arg length: 2 is required!

# start debug
#    cat(sprintf('%s: got length(args)==%i\n', this.fn, length(args)))
#   end debug

    for (i in 1:length(args)) {
#       eval(parse(text=args[[i]]))
      # `eval(parse())` is unsafe and requires awkward quoting:
      # e.g., of the following (bash) commandlines

      # - Rscript ./netCDF.stats.to.stdout.r netcdf.fp="GEIA_N2O_oceanic.nc" data.var.name="emi_n2o"
      #   fails

      # + Rscript ./netCDF.stats.to.stdout.r 'netcdf.fp="GEIA_N2O_oceanic.nc"' 'data.var.name="emi_n2o"'
      #   succeeds

      # so instead
      # TODO: use package `optparse` or `getopt`
      args.keyval.list <-
        strsplit(as.character(parse(text=args[[i]])),
          split='[[:blank:]]*<-|=[[:blank:]]*', fixed=FALSE)
  #                            split='[ \t]*<-|=[ \t]*', fixed=FALSE)
      args.keyval.vec <- unlist(args.keyval.list, recursive=FALSE, use.names=FALSE)
      # TODO: test vector elements!
      # Neither wants to remove all whitespace from around arguments :-( so
      args.key <- str_trim(args.keyval.vec[1], side="both")
      args.val <- str_trim(args.keyval.vec[2], side="both")

# start debug
#       cat(sprintf('%s: got\n', this.fn))
#       cat('\targs.keyval.list==\n')
#       print(args.keyval.list)
#       cat('\targs.keyval.vec==\n')
#       print(args.keyval.vec)
#       cat(sprintf('\targs.key==%s\n', args.key))
#       cat(sprintf('\targs.val==%s\n', args.val))
#   end debug

      # A real case statement would be nice to have
      if        (args.key == 'netcdf.fp') {
        netcdf.fp <- args.val
      } else if (args.key == 'data.var.name') {
        data.var.name <- args.val
      } else {
        stop(sprintf("unknown argument='%s'", args.key))
        # TODO: show usage
        q(status=1) # exit with error
      }
    } # end for loop over arguments

    # payload!
    netCDF.stats.to.stdout(netcdf.fp, data.var.name)

  } # end if testing number of arguments
} # end if (!interactive())