-
Notifications
You must be signed in to change notification settings - Fork 2
/
output-extract.R
executable file
·271 lines (222 loc) · 11.6 KB
/
output-extract.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
#!/usr/bin/env Rscript
# Copyright 2013
# Mostly Helene Genet & Colin Tucker, with some touchups by Tobey Carman
# Spatial Ecology Lab
# University of Alaska Fairbanks
# This script is designed to read the outputs from a single site run of
# dvm-dos-tem and generate a whole bunch of csv files. These csvs can then be
# plotted using plotting-output.R
library(ncdf4)
library(argparse)
d <- paste('Reads a bunch of cmt***_***-**.nc files that are',
'generated by a run of dvm-dos-tem in single site mode',
'and generates csv files for the specified variables.', sep=' ')
parser <- ArgumentParser(description=d)
# Looks like some of the fancier options like the
# formatter_class are not available yet...
h <- paste('A path (relative or absolute) to a folder containing ',
' some cmt***_***-**.nc files.', sep=' ')
parser$add_argument('--nc-files-dir', required=TRUE,
metavar='PATH', help=h)
h <- paste('Name of directory for storing the generated file(s)',
'Defaults to making a subdirectory withing the',
'nc-files-dir named "output-extract-generated-files"', sep=' ')
parser$add_argument('--generated-files-dir',
default='output-extract-generated-files', metavar='DIRNAME',
help=h)
parser$add_argument('--run-mode', default='eq', metavar='M', nargs='+',
#choices=('eq','sp','tr','sc','all'), # broken?
help='Which run mode(s) you are processing. (default: eq)')
parser$add_argument('--timestep', default='yearly', metavar='T', nargs='+',
help='Which timestep you are processing. (default: yearly)')
# NOTE: It it totally possible to define another option here that can let
# the user select a different 'suite' of variables to output...
# This line does the work of processing all the command line args according to
# the rules we define above...
args <- parser$parse_args()
# Now all the options are available through the args object like this:
# args$whatever_option
#
# NOTE: hyphens in the option name are converted to underscored in the variable!
#print(args)
#parser$print_help()
# Move us into the directory with all the netcdf files to ingest...
print("Changing working directory to:")
print(args$nc_files_dir)
setwd(args$nc_files_dir)
# Create a sub directory to store the output text files
dir.create(paste(getwd(), '/', args$generated_files_dir, sep=''), recursive=TRUE)
# Figure out what run mode(s) to process...
run <- args$run_mode
# Figure out what timestep(s) to process...
timestep <- c(args$timestep)
# Specify all variables that should be selected/processed...
variable <- c('NUPTAKEL','NUPTAKESALL','NMOBILALL','NMOBIL','NMOBILALL',
'NRESOBALL','NRESORB','VEGNSUM','RH','NMITKSOIL','NETNMIN',
'AVLNINPUT','AVLNLOST','ORGNLOST','LTRFALNALL','AVLNSUM','NEP',
'NPPALL','LTRFALCALL','VEGCSUM','GPPALL','SOMCSHLW','SOMCDEEP',
'SOMCMINEA','SOMCMINEB','SOMCMINEC','RHMOIST','RHQ10',
'SOILLTRFCN','LAI','SNOWFALL','ALD','EETTOTAL','PETTOTAL','TAIR',
'RAINFALL','SOILTAVE','SOILVWC','RZTHAWPCT')
# All list containing all the variables present in a valid cmtbgc_***-eq.nc file
listdim <- c('CHTID','YEAR','MONTH','CMTTYPE','VEGAGE','IFWOODY','IFDECIWOODY',
'IFPERENIAL','NONVASCULAR','VEGCOV','LAI','FPC','ROOTFRAC','FLEAF',
'FFOLIAGE','SNWAGE','SNWTHICK','SNWDENSE','SNWRHO','SNWEXTRAMASS',
'SOILLAYERNO','MOSSLAYERNO','SHLWLAYERNO','DEEPLAYERNO',
'MINELAYERNO','SOILTHICK','MOSSTHICK','SHLWTHICK','DEEPTHICK',
'MINEATHICK','MINEBTHICK','MINECTHICK','SOILZ','SOILDZ','SOILTYPE',
'SOILPORO','SOILTEXTURE','SOILRTFRAC')
# All list containing all the variables present in a valid cmtenv_***-eq.nc file
listenv <- c('CHTID','ERRORID','YEAR','MONTH','DAY','CO2','TAIR','NIRR','PREC',
'VAPO','SVP','VPD','PAR','RAINFALL','SNOWFALL','PARDOWN',
'PARABSORB','SWDOWN','SWINTER','RAININTER','SNOWINTER','EETTOTAL',
'PETTOTAL','CANOPYRAIN','CANOPYSNOW','CANOPYRC','CANOPYCC',
'CANOPYBTRAN','CANOPYM_PPFD','CANOPYM_VPD','CANOPYSWREFL',
'CANOPYSWTHFL','CANOPYEVAP','CANOPYTRAN','CANOPYPEVAP',
'CANOPYPTRAN','CANOPYSUBLIM','CANOPYRDRIP','CANOPYRTHFL',
'CANOPYSDRIP','CANOPYSTHFL','SNWLNUM','SNWTHICK','SNWDENSITY',
'SNWEXTRAMASS','SNWDZ','SNWAGE','SNWRHO','SNWPOR','SNWWE','SNWT',
'SNWWESUM','SNWTAVE','SNWSWREFL','SNWSUBLIM','SOILICESUM',
'SOILLIQSUM','SOILVWCSHLW','SOILVWCDEEP','SOILVWCMINEA',
'SOILVWCMINEB','SOILVWCMINEC','SOILTAVE','SOILTSHLW','SOILTDEEP',
'SOILTMINEA','SOILTMINEB','SOILTMINEC','SOILTEM','SOILLIQ',
'SOILICE','SOILVWC','SOILLWC','SOILIWC','FRONTZ','FRONTTYPE',
'WATERTABLE','PERMAFROST','ALD','ALC','RZGROWSTART','RZGROWEND',
'RZTEM','RZDEGDAY','RZTHAWPCT','SOILSWREFL','SOILEVAP','SOILPEVAP',
'RUNOFF','DRINAGE')
listbgc <- c('CHTID','ERRORID','YEAR','MONTH','VEGCSUM','VEGCPART','VEGNSUM',
'VEGNLAB','VEGNSTRNSUM','VEGNSTRNPART','VEGCDEAD','VEGNDEAD',
'WDEBRISC','WDEBRISN','GPPFTEMP','GPPGV','GPPFNA','GPPFCA','RAQ10',
'RMKR','INGPPALL','INGPP','INNPPALL','INNPP','GPPALL','GPP',
'NPPALL','NPP','RMALL','RM','RGALL','RG','LTRFALCALL','LTRFALC',
'LTRFALNALL','LTRFALN','INNUPTAKE','NROOTEXTRACT','NUPTAKEL',
'NUPTAKESALL','NUPTAKES','NMOBILALL','NMOBIL','NRESOBALL','NRESORB',
'RAWC','SOMA','SOMPR','SOMCR','ORGN','AVLN','SOMCSHLW','SOMCDEEP',
'SOMCMINEA','SOMCMINEB','SOMCMINEC','RAWCSUM','SOMASUM','SOMPRSUM',
'SOMCRSUM','ORGNSUM','AVLNSUM','RH','NMITKSOIL','RHMOIST','RHQ10',
'SOILLTRFCN','NEP','NETNMIN','ORGCINPUT','ORGNINPUT','AVLNINPUT',
'DOCLOST','AVLNLOST','ORGNLOST','BURNTHICK','BURNSOIC','BURNVEGC',
'BURNSOIN','BURNVEGN','BURNRETAINC','BURNRETAINN')
# loop over each set of run phases...
for (a in 1:length(run)) { # (eq, sp, sc, etc..), specified in file name?
# and in each one, loop over all the timesteps (), specified in file name?
for (b in 1:length(timestep)) {
# in each file, loop over all the variables..
for (c in 1:length(variable)) {
varname <- variable[c]
# check the lists of variables to see which file 'type' holds the variable
test1 <- (varname %in% listdim)
test2 <- (varname %in% listbgc)
test3 <- (varname %in% listenv)
# set the 'type' of the file
typename <- ifelse(test1 =='TRUE','dim',
ifelse(test2 == 'TRUE','bgc',
ifelse(test3 == 'TRUE','env','Variable unknown')))
if (typename == 'Variable unknown') print(typename)
# figure out what timestep this variable is represented at
stepname <- ifelse(timestep[b] == 'daily','dly',
ifelse(timestep[b] == 'monthly','mly',
ifelse(timestep[b] == 'yearly','yly','Time step unknown')))
if (stepname == 'Time step unknown') print(stepname)
# figure out what stage we are working on ('eq', 'sp', etc..)
runname <- run[a]
# Now that we know which file to open, open it and get the data
# E.g.: 'cmtbgc_yly-eq.nc'
fname <- paste('./cmt',typename,'_',stepname,'-',runname,'.nc',sep='')
out <- nc_open(fname)#, verbose=TRUE)
#identify the rank of the variable and the time-related parameters
for (i in 1:out$nvars) {
if (varname == out$var[[i]]$name) rk <- i
if (out$var[[i]]$name == 'YEAR') rkyear <- i
if (out$var[[i]]$name == 'MONTH') rkmonth <- i
if (typename == 'env' & out$var[[i]]$name == 'DAY') rkday <- i
}
# starting the file by copying the time-related parameters
#for (i in 1:out$nvars) print (paste("var",i,": ",out$var[[i]]$name))
year <- data.frame(ncvar_get(out,
out$var[[rkyear]],
start=1,
count=out$var[[rkyear]]$dim[[1]]$len))
month <- data.frame(ncvar_get(out,
out$var[[rkmonth]],
start=1,
count=out$var[[rkmonth]]$dim[[1]]$len))
if (typename == 'env') {
day <- data.frame(ncvar_get(out,
out$var[[rkday]],
start=1,
count=out$var[[rkday]]$dim[[1]]$len))
}
if (typename == 'dim' | typename == 'bgc') {
file <- data.frame(year,month)
names(file) <- c('year','month')
}
if (typename == 'env') {
file <- data.frame(year,month,day)
names(file) <- c('year','month','day')
}
#extraction for variables with one dimension
if (out$var[[rk]]$ndims == 1) {
for (i in 1:out$ndims) {
if (out$var[[rk]]$dim[[1]]$name == out$dim[[i]]$name) {
rkdim1 <- i
}
}
var <- data.frame(ncvar_get(out,
out$var[[rk]],
start=1,
count=out$dim[[rkdim1]]$len))
names(var) <- varname
file <- data.frame(file,var)
}
#extraction for variables with two dimensions
if (out$var[[rk]]$ndims == 2) {
for (i in 1:out$ndims) {
if (out$var[[rk]]$dim[[1]]$name == out$dim[[i]]$name) {
rkdim1 <- i
}
if (out$var[[rk]]$dim[[2]]$name == out$dim[[i]]$name) {
rkdim2 <- i
}
}
for(i in 1:out$dim[[rkdim1]]$len) {
var <- data.frame(ncvar_get(out,
out$var[[rk]],
start=c(i,1),
count=c(1,out$dim[[rkdim2]]$len)))
dimname <- out$dim[[rkdim1]]$name
names(var)<-paste(varname,"_",dimname,i,sep="")
file <- data.frame(file,var)
}
}
#extraction for variables with three dimensions
if (out$var[[rk]]$ndims == 3) {
for (i in 1:out$ndims) {
if (out$var[[rk]]$dim[[1]]$name == out$dim[[i]]$name)
rkdim1 <- i
if (out$var[[rk]]$dim[[2]]$name == out$dim[[i]]$name)
rkdim2 <- i
if (out$var[[rk]]$dim[[3]]$name == out$dim[[i]]$name)
rkdim3 <- i
}
for(i in 1:out$dim[[rkdim2]]$len) {
for(j in 1:out$dim[[rkdim1]]$len) {
var <- data.frame(ncvar_get(out,
out$var[[rk]],
start=c(j,i,1),
count=c(1,1,out$dim[[rkdim3]]$len)))
dimname1 <- out$dim[[rkdim1]]$name
dimname2 <- out$dim[[rkdim2]]$name
names(var)<-paste(varname,"_",dimname2,i,dimname1,j,sep="")
file <- data.frame(file,var)
}
}
}
ofname <- paste(args$generated_files_dir, "/", typename, "_",
stepname,"_", varname, "_", runname, ".csv", sep="")
print(cat("Writing", ofname, labels='')) # Not sure how to get rid of
# NULL that is printed on each line?
write.csv(file, file=ofname)
}
}
}