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