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