1 ;----------------------------------------------------------------------
2 ; This example reads an ASCII file that is formatted a specific way, and
3 ; writes out the results to a netCDF file.
5 ; The first line in the ASCII file must be a header, with each field
6 ; separated by a single character delimiter (like a ","). The rest of
7 ; the file must be such that each row contains all fields, each
8 ; separated by the designated delimiter.
10 ; The fields can be integer, float, double, character, or string.
11 ; String fields cannot be written to a netCDF file. They have to
12 ; be read in as character arrays and written out that way.
13 ;----------------------------------------------------------------------
15 ;----------------------------------------------------------------------
16 ; This function returns the index locations of the given delimiter
17 ; in a row or several rows of strings.
18 ;----------------------------------------------------------------------
19 function delim_indices(strings,nfields,delimiter)
20 local cstrings, cdelim
22 nrows = dimsizes(strings)
24 ; Handle special case if we only have one string. Make sure it
25 ; is put into a 2D array.
28 cstrings = new((/1,strlen(strings)+1/),character)
31 cstrings = stringtochar(strings) ; Convert to characters.
32 cdelim = stringtochar(delimiter) ; Convert delimiter to character.
34 ; Som error checking here. Make sure delimiter is one character.
38 if(rank.ne.1.or.(rank.eq.1.and.nc.ne.2)) then
39 print("delim_indices: fatal: the delimiter you've selected")
40 print("must be a single character. Can't continue.")
45 ; Create array to hold indices of delimiter locations, and then loop
46 ; through each row and find all the delimiters. Make sure each row has
47 ; the correct number of delimiters.
50 cindices = new((/nrows,ndelims/),integer)
52 ii = ind(cstrings(i,:).eq.cdelim(0))
54 ; Make sure there were delimiters on this row. If not, we just quit.
55 ; This could probably be modified to do this more gracefully.
57 if(any(ismissing(ii))) then
58 print("delim_indices: fatal: I didn't find any delimiters")
59 print("('" + delimiter + "') on row " + i + ". Can't continue.")
62 if(dimsizes(ii).ne.ndelims) then
63 print("delim_indices: fatal: I expected to find " + ndelims)
64 print("delimiters on row " + i + ". Instead, I found " + dimsizes(ii) + ".")
65 print("Can't continue.")
71 delete(ii) ; For next time through loop
77 ;----------------------------------------------------------------------
78 ; This function reads in a particular field from a string array,
79 ; given the field number to read (fields start at #1 and go to #nfield),
80 ; and the indices of the delimiters.
82 ; It returns either an integer, float, double, character, or a string,
83 ; depending on the input flag "return_type".
84 ;----------------------------------------------------------------------
85 function read_field(strings,ifield,indices,return_type)
86 local nstring, cstrings, nf, tmp_str
88 nrows = dimsizes(strings)
90 ; Handle special case if we only have one string. Make sure it
91 ; is put into a 2D array.
94 cstrings = new((/1,strlen(strings)+1/),character)
97 cstrings = stringtochar(strings)
98 nf = dimsizes(indices(0,:))+1 ; indices is nrows x (nfields-1)
101 ; Error checking. Make sure user has entered a valid field.
103 if(ifield.le.0.or.ifield.gt.nf) then
104 print("read_field: fatal: you've selected a field that is")
105 print("out-of-range of the number of fields that you have (" + nf + ").")
110 ; Set up array to return. For string, int, float, or double arrays,
111 ; we don't have to do anything special. For character arrays,
114 if(return_type.ne."character") then
115 return_array = new(nrows,return_type)
118 ; We don't know what the biggest character array is at this point, so
119 ; make it bigger than necessary, and then resize later as necessary.
121 tmp_return_array = new((/nrows,dimsizes(cstrings(0,:))/),"character")
123 max_len = 0 ; Use to keep track of max lengths of strings.
128 ; Special case of first field in row.
132 iend = indices(i,ifield-1)-1
135 ; Special case of first field in row.
137 if(ifield.eq.nf) then
138 ibeg = indices(i,ifield-2)+1
139 iend = dimsizes(cstrings(i,:))-1
141 ; Any field between first and last field.
144 ibeg = indices(i,ifield-2)+1
145 iend = indices(i,ifield-1)-1
149 ; Here's the code that pulls off the correct string, and converts it
150 ; to float if desired.
152 if(return_type.eq."integer") then
153 return_array(i) = stringtointeger(chartostring(cstrings(i,ibeg:iend)))
155 if(return_type.eq."float") then
156 return_array(i) = stringtofloat(chartostring(cstrings(i,ibeg:iend)))
158 if(return_type.eq."double") then
159 return_array(i) = stringtodouble(chartostring(cstrings(i,ibeg:iend)))
161 if(return_type.eq."string") then
162 return_array(i) = chartostring(cstrings(i,ibeg:iend))
164 if(return_type.eq."character") then
165 if( (iend-ibeg+1) .gt. max_len) then
166 max_len = iend-ibeg+1
168 tmp_return_array(i,0:iend-ibeg) = cstrings(i,ibeg:iend)
172 if(return_type.eq."character") then
173 return_array = new((/nrows,max_len/),"character")
174 return_array = tmp_return_array(:,0:max_len-1)
181 ;----------------------------------------------------------------------
182 ; This function reads in string fields only to get the maximum string
184 ;----------------------------------------------------------------------
185 function get_maxlen(strings,ifield,indices)
186 local nstring, cstrings, nf, tmp_str
188 nrows = dimsizes(strings)
190 ; Handle special case if we only have one string. Make sure it
191 ; is put into a 2D array.
194 cstrings = new((/1,strlen(strings)+1/),character)
197 cstrings = stringtochar(strings)
198 nf = dimsizes(indices(0,:))+1 ; indices is nrows x (nfields-1)
201 ; Error checking. Make sure user has entered a valid field.
203 if(ifield.le.0.or.ifield.gt.nf) then
204 print("read_field: fatal: you've selected a field that is")
205 print("out-of-range of the number of fields that you have (" + nf + ").")
209 ; We don't know what the biggest character array is at this point, so
210 ; make it bigger than necessary, and then resize later as necessary.
212 tmp_return_array = new((/nrows,dimsizes(cstrings(0,:))/),"character")
214 max_len = 0 ; Use to keep track of max lengths of strings.
218 ; Special case of first field in row.
222 iend = indices(i,ifield-1)-1
225 ; Special case of first field in row.
227 if(ifield.eq.nf) then
228 ibeg = indices(i,ifield-2)+1
229 iend = dimsizes(cstrings(i,:))-1
231 ; Any field between first and last field.
234 ibeg = indices(i,ifield-2)+1
235 iend = indices(i,ifield-1)-1
238 if( (iend-ibeg+1) .gt. max_len) then
239 max_len = iend-ibeg+1
246 ;----------------------------------------------------------------------
248 ;----------------------------------------------------------------------
251 ; Set up defaults here. We are hard-coding the field types here.
252 ; You can set up this script to try to determine the field types
253 ; automatically, but this is a bit tedious. Maybe later.
257 nfields = 30 ; # of fields
258 delimiter = "," ; field delimiter
260 filename = station+year+"_L4_m.txt" ; ASCII" file to read.
261 cdf_file = station+year+"_L4_m.nc" ; netCDF file to write.
263 ; In this case, fields #2-#2 are integers,
264 ; and the rest of the fields are floats.
266 var_types = new(nfields,string)
267 var_strlens = new(nfields,integer) ; var to hold strlens, just in case.
269 var_types = "float" ; Most are floats.
270 var_types(0:1) = "integer"
272 if(isfilepresent(cdf_file))
273 print("Warning: '" + cdf_file + "' exists. Will remove it.")
274 system("/bin/rm " + cdf_file)
277 ; Read in data as strings. This will create a string array that has the
278 ; same number of strings as there are rows in the file. We will then need
279 ; to parse each string later.
281 read_data = asciiread(filename,-1,"string")
282 header = read_data(0) ; Header. Use for variable names.
283 data = read_data(1:) ; Get rid of first line which is a header.
284 nrows = dimsizes(data) ; Number of rows.
286 ; Read in locations of delimiters in each string row.
288 hindices = delim_indices(header,nfields,delimiter) ; header row
289 dindices = delim_indices(data,nfields,delimiter) ; rest of file
294 ; Read in the field names which will become variable names on
297 var_names = new(nfields,string)
300 var_names(i) = read_field(header,i+1,hindices,"string")
303 ; Write out this netCDF file efficiently so it will be faster.
304 ; Try to predefine everything before you write to it.
306 f = addfile(cdf_file,"c")
307 setfileoption(f,"DefineMode",True) ; Enter predefine phase.
309 ; Write global attributes to file. It's okay to do this before
310 ; predefining the file's variables. We are still in "define" mode.
313 fAtt@description = "Data read in from " + filename + " ASCII file."
314 fAtt@creation_date = systemfunc ("date")
315 fileattdef( f, fAtt )
317 ; Write dimension names to file. If there are no character variables,
318 ; then there's only one dimension name ("nvalues").
323 dim_names = (/ "year", "month" /)
324 dim_sizes = (/ nyear , nmonth /)
325 dimUnlim = (/ True , False /)
327 filedimdef( f, dim_names, dim_sizes, dimUnlim )
329 ; Define each variable on the file.
331 ; Don't deal with variable Month (i=0).
334 filevardef(f, var_names(i), var_types(i), dim_names)
337 ; Loop through each field, read the values for that field, print
338 ; information about the variable, and then write it to the netCDF
342 ifield = i+1 ; Fields start at #1, not #0.
344 ; Note: you can't write strings to a netCDF file, so these have
345 ; to be written out as character arrays.
347 tmp_data = new((/1,nmonth/),var_types(i))
349 out_data = read_field(data,ifield,dindices,var_types(i))
351 tmp_data(0,:) = out_data(:)
353 ; Print some info about the variable.
356 print("Writing variable '" + var_names(i) + "' (field #" + ifield + ").")
357 print("Type is " + var_types(i) + ".")
358 print("min/max = " + min(tmp_data) + "/" + max(tmp_data))
360 if(any(ismissing(tmp_data))) then
361 print("This variable does contain missing values.")
363 print("This variable doesn't contain missing values.")
366 f->$var_names(i)$ = tmp_data ; Write to netCDF file.
368 delete(tmp_data) ; Delete for next round.