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

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

get time axis even when using /timestep keyword in read_ncdfSRC/ToBeReviewed/LECTURE/read_ncdf.pro

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.7 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      IF NOT keyword_set(callitself) then BEGIN
192        time = ncdf_gettime(filename, cdfid, caller = 'read_ncdf', err = err, _extra = ex)
193        jpt = lasttps-firsttps+1
194        IF time[0] LT 0 then time = julday(1, 1, 1) + lindgen(jpt) $
195        ELSE time = time[firsttps:lasttps]
196      ENDIF ELSE jpt = lasttps-firsttps+1
197    END
198    keyword_set(parent):BEGIN
199      widget_control, parent, get_uvalue = top_uvalue
200      filelist = extractatt(top_uvalue, 'filelist')
201      IF filelist[0] EQ 'many !' THEN filelist = filename
202      currentfile = (where(filelist EQ filename))[0]
203      time = (*(extractatt(top_uvalue, 'fileparameters'))[currentfile]).time_counter
204      date1 = date2jul(beginning[0])
205      if n_elements(ending) NE 0 then date2 = date2jul(ending[0]) ELSE date2 = date1
206      firsttps = (where(abs(time - date1) LT 0.9d/86400.d))[0] ; beware of rounding errors...
207      lasttps = (where(abs(time - date2) LT 0.9d/86400.d))[0]
208      jpt = lasttps-firsttps+1
209    END
210    keyword_set(allrecords) OR n_elements(beginning) EQ 0:BEGIN
211      time = ncdf_gettime(filename, cdfid, caller = 'read_ncdf', err = err, _extra = ex)
212      IF time[0] LT 0 then BEGIN
213        jpt = -time[0]
214        time = julday(1, 1, 1) + lindgen(jpt)
215      ENDIF
216      firsttps = 0
217      lasttps = jpt -1
218    END
219    ELSE:BEGIN
220      time = ncdf_gettime(filename, cdfid, caller = 'read_ncdf', err = err, _extra = ex)
221      IF n_elements(err) NE 0 THEN BEGIN
222        dummy = report(err)
223        ncdf_close, cdfid
224        return, -1
225      ENDIF
226; date1
227      date1 = date2jul(beginning[0])
228; date2
229      if n_elements(ending) NE 0 then date2 = date2jul(ending[0]) ELSE date2 = date1
230; firsttps
231      firsttps = where(time GE (date1 - 0.9d/86400.d)) & firsttps = firsttps[0]
232      if firsttps EQ -1 THEN BEGIN
233        ncdf_close, cdfid
234        return, report('date 1: '+strtrim(jul2date(date1), 1)+' is not found in the time axis.')
235      ENDIF
236; lasttps
237      lasttps = where(time LE (date2 + 0.9d/86400.d)) & lasttps = lasttps[n_elements(lasttps)-1]
238      if lasttps EQ -1 THEN BEGIN
239        ncdf_close, cdfid
240        return, report('the time axis has no date before date 2: '+strtrim(jul2date(date2), 1))
241      endif
242      if lasttps LT firsttps then BEGIN
243        ncdf_close, cdfid
244        return, report('the time axis has no dates between date1 and  date 2: '+strtrim(jul2date(date1), 1)+' '+strtrim(jul2date(date2), 1))
245      endif
246      time = time[firsttps:lasttps]
247      jpt = lasttps-firsttps+1
248    END
249  ENDCASE
250;------------------------------------------------------------
251; Name of the grid on which the field refer to.
252;------------------------------------------------------------
253  IF keyword_set(grid) THEN vargrid = strupcase(grid) ELSE BEGIN
254    vargrid = 'T'               ; default definition
255    IF finite(glamu[0]) EQ 1 THEN BEGIN
256; are we in one of the case corresponding to ROMS conventions?
257      CASE 1 OF
258        dimnames[2 < (varinq.ndims-1)] EQ 's_w':vargrid = 'W'
259        dimnames[0] EQ 'xi_rho' AND dimnames[1] EQ 'eta_rho':vargrid = 'T'
260        dimnames[0] EQ 'xi_u'   AND dimnames[1] EQ 'eta_u'  :vargrid = 'U'
261        dimnames[0] EQ 'xi_v'   AND dimnames[1] EQ 'eta_v'  :vargrid = 'V'
262        dimnames[0] EQ 'xi_psi' AND dimnames[1] EQ 'eta_psi':vargrid = 'F'
263        dimnames[0] EQ 'xi_rho' AND dimnames[1] EQ 'eta_v'  :vargrid = 'V'
264        dimnames[0] EQ 'xi_u'   AND dimnames[1] EQ 'eta_rho':vargrid = 'U'
265        dimnames[0] EQ 'xi_u'   AND dimnames[1] EQ 'eta_v'  :vargrid = 'F'
266        ELSE:BEGIN
267; could we define the grid type from the file name??
268          pattern = ['GRID.', 'GRID_', 'GRID', 'UPID_', '30ID_']
269          gdtype = ['T', 'U', 'V', 'W', 'F']
270          fnametest = strupcase(filename)
271          FOR i = 0, n_elements(pattern)-1 DO BEGIN
272            FOR j = 0, n_elements(gdtype)-1 DO BEGIN
273              substr = pattern[i]+gdtype[j]
274              pos = strpos(fnametest, substr)
275              IF pos NE -1 THEN $
276                 vargrid = strmid(fnametest, pos+strlen(substr)-1, 1)
277            ENDFOR
278          ENDFOR
279        END
280      ENDCASE
281    ENDIF
282  ENDELSE
283;---------------------------------------------------------------
284; redefinition of the domain
285;---------------------------------------------------------------
286  IF keyword_set(tout) THEN BEGIN
287    nx = jpi
288    ny = jpj
289    nz = jpk
290    firstx = 0
291    firsty = 0
292    firstz = 0
293    lastx = jpi-1
294    lasty = jpj-1
295    lastz = jpk-1
296    case strupcase(vargrid) of
297      'T':mask = tmask
298      'U':mask = umask()
299      'V':mask = vmask()
300      'W':mask = tmask
301      'F':mask = fmask()
302    endcase
303  ENDIF ELSE BEGIN
304    IF keyword_set(boxzoom) then BEGIN
305      CASE N_Elements(Boxzoom) Of
306        1:bte = [lon1, lon2, lat1, lat2, 0., boxzoom[0]]
307        2:bte = [lon1, lon2, lat1, lat2, boxzoom[0], boxzoom[1]]
308        4:bte = [Boxzoom, vert1, vert2]
309        5:bte = [Boxzoom[0:3], 0, Boxzoom[4]]
310        6:bte = Boxzoom
311        ELSE: BEGIN
312          ncdf_close, cdfid
313          return, report('Wrong Definition of Boxzoom')
314        END
315      ENDCASE
316      IF zinvar EQ 1 THEN domdef, bte, GRIDTYPE = ['T', vargrid], _extra = ex $
317      ELSE domdef, bte[0:3], GRIDTYPE = ['T', vargrid], _extra = ex
318    ENDIF
319    grille, mask, glam, gphi, gdep, nx, ny, nz, firstx, firsty, firstz, lastx, lasty, lastz
320    undefine, glam & undefine, gphi & ; We liberate some memory!
321  ENDELSE
322;---------------------------------------------------------------------
323; We initialize ixmindta, iymindta if needed
324;---------------------------------------------------------------------
325  if n_elements(jpidta) EQ 0 THEN jpidta = jpiglo
326  if n_elements(jpjdta) EQ 0 THEN jpjdta = jpjglo
327  if n_elements(jpkdta) EQ 0 THEN jpkdta = jpkglo
328  if n_elements(ixmindta) EQ 0 THEN ixmindta = 0
329  if n_elements(ixmaxdta) EQ 0 then ixmaxdta = jpidta-1
330  if ixmindta EQ -1 THEN ixmindta = 0
331  IF ixmaxdta EQ -1 then ixmaxdta = jpidta-1
332  if n_elements(iymindta) EQ 0 THEN iymindta = 0
333  IF n_elements(iymaxdta) EQ 0 then iymaxdta = jpjdta-1
334  if iymindta EQ -1 THEN iymindta = 0
335  IF iymaxdta EQ -1 then iymaxdta = jpjdta-1
336  if n_elements(izmindta) EQ 0 THEN izmindta = 0
337  IF n_elements(izmaxdta) EQ 0 then izmaxdta = jpkdta-1
338  if izmindta EQ -1 THEN izmindta = 0
339  IF izmaxdta EQ -1 then izmaxdta = jpkdta-1
340;----------------------------------------------------------------
341; We will read the file
342;---------------------------------------------------------------
343  if n_elements(key_stride) LE 2 then key_stride = [1, 1, 1]
344  key_stride = 1l > long(key_stride)
345;---------------------------------------------------------------------
346;---------------------------------------------------------------------
347@read_ncdf_varget
348;---------------------------------------------------------------------
349;---------------------------------------------------------------------
350; We define common (cm_4data) variables associated with the variable.
351;---------------------------------------------------------------------
352; varname
353  IF NOT keyword_set(callitself) THEN varname = name
354; varunit and others...
355  ncdf_getatt, cdfid, name, add_offset = add_offset, scale_factor = scale_factor, missing_value = missing_value, units = units, _extra = ex
356  IF NOT keyword_set(callitself) THEN varunit = units
357; vardate
358; We make a legible date
359  caldat, time[0], month, day, year
360  vardate = string(format = '(C(CMoA))', 31*(month-1))+' '+strtrim(day, 1)+', '+strtrim(year, 1)
361  varexp = file_basename(filename)
362; We apply the value valmask on land points.
363  if NOT keyword_set(cont_nofill) then begin
364    valmask = 1.e20
365    case 1 of
366      varinq.ndims eq 2:                                               earth = where(mask[*, *, 0] EQ 0) ;xy   array
367      varinq.ndims eq 3 AND (where(varinq.dim EQ inq.recdim))[0] EQ -1:earth = where(mask EQ 0)          ;xyz  array
368      varinq.ndims eq 3 AND (where(varinq.dim EQ inq.recdim))[0] NE -1:earth = where(mask[*, *, 0] EQ 0) ;xyt  array
369      varinq.ndims eq 4:                                               earth = where(mask EQ 0)          ;xyzt array
370    ENDCASE
371  ENDIF ELSE earth = -1
372; we look for  missing_value
373; we apply add_offset, scale_factor and missing_value
374  IF keyword_set(addscl_before) THEN BEGIN
375    IF scale_factor NE 1 THEN res = temporary(res)*scale_factor
376    IF add_offset   NE 0 THEN res = temporary(res)+add_offset
377  ENDIF
378  IF size(missing_value, /type) NE 7 THEN BEGIN
379    IF finite(missing_value) EQ 1 THEN BEGIN
380      CASE 1 OF
381        missing_value GT 1.e6:missing = where(res GT missing_value/10.)
382        missing_value LT -1.e6:missing = where(res LT missing_value/10.)
383        abs(missing_value) LT 1.e-6:missing = where(abs(res) LT 1.e-6)
384        ELSE:missing = where(res EQ missing_value)
385      ENDCASE
386    ENDIF ELSE missing = where(finite(res) EQ 0)
387  ENDIF ELSE missing = -1
388  IF NOT keyword_set(addscl_before) THEN BEGIN
389    if scale_factor NE 1 then res = temporary(res)*scale_factor
390    if add_offset NE 0 then res = temporary(res)+add_offset
391  ENDIF
392  IF missing[0] NE -1 THEN res[temporary(missing)] = !values.f_nan
393  IF earth[0] NE -1 THEN BEGIN
394    IF varinq.ndims eq 3 AND (where(varinq.dim EQ inq.recdim))[0] NE -1 THEN $ ;xyt array
395       earth = earth#replicate(1, jpt)+replicate(nx*ny, n_elements(earth))#lindgen(jpt)
396    IF varinq.ndims eq 4 THEN earth = earth#replicate(1, jpt)+replicate(nx*ny*nz, n_elements(earth))#lindgen(jpt)
397    CASE size(res, /type) OF
398      1:res[temporary(earth)] = 0b
399      2:res[temporary(earth)] = 0
400      3:res[temporary(earth)] = OL
401      ELSE:res[temporary(earth)] = valmask
402    ENDCASE
403  ENDIF
404;---------------------------------------------------------------------
405; if it is roms outputs, we need to get additionals infos...
406  IF NOT keyword_set(callitself) THEN BEGIN
407    IF strmid(dimnames[0], 0, 3) EQ 'xi_' AND strmid(dimnames[1], 0, 4) EQ 'eta_' THEN BEGIN
408      ncdf_attget, cdfid, 'theta_s', theta_s, /global
409      ncdf_attget, cdfid, 'theta_b', theta_b, /global
410      ncdf_attget, cdfid, 'hc', hc, /global
411; look for all variables names
412      allvarnames = strarr(inq.nvars)
413      FOR i = 0, inq.nvars-1 DO BEGIN
414        tmp = ncdf_varinq( cdfid, i)
415        allvarnames[i] = tmp.name
416      ENDFOR
417      CASE 1 OF
418        keyword_set(zetazero):zeta = fltarr(nx, ny, jpt)
419        keyword_set(zetafilename):  $
420           zeta = read_ncdf('zeta', firsttps, lasttps, FILENAME = zetafilename $
421                            , /TIMESTEP, /NOSTRUCT, CONT_NOFILL = CONT_NOFILL $
422                            , GRID = vargrid, /CALLITSELF, _EXTRA = ex)
423        (where(allvarnames EQ 'zeta'))[0] NE -1: $
424           zeta = read_ncdf('zeta', firsttps, lasttps, FILENAME = filename $
425                            , /TIMESTEP, /NOSTRUCT, CONT_NOFILL = CONT_NOFILL $
426                            , GRID = vargrid, /CALLITSELF, _EXTRA = ex)
427        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.')
428      ENDCASE
429      romszinfos = {h:romszinfos.h, zeta:temporary(zeta), theta_s:theta_s, theta_b:theta_b, hc:hc}
430    ENDIF ELSE romszinfos = {h:-1, zeta:-1, theta_s:-1, theta_b:-1, hc:-1}
431  ENDIF
432;---------------------------------------------------------------------
433  IF keyword_set(direc) THEN BEGIN
434    IF jpt EQ 1 THEN res = moyenne(temporary(res), direc, _extra = ex) $
435    ELSE BEGIN
436      res = grossemoyenne(temporary(res), direc, _extra = ex)
437      IF ( strpos(strlowcase(direc), 't') ge 0 ) THEN BEGIN
438        vardate = strtrim(jul2date(time[0]), 1)+' - '+strtrim(jul2date(time[jpt-1]), 1)
439        time = total(time)/float(jpt)
440        jpt = 1
441      ENDIF
442    ENDELSE
443  ENDIF
444;---------------------------------------------------------------------
445  ncdf_close, cdfid
446  IF keyword_set(nostruct) THEN return, res
447  IF keyword_set(key_forgetold) THEN BEGIN
448    return, {arr:temporary(res), grid:vargrid, unit:varunit, experiment:varexp, name:varname}
449  ENDIF ELSE BEGIN
450    return, {tab:temporary(res), grille:vargrid, unite:varunit, experience:varexp, nom:varname}
451  ENDELSE
452
453END
Note: See TracBrowser for help on using the repository browser.