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

Last change on this file since 284 was 284, checked in by smasson, 17 years ago

make sur dates are given as long integer

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