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

Last change on this file since 366 was 366, checked in by pinsard, 16 years ago

typo

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