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

Last change on this file since 336 was 336, checked in by smasson, 16 years ago

improve boxzoom usage in read_ncdf

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