source: trunk/SRC/ToBeReviewed/LECTURE/read_ncdf.pro @ 457

Last change on this file since 457 was 457, checked in by smasson, 13 years ago

add allrecords keyword in read_ncdf.pro

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.3 KB
Line 
1;+
2;
3; @file_comments
4; Reading function for the file net_cdf.
5; This program is less universal than <pro>ncdf_lec</pro> (it appeal to
6; declared variables in <pro>common</pro>) but it is very easier to be used.
7; It considerate
8; the declaration of the different zooms which have been defined
9; (ixminmesh...premierx...), the declaration of the variable key_shift...
10; To put it in a nutshell, the result of read_ncdf can be directly used in
11; <pro>plt</pro> ...
12;
13; This is also this program which is used by default in our reading widgets.
14;
15; @categories
16; Reading
17;
18; @param NAME {in}{required}{type=string}
19; It define the field to be read.
20;
21; @param BEGINNING {in}{required}
22; Relative with the time axis.
23; These can be
24;  - 2 dates of the type yyyymmdd and in this case, we select data
25;  which are included between these two dates.
26;  - 2 indexes which define between which and which time steps we have
27;  to extract the temporal dimension.
28;
29; @param ENDING {in}{required}
30; Relative with the time axis.
31; See BEGINNING.
32;
33; @param COMPATIBILITY {in}{optional}
34; Useless, defined for compatibility
35;
36; @keyword ADDSCL_BEFORE {default=0}{type=scalar: 0 or 1}
37; put 1 to apply add_offset and scale factor on data before looking for
38; missing values
39;
40; @keyword ALLRECORDS
41; activate to read all records in a file (no need to specify any
42; parameter other than NAME)
43;
44; @keyword BOXZOOM
45; Contain the boxzoom on which we have to do the reading
46;
47; @keyword CALLITSELF {default=0}{type=scalar: 0 or 1}
48; For ROMS outputs. Use by read_ncdf itself to access auxilliary data
49; (h and zeta).
50;
51; @keyword DIREC
52; a string used to specify the direction along which we want to make
53; spatial and/or temporal mean. It could be: 'x' 'y' 'z' 't' 'xy' 'xz'
54; 'yz' 'xyz' 'xt' 'yt' 'zt' 'xyt' 'xzt' 'yzt' or 'xyzt'
55;
56; @keyword FILENAME {required}{type=string}
57; It contains the file's name.
58;
59; @keyword INIT {default=0}{type=scalar: 0 or 1}
60; To call automatically <pro>initncdf</pro> with filename as input argument
61; and thus redefine all the grid parameters
62;
63; @keyword GRID
64; ='[UTVWF]' to specify the type of grid. Default is (1)
65; based on the name of the file if the file ends by
66; GRID[._][TUVFW].NC (not case sensible) or (2) T if case (1)
67; is not found.
68;
69; @keyword TIMESTEP {default=0}{type=scalar: 0 or 1}
70; Specify that BEGINNING and ENDING refer to indexes of the time axis and not
71; to dates
72;
73; @keyword TOUT {default=0}{type=scalar: 0 or 1}
74; We activate it if we want to read the file on the whole domain without
75; considerate the sub-domain defined by the boxzoom or
76; lon1,lon2,lat1,lat2,vert1,vert2.
77;
78; @keyword NOSTRUCT {default=0}{type=scalar: 0 or 1}
79; We activate it if we do not want that read_ncdf send back a structure
80; but only the array referring to the field.
81;
82; @keyword ZETAFILENAME {default=FILENAME}{type=string}
83; For ROMS outputs. The filename of the file where zeta variable should be read
84;
85; @keyword ZETAZERO {default=0}{type=scalar: 0 or 1}
86; For ROMS outputs. To define zeta to 0. instead of reading it
87;
88; @keyword ZINVAR {type=named variable}
89; Set this keyword to a named variable in which 1 is returned if a
90; vertical dimension is found in the variable. Returns 0 otherwise
91;
92; @keyword _EXTRA
93; Used to pass keywords to <pro>isafile</pro>, <pro>initncdf</pro>,
94; <pro>ncdf_gettime</pro>, <pro>ncdf_getatt</pro> and <pro>domdef</pro>
95;
96; @returns
97; Structure readable by <pro>litchamp</pro> or an array if NOSTRUCT is
98; activated.
99;
100; @uses
101; <pro>common</pro>
102;
103; @restrictions
104; The field must have a temporal dimension.
105;
106; @history
107; Sebastien Masson (smasson\@lodyc.jussieu.fr)
108;                      15/10/1999
109;
110; @version
111; $Id$
112;
113;-
114FUNCTION read_ncdf, name, beginning, ending, compatibility $
115                    , ALLRECORDS = allrecords, BOXZOOM = boxzoom, FILENAME = filename $
116                    , PARENTIN = parentin, TIMESTEP = timestep $
117                    , ADDSCL_BEFORE = addscl_before $
118                    , TOUT = tout, NOSTRUCT = nostruct $
119                    , CONT_NOFILL = CONT_NOFILL, INIT = init $
120                    , GRID = grid, CALLITSELF = callitself, DIREC = direc $
121                    , ZETAFILENAME = zetafilename, ZETAZERO = zetazero $
122                    , ZINVAR = zinvar, _EXTRA = ex
123;
124  compile_opt idl2, strictarrsubs
125;
126@cm_4mesh
127@cm_4data
128@cm_4cal
129  IF NOT keyword_set(key_forgetold) THEN BEGIN
130@updatenew
131@updatekwd
132  ENDIF
133;------------------------------------------------------------
134; we find the filename.
135;------------------------------------------------------------
136;  print,filename
137; is parent a valid widget ?
138  IF keyword_set(parentin) THEN BEGIN
139    parent = long(parentin)
140    parent = parent*widget_info(parent, /managed)
141  ENDIF
142  filename = isafile(filename = filename, IODIRECTORY = iodir, _EXTRA = ex)
143;------------------------------------------------------------
144; Opening of the name file
145;------------------------------------------------------------
146  IF size(filename, /type) NE 7 THEN $
147     return, report('read_ncdf cancelled')
148  IF !version.OS_FAMILY EQ 'unix' THEN spawn, '\file '+filename+' > /dev/null'
149  cdfid = ncdf_open(filename)
150  inq = ncdf_inquire(cdfid)
151;------------------------------------------------------------
152; we check if the variable name exists in the file.
153;------------------------------------------------------------
154  IF ncdf_varid(cdfid, name) EQ -1 THEN BEGIN
155    ncdf_close, cdfid
156    return, report('variable '+name+' !C not found in the file '+filename)
157  ENDIF
158  varinq = ncdf_varinq(cdfid, name)
159  IF varinq.ndims LT 2 THEN return, report('read_ncdf cannot read scalar or 1D data')
160; look for the dimension names
161  dimnames = strarr(varinq.ndims)
162  FOR i = 0, varinq.ndims-1 DO BEGIN
163    ncdf_diminq, cdfid, varinq.dim[i], tmp, dimsize
164    dimnames[i] = tmp
165  ENDFOR
166;------------------------------------------------------------
167; we check if the variable has a vertical dimension and/or
168; a record dimension. This is useful to define boxzoom
169; keyword in domdef
170;------------------------------------------------------------
171  dummy = where(varinq.dim EQ inq.recdim, tinvar)
172; check the presence of a vertical dimension according to the
173; number of dimensions and the presence of a record dimension
174  zinvar = (varinq.ndims EQ 3 AND tinvar NE 1) OR varinq.ndims EQ 4
175;------------------------------------------------------------
176; shall we redefine the grid parameters
177;------------------------------------------------------------
178  IF keyword_set(init) THEN initncdf, filename, _extra = ex
179;------------------------------------------------------------
180; check the time axis and the debut and ending dates
181;------------------------------------------------------------
182  IF n_elements(beginning) EQ 0 AND NOT keyword_set(allrecords) THEN BEGIN
183    beginning = 0L
184    timestep = 1L
185  ENDIF
186; define time and jpt
187  CASE 1 OF
188    keyword_set(timestep):BEGIN
189      firsttps = long(beginning[0])
190      IF n_elements(ending) NE 0 THEN lasttps = long(ending[0]) ELSE lasttps = firsttps
191      jpt = lasttps-firsttps+1
192      IF NOT keyword_set(callitself) then time = julday(1, 1, 1) + lindgen(jpt)
193    END
194    keyword_set(parent):BEGIN
195      widget_control, parent, get_uvalue = top_uvalue
196      filelist = extractatt(top_uvalue, 'filelist')
197      IF filelist[0] EQ 'many !' THEN filelist = filename
198      currentfile = (where(filelist EQ filename))[0]
199      time = (*(extractatt(top_uvalue, 'fileparameters'))[currentfile]).time_counter
200      date1 = date2jul(beginning[0])
201      if n_elements(ending) NE 0 then date2 = date2jul(ending[0]) ELSE date2 = date1
202      firsttps = (where(abs(time - date1) LT 0.9d/86400.d))[0] ; beware of rounding errors...
203      lasttps = (where(abs(time - date2) LT 0.9d/86400.d))[0]
204      jpt = lasttps-firsttps+1
205    END
206    keyword_set(allrecords):BEGIN
207      time = ncdf_gettime(filename, cdfid, caller = 'read_ncdf', err = err, _extra = ex)
208      IF time[0] LT 0 then BEGIN
209        jpt = -time[0]
210        time = julday(1, 1, 1) + lindgen(jpt)
211      ENDIF
212      firsttps = 0
213      lasttps = jpt -1
214    END
215    ELSE:BEGIN
216      time = ncdf_gettime(filename, cdfid, caller = 'read_ncdf', err = err, _extra = ex)
217      IF n_elements(err) NE 0 THEN BEGIN
218        dummy = report(err)
219        ncdf_close, cdfid
220        return, -1
221      ENDIF
222; date1
223      date1 = date2jul(beginning[0])
224; date2
225      if n_elements(ending) NE 0 then date2 = date2jul(ending[0]) ELSE date2 = date1
226; firsttps
227      firsttps = where(time GE (date1 - 0.9d/86400.d)) & firsttps = firsttps[0]
228      if firsttps EQ -1 THEN BEGIN
229        ncdf_close, cdfid
230        return, report('date 1: '+strtrim(jul2date(date1), 1)+' is not found in the time axis.')
231      ENDIF
232; lasttps
233      lasttps = where(time LE (date2 + 0.9d/86400.d)) & lasttps = lasttps[n_elements(lasttps)-1]
234      if lasttps EQ -1 THEN BEGIN
235        ncdf_close, cdfid
236        return, report('the time axis has no date before date 2: '+strtrim(jul2date(date2), 1))
237      endif
238      if lasttps LT firsttps then BEGIN
239        ncdf_close, cdfid
240        return, report('the time axis has no dates between date1 and  date 2: '+strtrim(jul2date(date1), 1)+' '+strtrim(jul2date(date2), 1))
241      endif
242      time = time[firsttps:lasttps]
243      jpt = lasttps-firsttps+1
244    END
245  ENDCASE
246;------------------------------------------------------------
247; Name of the grid on which the field refer to.
248;------------------------------------------------------------
249  IF keyword_set(grid) THEN vargrid = strupcase(grid) ELSE BEGIN
250    vargrid = 'T'               ; default definition
251    IF finite(glamu[0]) EQ 1 THEN BEGIN
252; are we in one of the case corresponding to ROMS conventions?
253      CASE 1 OF
254        dimnames[2 < (varinq.ndims-1)] EQ 's_w':vargrid = 'W'
255        dimnames[0] EQ 'xi_rho' AND dimnames[1] EQ 'eta_rho':vargrid = 'T'
256        dimnames[0] EQ 'xi_u'   AND dimnames[1] EQ 'eta_u'  :vargrid = 'U'
257        dimnames[0] EQ 'xi_v'   AND dimnames[1] EQ 'eta_v'  :vargrid = 'V'
258        dimnames[0] EQ 'xi_psi' AND dimnames[1] EQ 'eta_psi':vargrid = 'F'
259        dimnames[0] EQ 'xi_rho' AND dimnames[1] EQ 'eta_v'  :vargrid = 'V'
260        dimnames[0] EQ 'xi_u'   AND dimnames[1] EQ 'eta_rho':vargrid = 'U'
261        dimnames[0] EQ 'xi_u'   AND dimnames[1] EQ 'eta_v'  :vargrid = 'F'
262        ELSE:BEGIN
263; could we define the grid type from the file name??
264          pattern = ['GRID.', 'GRID_', 'GRID', 'UPID_', '30ID_']
265          gdtype = ['T', 'U', 'V', 'W', 'F']
266          fnametest = strupcase(filename)
267          FOR i = 0, n_elements(pattern)-1 DO BEGIN
268            FOR j = 0, n_elements(gdtype)-1 DO BEGIN
269              substr = pattern[i]+gdtype[j]
270              pos = strpos(fnametest, substr)
271              IF pos NE -1 THEN $
272                 vargrid = strmid(fnametest, pos+strlen(substr)-1, 1)
273            ENDFOR
274          ENDFOR
275        END
276      ENDCASE
277    ENDIF
278  ENDELSE
279;---------------------------------------------------------------
280; redefinition of the domain
281;---------------------------------------------------------------
282  IF keyword_set(tout) THEN BEGIN
283    nx = jpi
284    ny = jpj
285    nz = jpk
286    firstx = 0
287    firsty = 0
288    firstz = 0
289    lastx = jpi-1
290    lasty = jpj-1
291    lastz = jpk-1
292    case strupcase(vargrid) of
293      'T':mask = tmask
294      'U':mask = umask()
295      'V':mask = vmask()
296      'W':mask = tmask
297      'F':mask = fmask()
298    endcase
299  ENDIF ELSE BEGIN
300    IF keyword_set(boxzoom) then BEGIN
301      CASE N_Elements(Boxzoom) Of
302        1:bte = [lon1, lon2, lat1, lat2, 0., boxzoom[0]]
303        2:bte = [lon1, lon2, lat1, lat2, boxzoom[0], boxzoom[1]]
304        4:bte = [Boxzoom, vert1, vert2]
305        5:bte = [Boxzoom[0:3], 0, Boxzoom[4]]
306        6:bte = Boxzoom
307        ELSE: BEGIN
308          ncdf_close, cdfid
309          return, report('Wrong Definition of Boxzoom')
310        END
311      ENDCASE
312      IF zinvar EQ 1 THEN domdef, bte, GRIDTYPE = ['T', vargrid], _extra = ex $
313      ELSE domdef, bte[0:3], GRIDTYPE = ['T', vargrid], _extra = ex
314    ENDIF
315    grille, mask, glam, gphi, gdep, nx, ny, nz, firstx, firsty, firstz, lastx, lasty, lastz
316    undefine, glam & undefine, gphi & ; We liberate some memory!
317  ENDELSE
318;---------------------------------------------------------------------
319; We initialize ixmindta, iymindta if needed
320;---------------------------------------------------------------------
321  if n_elements(jpidta) EQ 0 THEN jpidta = jpiglo
322  if n_elements(jpjdta) EQ 0 THEN jpjdta = jpjglo
323  if n_elements(jpkdta) EQ 0 THEN jpkdta = jpkglo
324  if n_elements(ixmindta) EQ 0 THEN ixmindta = 0
325  if n_elements(ixmaxdta) EQ 0 then ixmaxdta = jpidta-1
326  if ixmindta EQ -1 THEN ixmindta = 0
327  IF ixmaxdta EQ -1 then ixmaxdta = jpidta-1
328  if n_elements(iymindta) EQ 0 THEN iymindta = 0
329  IF n_elements(iymaxdta) EQ 0 then iymaxdta = jpjdta-1
330  if iymindta EQ -1 THEN iymindta = 0
331  IF iymaxdta EQ -1 then iymaxdta = jpjdta-1
332  if n_elements(izmindta) EQ 0 THEN izmindta = 0
333  IF n_elements(izmaxdta) EQ 0 then izmaxdta = jpkdta-1
334  if izmindta EQ -1 THEN izmindta = 0
335  IF izmaxdta EQ -1 then izmaxdta = jpkdta-1
336;----------------------------------------------------------------
337; We will read the file
338;---------------------------------------------------------------
339  if n_elements(key_stride) LE 2 then key_stride = [1, 1, 1]
340  key_stride = 1l > long(key_stride)
341;---------------------------------------------------------------------
342;---------------------------------------------------------------------
343@read_ncdf_varget
344;---------------------------------------------------------------------
345;---------------------------------------------------------------------
346; We define common (cm_4data) variables associated with the variable.
347;---------------------------------------------------------------------
348; varname
349  IF NOT keyword_set(callitself) THEN varname = name
350; varunit and others...
351  ncdf_getatt, cdfid, name, add_offset = add_offset, scale_factor = scale_factor, missing_value = missing_value, units = units, _extra = ex
352  IF NOT keyword_set(callitself) THEN varunit = units
353; vardate
354; We make a legible date
355  caldat, time[0], month, day, year
356  vardate = string(format = '(C(CMoA))', 31*(month-1))+' '+strtrim(day, 1)+', '+strtrim(year, 1)
357  varexp = file_basename(filename)
358; We apply the value valmask on land points.
359  if NOT keyword_set(cont_nofill) then begin
360    valmask = 1.e20
361    case 1 of
362      varinq.ndims eq 2:                                               earth = where(mask[*, *, 0] EQ 0) ;xy   array
363      varinq.ndims eq 3 AND (where(varinq.dim EQ inq.recdim))[0] EQ -1:earth = where(mask EQ 0)          ;xyz  array
364      varinq.ndims eq 3 AND (where(varinq.dim EQ inq.recdim))[0] NE -1:earth = where(mask[*, *, 0] EQ 0) ;xyt  array
365      varinq.ndims eq 4:                                               earth = where(mask EQ 0)          ;xyzt array
366    ENDCASE
367  ENDIF ELSE earth = -1
368; we look for  missing_value
369; we apply add_offset, scale_factor and missing_value
370  IF keyword_set(addscl_before) THEN BEGIN
371    IF scale_factor NE 1 THEN res = temporary(res)*scale_factor
372    IF add_offset   NE 0 THEN res = temporary(res)+add_offset
373  ENDIF
374  IF size(missing_value, /type) NE 7 THEN BEGIN
375    IF finite(missing_value) EQ 1 THEN BEGIN
376      CASE 1 OF
377        missing_value GT 1.e6:missing = where(res GT missing_value/10.)
378        missing_value LT -1.e6:missing = where(res LT missing_value/10.)
379        abs(missing_value) LT 1.e-6:missing = where(abs(res) LT 1.e-6)
380        ELSE:missing = where(res EQ missing_value)
381      ENDCASE
382    ENDIF ELSE missing = where(finite(res) EQ 0)
383  ENDIF ELSE missing = -1
384  IF NOT keyword_set(addscl_before) THEN BEGIN
385    if scale_factor NE 1 then res = temporary(res)*scale_factor
386    if add_offset NE 0 then res = temporary(res)+add_offset
387  ENDIF
388  IF missing[0] NE -1 THEN res[temporary(missing)] = !values.f_nan
389  IF earth[0] NE -1 THEN BEGIN
390    IF varinq.ndims eq 3 AND (where(varinq.dim EQ inq.recdim))[0] NE -1 THEN $ ;xyt array
391       earth = earth#replicate(1, jpt)+replicate(nx*ny, n_elements(earth))#lindgen(jpt)
392    IF varinq.ndims eq 4 THEN earth = earth#replicate(1, jpt)+replicate(nx*ny*nz, n_elements(earth))#lindgen(jpt)
393    res[temporary(earth)] = 1.e20
394  ENDIF
395;---------------------------------------------------------------------
396; if it is roms outputs, we need to get additionals infos...
397  IF NOT keyword_set(callitself) THEN BEGIN
398    IF strmid(dimnames[0], 0, 3) EQ 'xi_' AND strmid(dimnames[1], 0, 4) EQ 'eta_' THEN BEGIN
399      ncdf_attget, cdfid, 'theta_s', theta_s, /global
400      ncdf_attget, cdfid, 'theta_b', theta_b, /global
401      ncdf_attget, cdfid, 'hc', hc, /global
402; look for all variables names
403      allvarnames = strarr(inq.nvars)
404      FOR i = 0, inq.nvars-1 DO BEGIN
405        tmp = ncdf_varinq( cdfid, i)
406        allvarnames[i] = tmp.name
407      ENDFOR
408      CASE 1 OF
409        keyword_set(zetazero):zeta = fltarr(nx, ny, jpt)
410        keyword_set(zetafilename):  $
411           zeta = read_ncdf('zeta', firsttps, lasttps, FILENAME = zetafilename $
412                            , /TIMESTEP, /NOSTRUCT, CONT_NOFILL = CONT_NOFILL $
413                            , GRID = vargrid, /CALLITSELF, _EXTRA = ex)
414        (where(allvarnames EQ 'zeta'))[0] NE -1: $
415           zeta = read_ncdf('zeta', firsttps, lasttps, FILENAME = filename $
416                            , /TIMESTEP, /NOSTRUCT, CONT_NOFILL = CONT_NOFILL $
417                            , GRID = vargrid, /CALLITSELF, _EXTRA = ex)
418        ELSE:return, report('The variable zeta was not found in the file, please use the keyword ZETAFILENAME to specify the name of a file containing zeta or use  keyword ZETAZERO to define zeta to 0.')
419      ENDCASE
420      romszinfos = {h:romszinfos.h, zeta:temporary(zeta), theta_s:theta_s, theta_b:theta_b, hc:hc}
421    ENDIF ELSE romszinfos = {h:-1, zeta:-1, theta_s:-1, theta_b:-1, hc:-1}
422  ENDIF
423;---------------------------------------------------------------------
424  IF keyword_set(direc) THEN BEGIN
425    IF jpt EQ 1 THEN res = moyenne(temporary(res), direc, _extra = ex) $
426    ELSE BEGIN
427      res = grossemoyenne(temporary(res), direc, _extra = ex)
428      IF ( strpos(strlowcase(direc), 't') ge 0 ) THEN BEGIN
429        vardate = strtrim(jul2date(time[0]), 1)+' - '+strtrim(jul2date(time[jpt-1]), 1)
430        time = total(time)/float(jpt)
431        jpt = 1
432      ENDIF
433    ENDELSE
434  ENDIF
435;---------------------------------------------------------------------
436  ncdf_close, cdfid
437  IF keyword_set(nostruct) THEN return, res
438  IF keyword_set(key_forgetold) THEN BEGIN
439    return, {arr:temporary(res), grid:vargrid, unit:varunit, experiment:varexp, name:varname}
440  ENDIF ELSE BEGIN
441    return, {tab:temporary(res), grille:vargrid, unite:varunit, experience:varexp, nom:varname}
442  ENDELSE
443
444END
Note: See TracBrowser for help on using the repository browser.