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

Last change on this file since 325 was 325, checked in by pinsard, 17 years ago

modification of some headers (+some corrections) to prepare usage of the new idldoc

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