1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/ameriflux/04.read_ascii.ncl Mon Jan 26 22:08:20 2009 -0500
1.3 @@ -0,0 +1,391 @@
1.4 +;----------------------------------------------------------------------
1.5 +; change Month to yyyymm
1.6 +; add Month to output
1.7 +; add lat, lon to output
1.8 +; add year to output
1.9 +;
1.10 +; This example reads an ASCII file that is formatted a specific way, and
1.11 +; writes out the results to a netCDF file.
1.12 +;
1.13 +; The first line in the ASCII file must be a header, with each field
1.14 +; separated by a single character delimiter (like a ","). The rest of
1.15 +; the file must be such that each row contains all fields, each
1.16 +; separated by the designated delimiter.
1.17 +;
1.18 +; The fields can be integer, float, double, character, or string.
1.19 +; String fields cannot be written to a netCDF file. They have to
1.20 +; be read in as character arrays and written out that way.
1.21 +;----------------------------------------------------------------------
1.22 +
1.23 +;----------------------------------------------------------------------
1.24 +; This function returns the index locations of the given delimiter
1.25 +; in a row or several rows of strings.
1.26 +;----------------------------------------------------------------------
1.27 +function delim_indices(strings,nfields,delimiter)
1.28 +local cstrings, cdelim
1.29 +begin
1.30 + nrows = dimsizes(strings)
1.31 +;
1.32 +; Handle special case if we only have one string. Make sure it
1.33 +; is put into a 2D array.
1.34 +;
1.35 + if(nrows.eq.1) then
1.36 + cstrings = new((/1,strlen(strings)+1/),character)
1.37 + end if
1.38 +
1.39 + cstrings = stringtochar(strings) ; Convert to characters.
1.40 + cdelim = stringtochar(delimiter) ; Convert delimiter to character.
1.41 +;
1.42 +; Som error checking here. Make sure delimiter is one character.
1.43 +;
1.44 + nc = dimsizes(cdelim)
1.45 + rank = dimsizes(nc)
1.46 + if(rank.ne.1.or.(rank.eq.1.and.nc.ne.2)) then
1.47 + print("delim_indices: fatal: the delimiter you've selected")
1.48 + print("must be a single character. Can't continue.")
1.49 + exit
1.50 + end if
1.51 +
1.52 +;
1.53 +; Create array to hold indices of delimiter locations, and then loop
1.54 +; through each row and find all the delimiters. Make sure each row has
1.55 +; the correct number of delimiters.
1.56 +;
1.57 + ndelims = nfields-1
1.58 + cindices = new((/nrows,ndelims/),integer)
1.59 + do i = 0, nrows-1
1.60 + ii = ind(cstrings(i,:).eq.cdelim(0))
1.61 +;
1.62 +; Make sure there were delimiters on this row. If not, we just quit.
1.63 +; This could probably be modified to do this more gracefully.
1.64 +;
1.65 + if(any(ismissing(ii))) then
1.66 + print("delim_indices: fatal: I didn't find any delimiters")
1.67 + print("('" + delimiter + "') on row " + i + ". Can't continue.")
1.68 + exit
1.69 + end if
1.70 + if(dimsizes(ii).ne.ndelims) then
1.71 + print("delim_indices: fatal: I expected to find " + ndelims)
1.72 + print("delimiters on row " + i + ". Instead, I found " + dimsizes(ii) + ".")
1.73 + print("Can't continue.")
1.74 + exit
1.75 + end if
1.76 +
1.77 + cindices(i,:) = ii
1.78 +
1.79 + delete(ii) ; For next time through loop
1.80 + end do
1.81 +
1.82 + return(cindices)
1.83 +end
1.84 +
1.85 +;----------------------------------------------------------------------
1.86 +; This function reads in a particular field from a string array,
1.87 +; given the field number to read (fields start at #1 and go to #nfield),
1.88 +; and the indices of the delimiters.
1.89 +;
1.90 +; It returns either an integer, float, double, character, or a string,
1.91 +; depending on the input flag "return_type".
1.92 +;----------------------------------------------------------------------
1.93 +function read_field(strings,ifield,indices,return_type)
1.94 +local nstring, cstrings, nf, tmp_str
1.95 +begin
1.96 + nrows = dimsizes(strings)
1.97 +;
1.98 +; Handle special case if we only have one string. Make sure it
1.99 +; is put into a 2D array.
1.100 +;
1.101 + if(nrows.eq.1) then
1.102 + cstrings = new((/1,strlen(strings)+1/),character)
1.103 + end if
1.104 +
1.105 + cstrings = stringtochar(strings)
1.106 + nf = dimsizes(indices(0,:))+1 ; indices is nrows x (nfields-1)
1.107 +
1.108 +;
1.109 +; Error checking. Make sure user has entered a valid field.
1.110 +;
1.111 + if(ifield.le.0.or.ifield.gt.nf) then
1.112 + print("read_field: fatal: you've selected a field that is")
1.113 + print("out-of-range of the number of fields that you have (" + nf + ").")
1.114 + exit
1.115 + end if
1.116 +
1.117 +;
1.118 +; Set up array to return. For string, int, float, or double arrays,
1.119 +; we don't have to do anything special. For character arrays,
1.120 +; however, we do.
1.121 +;
1.122 + if(return_type.ne."character") then
1.123 + return_array = new(nrows,return_type)
1.124 + else
1.125 +;
1.126 +; We don't know what the biggest character array is at this point, so
1.127 +; make it bigger than necessary, and then resize later as necessary.
1.128 +;
1.129 + tmp_return_array = new((/nrows,dimsizes(cstrings(0,:))/),"character")
1.130 +
1.131 + max_len = 0 ; Use to keep track of max lengths of strings.
1.132 + end if
1.133 +
1.134 + do i = 0,nrows-1
1.135 +;
1.136 +; Special case of first field in row.
1.137 +;
1.138 + if(ifield.eq.1) then
1.139 + ibeg = 0
1.140 + iend = indices(i,ifield-1)-1
1.141 + else
1.142 +;
1.143 +; Special case of first field in row.
1.144 +;
1.145 + if(ifield.eq.nf) then
1.146 + ibeg = indices(i,ifield-2)+1
1.147 + iend = dimsizes(cstrings(i,:))-1
1.148 +;
1.149 +; Any field between first and last field.
1.150 +;
1.151 + else
1.152 + ibeg = indices(i,ifield-2)+1
1.153 + iend = indices(i,ifield-1)-1
1.154 + end if
1.155 + end if
1.156 +;
1.157 +; Here's the code that pulls off the correct string, and converts it
1.158 +; to float if desired.
1.159 +;
1.160 + if(return_type.eq."integer") then
1.161 + return_array(i) = stringtointeger(chartostring(cstrings(i,ibeg:iend)))
1.162 + end if
1.163 + if(return_type.eq."float") then
1.164 + return_array(i) = stringtofloat(chartostring(cstrings(i,ibeg:iend)))
1.165 + end if
1.166 + if(return_type.eq."double") then
1.167 + return_array(i) = stringtodouble(chartostring(cstrings(i,ibeg:iend)))
1.168 + end if
1.169 + if(return_type.eq."string") then
1.170 + return_array(i) = chartostring(cstrings(i,ibeg:iend))
1.171 + end if
1.172 + if(return_type.eq."character") then
1.173 + if( (iend-ibeg+1) .gt. max_len) then
1.174 + max_len = iend-ibeg+1
1.175 + end if
1.176 + tmp_return_array(i,0:iend-ibeg) = cstrings(i,ibeg:iend)
1.177 + end if
1.178 + end do
1.179 +
1.180 + if(return_type.eq."character") then
1.181 + return_array = new((/nrows,max_len/),"character")
1.182 + return_array = tmp_return_array(:,0:max_len-1)
1.183 + end if
1.184 +
1.185 + return(return_array)
1.186 +end
1.187 +
1.188 +
1.189 +;----------------------------------------------------------------------
1.190 +; This function reads in string fields only to get the maximum string
1.191 +; length.
1.192 +;----------------------------------------------------------------------
1.193 +function get_maxlen(strings,ifield,indices)
1.194 +local nstring, cstrings, nf, tmp_str
1.195 +begin
1.196 + nrows = dimsizes(strings)
1.197 +;
1.198 +; Handle special case if we only have one string. Make sure it
1.199 +; is put into a 2D array.
1.200 +;
1.201 + if(nrows.eq.1) then
1.202 + cstrings = new((/1,strlen(strings)+1/),character)
1.203 + end if
1.204 +
1.205 + cstrings = stringtochar(strings)
1.206 + nf = dimsizes(indices(0,:))+1 ; indices is nrows x (nfields-1)
1.207 +
1.208 +;
1.209 +; Error checking. Make sure user has entered a valid field.
1.210 +;
1.211 + if(ifield.le.0.or.ifield.gt.nf) then
1.212 + print("read_field: fatal: you've selected a field that is")
1.213 + print("out-of-range of the number of fields that you have (" + nf + ").")
1.214 + exit
1.215 + end if
1.216 +;
1.217 +; We don't know what the biggest character array is at this point, so
1.218 +; make it bigger than necessary, and then resize later as necessary.
1.219 +;
1.220 + tmp_return_array = new((/nrows,dimsizes(cstrings(0,:))/),"character")
1.221 +
1.222 + max_len = 0 ; Use to keep track of max lengths of strings.
1.223 +
1.224 + do i = 0,nrows-1
1.225 +;
1.226 +; Special case of first field in row.
1.227 +;
1.228 + if(ifield.eq.1) then
1.229 + ibeg = 0
1.230 + iend = indices(i,ifield-1)-1
1.231 + else
1.232 +;
1.233 +; Special case of first field in row.
1.234 +;
1.235 + if(ifield.eq.nf) then
1.236 + ibeg = indices(i,ifield-2)+1
1.237 + iend = dimsizes(cstrings(i,:))-1
1.238 +;
1.239 +; Any field between first and last field.
1.240 +;
1.241 + else
1.242 + ibeg = indices(i,ifield-2)+1
1.243 + iend = indices(i,ifield-1)-1
1.244 + end if
1.245 + end if
1.246 + if( (iend-ibeg+1) .gt. max_len) then
1.247 + max_len = iend-ibeg+1
1.248 + end if
1.249 + end do
1.250 +
1.251 + return(max_len)
1.252 +end
1.253 +
1.254 +;----------------------------------------------------------------------
1.255 +; Main code.
1.256 +;----------------------------------------------------------------------
1.257 +begin
1.258 +
1.259 +;###############################################################
1.260 +; Set up defaults. We are hard-coding here..
1.261 +
1.262 + year = 1991
1.263 + station = "USHa1"
1.264 + lat = 42.5378
1.265 + lon = -72.1715 + 360.
1.266 +
1.267 + nfields = 30 ; # of fields
1.268 + delimiter = "," ; field delimiter
1.269 +
1.270 + filename = station+year+"_L4_m.txt" ; ASCII" file to read.
1.271 + cdf_file = station+year+"_L4_m.nc" ; netCDF file to write.
1.272 +
1.273 + if(isfilepresent(cdf_file))
1.274 + print("Warning: '" + cdf_file + "' exists. Will remove it.")
1.275 + system("/bin/rm " + cdf_file)
1.276 + end if
1.277 +
1.278 +; In this case, fields #1-#2 are integers,
1.279 +; and the rest of the fields are floats.
1.280 +
1.281 + var_types = new(nfields,string)
1.282 + var_types = "float" ; Most are floats.
1.283 + var_types(0:1) = "integer"
1.284 +
1.285 +;#####################################################################
1.286 +
1.287 +; Read in data as strings. This will create a string array that has the
1.288 +; same number of strings as there are rows in the file. We will then need
1.289 +; to parse each string later.
1.290 +
1.291 + read_data = asciiread(filename,-1,"string")
1.292 +
1.293 + header = read_data(0) ; Header. Use for variable names.
1.294 + data = read_data(1:) ; Get rid of first line which is a header.
1.295 + nmonth = dimsizes(data) ; Number of rows == number of month.
1.296 +
1.297 +; Read in locations of delimiters in each string row.
1.298 +
1.299 + hindices = delim_indices(header,nfields,delimiter) ; header row
1.300 + dindices = delim_indices(data,nfields,delimiter) ; rest of file
1.301 +
1.302 +; Read in the field names which will become variable names on
1.303 +; the netCDF file.
1.304 +
1.305 + var_names = new(nfields,string)
1.306 +
1.307 + do i=0,nfields-1
1.308 + var_names(i) = read_field(header,i+1,hindices,"string")
1.309 + end do
1.310 +
1.311 +;-------------------------------------------------------------------
1.312 +; Write out this netCDF file efficiently so it will be faster.
1.313 +; Try to predefine everything before you write to it.
1.314 +
1.315 + f = addfile(cdf_file,"c")
1.316 + setfileoption(f,"DefineMode",True) ; Enter predefine phase.
1.317 +
1.318 +; Write global attributes to file. It's okay to do this before
1.319 +; predefining the file's variables. We are still in "define" mode.
1.320 +
1.321 + fAtt = True
1.322 + fAtt@description = "Data read in from " + filename + " ASCII file."
1.323 + fAtt@creation_date = systemfunc ("date")
1.324 + fileattdef( f, fAtt )
1.325 +
1.326 +; Write dimension names to file.
1.327 +
1.328 + dim_names = (/ "year", "month" /)
1.329 + dim_sizes = (/ -1 , nmonth /)
1.330 + dimUnlim = (/ True , False /)
1.331 + filedimdef( f, dim_names, dim_sizes, dimUnlim )
1.332 +
1.333 + filedimdef( f, "lat", 1, False )
1.334 + filedimdef( f, "lon", 1, False )
1.335 +
1.336 +; Define each variable on the file.
1.337 +
1.338 + filevardef( f, "year", "integer", "year" )
1.339 + filevardef( f, "lat" , "float" , "lat" )
1.340 + filevardef( f, "lon" , "float" , "lon" )
1.341 +
1.342 + do i=0,nfields-1
1.343 + filevardef(f, var_names(i), var_types(i), dim_names)
1.344 + end do
1.345 +;-----------------------------------------------------------------
1.346 +
1.347 +; Loop through each field, read the values for that field, print
1.348 +; information about the variable, and then write it to the netCDF file.
1.349 +
1.350 + do i=0,nfields-1
1.351 + ifield = i+1 ; Fields start at #1, not #0.
1.352 +
1.353 + tmp_data = new((/1,nmonth/),var_types(i))
1.354 +
1.355 + if (i.le.1) then
1.356 + tmp_data@_FillValue = -999
1.357 + else
1.358 + tmp_data@_FillValue = -9999.00
1.359 + end if
1.360 +
1.361 + tmp_data(0,:) = read_field(data,ifield,dindices,var_types(i))
1.362 +
1.363 +; change Month to yyyymm
1.364 +
1.365 + if (i.eq.0) then
1.366 + tmp_data(0,:) = tmp_data(0,:) + year*100
1.367 + end if
1.368 +
1.369 +; Print some info about the variable.
1.370 +
1.371 +; print("")
1.372 +; print("Writing variable '" + var_names(i) + "' (field #" + ifield + ").")
1.373 +; print("Type is " + var_types(i) + ".")
1.374 +; print("min/max = " + min(tmp_data) + "/" + max(tmp_data))
1.375 +
1.376 +; if(any(ismissing(tmp_data))) then
1.377 +; print("This variable does contain missing values.")
1.378 +; else
1.379 +; print("This variable doesn't contain missing values.")
1.380 +; end if
1.381 +
1.382 +; write variable to file
1.383 +
1.384 + f->$var_names(i)$ = tmp_data ; Write to netCDF file.
1.385 +
1.386 + delete(tmp_data) ; Delete for next round.
1.387 + end do
1.388 +
1.389 +; write variable to file
1.390 +
1.391 + f->year = year
1.392 + f->lat = lat
1.393 + f->lon = lon
1.394 +end