source: trunk/SRC/ReadWrite/write_ncdf.pro

Last change on this file was 495, checked in by pinsard, 10 years ago

fix thanks to coding rules; typo; dupe empty lines; trailing blanks

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 74.9 KB
Line 
1;----------------------------------------------------------------------------------------------
2;
3; @version
4; $Id$
5;
6;----------------------------------------------------------------------------------------------
7;
8; secondary subroutines used in the main subroutine named : write_ncdf.pro
9; ------------------------------------------------------------------------
10;
11;----------------------------------------------------------------------------------------------
12
13;
14; ---
15;
16
17;----------------------------------------------------------------------------------------------
18;
19; SUBROUTINE (1)/(3) :
20;
21; subroutine utilise ds le cas ou NOT_OUASSALU n est pas active
22; (default) et alors cela sert a uniformiser les dimensions qui sont
23; en dernieres dim de vars en unlimited si une dim de meme taille est
24; definie en unlimited et si eventuellement elles peuvent aussi etre
25; definies comme telles i.e. on privilegie le type unlimited pour les
26; dimensions en fin de var lorsque c''est possible et qu au moins un
27; dim de meme type est demandee en unlimited
28;
29; cf details plus bas...
30;
31;-
32pro writenc_unlimdim_update, dnames_imposed, unl_imposed, fmtbase, nviv $
33    , iidp1st, nn, dst, iid, SUPERTABU=supertab $
34    , DIMSIZESU=dimsizes, UNLIMTABAU=unlimtaba, UNLIMAU=unlima $
35    , DIMIDASU=dimidas, NDIMTOTU=ndimtot, DNAMOSSU=dnamoss, DNAMAU=dnama $
36    , IMPOSE_DNM_UNLU=impose_dnm_unl
37
38; -------
39
40compile_opt idl2, strictarrsubs ; idl2 --> les entiers sont des long par defaut ET [...] obligatoire pour les tablo
41                                ; strictarrsubs --> pas de depassement de tablo
42
43; -------
44
45; (1) mise en forme en structures classiques du main prog
46
47if n_elements(supertab) ne ndimtot then message,'PB : procedure write_ncdf_unlimdim_update init, (dim'+iodp1st+', var'+nviv+')... stop'
48for ikd=0,ndimtot-1 do begin
49    ikdp1st = string(ikd+1,format=fmtbase)
50    com = 'strd'+ikdp1st+' = writenc_strlc2str(supertab[ikd])'
51    if not execute(com) then message,'PB : writenc_unlimdim_update, loop1 on dim tot ('+ikdp1st+'), dim '+iidp1st+', var '+nviv+'... stop'
52endfor
53
54; -------
55
56; (2) traitement des structures de dim existantes, et comparaison a la dim courante (qui est last of var)
57
58; --> on est en train de gerer une last dim d une var avec option oneunlim_all_samesizeandlast_unlim=1,
59;       i.e. : si une dim est definie en unlim=1 ALORS toutes les dim de meme taille ET last dim definie avant ou
60;       apres deviennent identiques a cette dim (ne font plus qu une, selon compatibilite nom de dim ET unlimited impose ou pas)
61;
62;       DONC - soit cette dim est unlim=0 --> - soit on a deja une dim meme taille unlimited=1 alors: Si nom+unlim_impose compatibles,
63;                                               on passe notre dim courante a unlim=1 et elle sera assimile a celle qui
64;                                               existe deja avec le meme nom precedent (car meme caracteristiques). Si nom+unlim incompatibles,
65;                                               on va juste creer une nouvelle dim last not unlimited.
66;
67;                                             - soit on a pas deja de dim meme taille et unlim=1, donc cas classique cette dim unlim=0 est
68;                                               creee ou assimilee a une existante si nom et taille compatibles
69;
70;            - soit cette dim est unlim=1 --> - soit une dim unlim=1 existe deja, alors elle sera assimilee a celle-ci si noms compatibles
71;
72;                                             - soit une dim unlim=1 existe pas deja, alors cas plus complexe : pour eventuellement
73;                                               les mettre a jour, on doit parcourir les dimensions de meme taille pour separer les variables
74;                                               dont la dim en question est la last, et les variables dont la dim est not la last
75;                                                - soit on n a pas de variables qui ont une dim de meme taille en last dim, alors pas de mise
76;                                                  a jour a faire, on va creer une nouvelle dim, qui sera la dim unlim=1 du fichier
77;                                                - soit on a des variable(s) avec une dim last de meme taille unlim=0 ET nomdim compatible,
78;                                                  DONC on doit mettre a jour les last dim(s) de ces variables, 3 cas:
79;                                                  - une dim (unlim=0) contient que des vars qui en dependent en last dim et meme taille
80;                                                    que dim courante --> alors selon compatibilite pour changer unlim et nomdim, on regroupe
81;                                                    les vars qui ont last dim same size sous cette meme dim qui devient unlim=1 et a laquelle
82;                                                    la dim courante sera assimilee
83;                                                  - aucune dim contient que des vars en last dim et meme taille que dim courante --> alors
84;                                                    on cree des ICI une NOUVELLE dim qui est identique a la dim courante pour que celle-ci y
85;                                                    assimilee (pas creer 2 fois meme dim) ET qui contient les vars avec last dim qui sont
86;                                                    compatibles en unlim dim et nomdim
87;                                                  - n=plus de une dim (unlim=0) contient que des vars en last dim et meme taille que dim
88;                                                    courante --> il faudrait supprimer n-1 dim pour les assimiler a l une d entre elles...
89;                                                    en fait cela veut dire que pas assez de contraintes ont ete donne en entree aux dim
90;                                                    donc WARNING pour dire qu en ajoutant des contraintes pour forcer dim unlim=0 ou 1 ou bien
91;                                                    forcer le nom de la dim, alors on levera l ambiguite.
92
93if unlima eq 0 then begin
94
95    ; si on a une last dim not unlim, on check si des dim meme taille unlim1 qui existent pour les utiliser as same dim
96    ; --> si on trouve une dim meme taille et unlim=1 et nom ok alors on met la dim nbdimvv[inv] en unlim aussi
97
98    aaddo = where(dimsizes - nn eq 0 and unlimtaba eq 1)
99    if n_elements(aaddo) ne 1 then message,'PB : on a 1 ou 0 dim en unlimited (a), pas plus... stop'
100
101    if aaddo[0] ne -1 then begin ; on a une dims unlim=1 deja definie et de meme taille
102
103        strnbd = string(aaddo[0]+1,format=fmtbase)
104        com = 'strdtmp = strd'+strnbd
105        if not execute(com) then message, 'ERR : attrib strdtmp -1 (dim'+iodp1st+', var'+nviv+')...stop'
106        samnamokchgunlim = 0 ; peu importe cette valeur car si elle change pas c parce que dnames_imposed=0 donc condition apres deja ok
107        if dnames_imposed eq 1 then if strdtmp.nomdim eq dnama then samnamokchgunlim=1 else samnamokchgunlim=0
108        if (unl_imposed eq 0) and (dnames_imposed eq 0 or samnamokchgunlim) $
109          then unlima=1 ; ok pn peut changer unlim de la nouvelle dim qui pourra bien etre assimilee par la suite a une dim deja existante
110
111    endif
112
113endif else begin ; unlima = 1 --> cette last dim de la var est unlim=1 et donc unl_imposed = 1 aussi
114
115    aaddo = where(dimsizes - nn eq 0 and unlimtaba eq 1)
116    if n_elements(aaddo) ne 1 then message,'PB : on a 1 ou 0 dim en unlimited (b), pas plus... stop'
117
118    if aaddo[0] eq -1 then begin ; si une dim same kind pas deja definie --> update des dims precedentes ou create (sinon, on aura assimil...)
119    ; on a pas de dim meme taille avec unlim=1, donc on cherche si on a des last dims de meme taille
120    ; pour les mettre a jour question var et les rendre unlim=1 si possible ou creer un new dim unlim sinon
121        aabb = where(dimsizes - nn eq 0) ; et comme aucun n a same size et unlim=1 (cf au dessus) --> on tombe sur des dim unlim=0 !!!!
122
123        if aabb[0] ne -1 then begin
124
125            nbsdd = n_elements(aabb)
126            for iod=0,nbsdd-1 do begin ; on parcourt les dim de meme taille pr separer last dim ET not last dim
127                iodp1st=string(iod+1,format=fmtbase)
128                strnbd = string(aabb[iod]+1,format=fmtbase)
129                com = 'strdtmp = strd'+strnbd
130                if not execute(com) then message, 'ERR : attrib strdtmp 0a (dim'+iodp1st+', var'+nviv+')...stop'
131                ; que si on peut modifier leur dim name
132                IF dnames_imposed EQ 1 THEN if impose_dnm_unl[0,aabb[iod]] eq 1 and strdtmp.nomdim ne dnama then CONTINUE
133                strvarsdim = strdtmp.vardep_ndim
134                vnmarr = strvarsdim.(0)
135                ddparr = strvarsdim.(1)
136                nvararr = strvarsdim.(2)
137                lastad = strvarsdim.(3)
138                for iij=0,n_elements(nvararr)-1 do begin ;loop on var which depend on dim
139                    if lastad[iij] eq 1 then begin ; les var ou la dim est une last dim
140                        if n_elements(lasdd) eq 0 then                                             $
141                          lasdd = [ { u:aabb[iod]+1,v:[vnmarr[iij]],w:[ddparr[iij]]                $
142                                      ,x:[nvararr[iij]],y:[lastad[iij]] } ]                        $
143                        else                                                                       $
144                          lasdd = [ lasdd, { u:aabb[iod]+1,v:[vnmarr[iij]],w:[ddparr[iij]]         $
145                                             ,x:[nvararr[iij]],y:[lastad[iij]] } ]
146                    endif else begin ; vars ou la dim est pas un last dim
147                        if n_elements(notlasdd) eq 0 then                                           $
148                          notlasdd = [ { u:aabb[iod]+1,v:[vnmarr[iij]],w:[ddparr[iij]]              $
149                                         ,x:[nvararr[iij]],y:[lastad[iij]] } ]                      $
150                        else                                                                        $
151                          notlasdd = [ notlasdd, { u:aabb[iod]+1,v:[vnmarr[iij]],w:[ddparr[iij]]    $
152                                                   ,x:[nvararr[iij]],y:[lastad[iij]] } ]
153                    endelse
154                endfor
155            endfor
156
157            if n_elements(lasdd) ne 0 then begin ; alors on a des vars qui ont la meme dim en taille ET last dim --> update/creation faisable
158
159                listdwlast = lasdd[*].(0)
160                nnndz=0
161                dimwzonlylast=-1 & zorglub=temporary(dimwzonlylast)
162
163                dimdone = [-1]
164                FOR iad = 0, n_elements(listdwlast)-1 DO BEGIN ; on parcourt les dims de listdwlast, mais que une fois par dim size
165                    IF (where(dimdone eq listdwlast[iad]))[0] EQ -1 THEN BEGIN ; si cette dim est pas encore faite, on la fait
166                        strnbdo = string(listdwlast[iad], format = fmtbase)
167                        com = 'strdtmp = strd'+strnbdo
168                        if not execute(com) then message, $
169                          'ERR : attrib strdtmp 0b (dim'+strnbdo+', var'+nviv+')...stop'
170                        ;print,'hello ',strdtmp.vardep_ndim.(3)
171                        if (where(strdtmp.vardep_ndim.(3) eq 0))[0] eq -1 and impose_dnm_unl[1, listdwlast[iad]-1] eq 0 then begin
172                        ; pour cette dim: que des var avec last ET son unlim est pas imposed: ok, on peut utiliser cette dim pour update
173                            dimwzonlylast = listdwlast[iad]
174                            nnndz = nnndz+1
175                        endif
176                        IF iad EQ 0 THEN dimdone = [listdwlast[iad]] ELSE dimdone =  [dimdone, listdwlast[iad]]
177                    endif
178                ENDFOR
179
180                updatevara=0
181
182                ;if inv eq 2 and iid eq 0 then stop
183                ;if iidp1st eq '01' and nviv eq '03' then stop
184
185                case nnndz of
186                    1:begin ; 1 dim contient que des var avec last dim --> on s en sert pour update ok
187                        ;
188                        ; on ajoute ces vars (si plus de 1 existe) qui ont dim unlim a la struct de dim choisie
189                        ;
190                        strnbdu = string(dimwzonlylast,format=fmtbase)
191                        com = 'strdtmp1 = strd'+strnbdu
192                        if not execute(com) then message, $
193                          'ERR : attrib strdtmp 0c (dim'+iidp1st+', var'+nviv+')...stop'
194                        uubb = where(lasdd[*].(0) ne dimwzonlylast) ; autre dim avec var last=1 ? si oui update:
195                        if uubb[0] ne -1 then begin
196                            updatevara=1
197                            bbvdnd = {  a:[strdtmp1.vardep_ndim.(0),lasdd[uubb].(1)  ]   $
198                                        ,b:[strdtmp1.vardep_ndim.(1),lasdd[uubb].(2)  ]   $
199                                        ,c:[strdtmp1.vardep_ndim.(2),lasdd[uubb].(3)  ]   $
200                                        ,d:[strdtmp1.vardep_ndim.(3),lasdd[uubb].(4)  ]  }
201                        endif else bbvdnd = strdtmp1.vardep_ndim ; ici pas d update var a faire (updatevara=0)
202                        unlimtaba[dimwzonlylast-1] = 1 ; update de unlim !!!
203                        ;si dnames_imposed=1, on a selectionne des dims de meme nom ou nom non impose, donc nomdim=dnama[iid],
204                        ;si dnames_imposed=0, le nom de notre dim courante peut changer pour assimile a ancien nomdim dnamoss[dimwzonlylast-1]
205                        ; -> ok gere par dnames_imposed... continue plus haut
206                        if n_elements(dnama) ne 0 then dnamoss[dimwzonlylast-1] = dnama[iid]
207                        strdtmp2={ dimid:strdtmp1.dimid,taille:strdtmp1.taille,nomdim:dnamoss[dimwzonlylast-1] $
208                                   ,unlimz:unlimtaba[dimwzonlylast-1],vardep_ndim:bbvdnd} ; on passe en unlim=1 ICI
209                        com='strd'+strnbdu+'=strdtmp2'
210                        if not execute(com) then message, $
211                          'ERR : update strd unlim dim '+strnbdu+', loop: dim'+iidp1st+', var'+nviv+'... stop 0'
212                        strdtmp1 = 0 & strdtmp2 = 0
213                    end
214                    0:begin
215                        ; aucune dim ne contient que des vars en last dim --> on doit cree une new dim
216                        ; --> la dim iidp1st = nbdimvv sera donc pas creee mais assimilee a celle-ci
217                        ;     on ne cree bien qu une seule dim au max par passage sur indice iid
218
219                        ; pour creer nouvelle dim a laquelle la courante sera assimilee, il faut que les variables
220                        ; ramenees dedans, proviennent de dim qui le permettent, vis a vis de nom de dim imposee et/ou unlim impose
221                        noka = 0
222                        for iud=0,n_elements(lasdd)-1 do begin
223                            if ( impose_dnm_unl[1, lasdd[iud].(0)-1 ] eq 0) then begin ; car unlim passe de 0 a 1 pour ces dim de vars
224                                ndst = string(ndimtot, format = fmtbase)
225                                if n_elements(dnama) ne 0 then dnamur = dnama[iid] else dnamur = dst+ndst
226                                if  ( ( impose_dnm_unl[0, lasdd[iud].(0)-1 ] eq 0 ) or ( dnamur eq  dnamoss[lasdd[iud].(0) -1]) ) then begin
227                                    if noka eq 0 then begin
228                                        lasddoka = [lasdd[iud]]
229                                        listdwlastoka = [lasdd[iud].(0)]
230                                    endif else begin
231                                        lasddoka = [lasddoka,lasdd[iud]]
232                                        listdwlastoka = [listdwlastoka,lasdd[iud].(0)]
233                                    endelse
234                                    noka = noka + 1
235                                endif else begin
236                                    if n_elements(notlasddoka) eq 0 then begin
237                                        if n_elements(notlasdd) eq 0 then notlasddoka = [lasdd[iud]]  $
238                                          else notlasddoka = [notlasdd, lasdd[iud]]
239                                    endif else notlasddoka = [notlasddoka, lasdd[iud]]
240                                endelse
241                            endif
242                        endfor
243                        if noka ne 0 then begin
244                            updatevara=1
245                            ndimtot = ndimtot+1
246                            ndst = string(ndimtot, format = fmtbase)
247                            dimsizes = [dimsizes, nn]
248                            dimidas = [dimidas, dst+ndst]
249                            lasto=1
250                            unlimtaba = [unlimtaba,unlima] ; rappel : unlima =1
251                            if n_elements(dnama) ne 0 then dnamoss = [dnamoss, dnama[iid]] else dnamoss = [dnamoss, dimidas[ndimtot-1]]
252                            impose_dnm_unl = [[impose_dnm_unl],[dnames_imposed,unl_imposed]] ; tablo: ix=2, jy=ndimtot
253                            ddvdnd = {  a:[lasddoka[*].(1)  ]    $
254                                        ,b:[lasddoka[*].(2)  ]   $
255                                        ,c:[lasddoka[*].(3)  ]   $
256                                        ,d:[lasddoka[*].(4)  ]  }
257                            com = 'strd'+ndst+' = { ' $
258                              +' dimid:dimidas[ndimtot-1],taille:nn,nomdim:dnamoss[ndimtot-1],unlimz:unlimtaba[ndimtot-1]' $
259                              +',vardep_ndim:ddvdnd } '
260                            if not execute(com) then message, 'ERR : a la def (3) de la structure de dim' $
261                              +iidp1st+', var'+nviv+'... stop'
262                        endif ; else aucune last var de dim est ok pour aller ds la nouvelle dim creable... elle se creera toute seule apres
263                    end
264                    else:begin
265                        print, ' *** WARNING !!! on trouve 2 dims ou plus, que l on peut mettre en unlimited (assimilees a la dim '      $
266                              +'unlimited demandee)... pour ne pas choisir ou supprimer une dim, on ne change aucune dim en unlimited. ' $
267                              +' --> Pour lever l''ambiguite si besoin, utiliser les champs unlim et dnames pour imposer des noms '      $
268                              +'et caracteristiques de dimensions et donner plus de contraintes pour la construction du netcdf (ou bien ' $
269                              +'activer le mot cle /NOT_OUASSALU pour ne pas uniformiser les last dim des vars a unlimited dim).'
270                        ;message, 'PB Z : on ne peut avoir que 0 ou max 1 dim avec que des var lasto ' $
271                        ;              +'(dim'+iidp1st+', var'+nviv+')...stop'
272                    end
273                endcase
274                ;
275                ; on doit egalement enlever ces vars des struct de dim ou on les a prises
276                ;
277                if updatevara eq 1 then begin
278
279                    if nnndz eq 0 then begin
280                        listdwlast = listdwlastoka
281                        notlasdd = notlasddoka
282                    endif
283
284                    dimdone = [-1]
285                    FOR iad = 0, n_elements(listdwlast)-1 DO BEGIN ; on parcourt les dims de listdwlast, mais que une fois par dim size
286                        IF (where(dimdone eq listdwlast[iad]))[0] EQ -1 THEN BEGIN ; si cette dim est pas encore faite, on la fait
287                            if nnndz eq 1 then if listdwlast[iad] eq dimwzonlylast then continue ;on saute dimwz si exist
288                            strnbdv = string(listdwlast[iad],format=fmtbase)
289                            com = 'strdtmp1 = strd'+strnbdv
290                            if not execute(com) then message, $
291                              'ERR : attrib strdtmp 0d dim loc'+strnbdv+' (dim'+iidp1st+', var'+nviv+')...stop'
292                            if n_elements(notlasdd) ne 0 then begin
293                                oobb = where(notlasdd[*].(0) eq listdwlast[iad]) ; dim de notlast concernee
294                                if oobb[0] eq -1 then message,'PB : 0 ou 1 max dim wz only last var ' $
295                                  +'dim loc'+istrnbdv+' (dim'+iidp1st+', var'+nviv+')...stop a PB Z expected'
296                                ccvdnd = {  a:[ notlasdd[oobb].(1)  ]   $
297                                            ,b:[ notlasdd[oobb].(2)  ]   $
298                                            ,c:[ notlasdd[oobb].(3)  ]   $
299                                            ,d:[ notlasdd[oobb].(4)  ]  }
300                                strdtmp2={  dimid:strdtmp1.dimid,taille:strdtmp1.taille,nomdim:strdtmp1.nomdim $
301                                            ,unlimz:strdtmp1.unlimz,vardep_ndim:ccvdnd}
302                                com='strd'+strnbdv+'=strdtmp2'
303                                if not execute(com) then message, 'ERR : update strd unlim, dim loc'+strnbdv $
304                                  +', loop: dim'+iidp1st+', var'+nviv+'... stop 1'
305                                strdtmp1 = 0 & strdtmp2 = 0
306                            ENDIF
307                            IF iad EQ 0 THEN dimdone = [listdwlast[iad]] ELSE dimdone =  [dimdone, listdwlast[iad]]
308                        ENDIF
309                    endfor
310
311                endif ; else pas besoin de faire update sur les var car on a juste mis unlim a 1 ds dimwzonlylas
312
313            endif ; else... on n a pas de dim meme taille dont une var depend en last dim --> on va creer new dim
314
315        endif ; else... pas de dim deja definie et de meme taille, donc on va creer une new dim
316
317    endif else begin ; else... on a deja une dim de meme taille et unlim=1, donc elle DOIVENT etre les memes car une seule dim unlim=1
318
319        strnbd = string(aaddo[0]+1,format=fmtbase)
320        com = 'strdtmp = strd'+strnbd
321        if not execute(com) then message, 'ERR : attrib strdtmp 0d (dim'+iodp1st+', var'+nviv+')...stop'
322        if dnames_imposed eq 1 then if not (strdtmp.nomdim eq dnama[n_elements(dnama)-1]) then $
323          message,'PB : on specifie 2 dimensions unlimited avec 2 noms differents... impossible... stop'
324
325    endelse
326
327endelse
328
329;print,'d',inv,unlima
330
331; -------
332
333; (3) re-mise en forme en supertab pour passer au prog principal
334
335for ikd=0,ndimtot-1 do begin ; loop on dims pour mettre les champs vardep_ndim des struc dim en liste chainee
336    ikdp1st = string(ikd+1,format=fmtbase)
337    com = 'strdlc = writenc_str2strlc(strd'+ikdp1st+')'
338    if not execute(com) then message,'PB : writenc_unlimdim_update loop2 on dim tot ('+ikdp1st+'), dim '+iidp1st+', var '+nviv+'... stop'
339    if ikd eq 0 then supertab = [strdlc] else supertab = [supertab, strdlc]
340endfor           ; on obtient ici supertab = [strd01lc ,strd02lc ....]
341
342end
343
344;----------------------------------------------------------------------------------------------
345;
346;+
347; SUBROUTINE (2)/(3) :
348;
349; on remplace la 4e structure de structa par une liste chainee afin
350; d uniformiser les format de strd (cf prog write_ncdf) pour les
351; passer facilement en argument au sous-prog writenc_unlimdim_update, sous forme de tablo de structures de
352; meme type !!!! (utilise si writenc_unlimdim_update est utilise i.e. dans le cas ou la cle NOT_OUASSALU
353; est pas active, i.e. cas par defaut)
354;
355;-
356function writenc_str2strlc, structa
357
358; --------
359
360strdtmp = structa
361strvarsdim = strdtmp.vardep_ndim
362
363vnmarr = strvarsdim.(0)
364ddparr = strvarsdim.(1)
365nvararr = strvarsdim.(2)
366lastad = strvarsdim.(3)
367
368nvardepa = n_elements(lastad)
369
370if nvardepa lt 1 then message,'PB : aucune var ne depend de cette dim... impossible... stop'
371
372; Create an anonymous structure to contain list elements. Note that
373; the next field is initialized to be a null pointer.
374
375llistvofd01 = {vname:'', numdimdep:0, nvar:0, dlast:0, next:ptr_new()}
376
377if ptr_valid(fst_llistvofd01) then ptr_free,fst_llistvofd01
378
379first_varsd01 = ptr_new(llistvofd01)
380
381current = first_varsd01
382
383for iidv=0,nvardepa-1 do begin
384
385    next = ptr_new({vname:'', numdimdep:0, nvar:0, dlast:0, next:ptr_new()})
386
387    ; set the name field of 'current' to the input string.
388
389    (*current).vname = vnmarr[iidv]
390    (*current).numdimdep = ddparr[iidv]
391    (*current).nvar = nvararr[iidv]
392    (*current).dlast = lastad[iidv]
393
394    ; prepare the next field of 'current' to the pointer to the next list element.
395
396    (*current).next = next
397
398    ; copy the 'current' pointer to 'last'
399
400    last = current
401
402    ; make 'current' the next pointer.
403
404    current = next
405
406endfor
407
408if ptr_valid(next) then ptr_free, next
409
410; Set the _next_ field of the last element to the null pointer.
411
412if ptr_valid(last) then (*last).next = ptr_new()
413
414; --------
415
416strdout_ptr = {  dimid:strdtmp.dimid, taille: strdtmp.taille , nomdim: strdtmp.nomdim , unlimz: strdtmp.unlimz   $
417                ,vardep_ptr : first_varsd01 }
418
419return,strdout_ptr
420
421end
422
423;+
424;
425; SUBROUTINE (3)/(3) :
426;
427; convertit une structure contenant une liste
428; chainee en structure classique utilisee par le main prog (utile pour
429; passer ces structures en argument au sous-prog
430; writenc_unlimdim_update, i.e. dans le cas ou la cle NOT_OUASSALU n
431; est pas activee, i.e. cas par defaut)
432;
433;-
434function writenc_strlc2str, strwlist
435
436ptr_firstvars = strwlist.vardep_ptr
437
438; create a second pointer to the heap variable pointed at by 'first'
439current = ptr_firstvars
440
441invdp = 0
442
443while ptr_valid(current) do begin
444
445    if invdp eq 0 then begin
446        vnmarr  = [ (*current).(0) ]
447        ddparr  = [ (*current).(1) ]
448        nvararr = [ (*current).(2) ]
449        lastad  = [ (*current).(3) ]
450    endif else begin
451        vnmarr  = [ vnmarr, (*current).(0)     ]
452        ddparr  = [ ddparr, (*current).(1) ]
453        nvararr = [ nvararr, (*current).(2)     ]
454        lastad  = [ lastad, (*current).(3)      ]
455    endelse
456
457  ; set 'current' equal to the pointer in its own next field.
458  current = (*current).next
459
460  invdp = invdp + 1
461
462endwhile
463
464if invdp eq 0 then message,'PB : aucune var ne depend de cette dim... impossible 2 ... stop'
465
466strwolist = { dimid:strwlist.dimid, taille: strwlist.taille , nomdim: strwlist.nomdim , unlimz: strwlist.unlimz   $
467              ,vardep_ndim: {a:vnmarr,b:ddparr,c:nvararr,d:lastad}}
468
469return, strwolist
470
471end
472
473;----------------------------------------------------------------------------------------------
474;
475; END SECONDARY SUBROUTINES
476; -------------------------
477;
478;----------------------------------------------------------------------------------------------
479
480; ... ... .... ...    .. . ..  .
481
482;----------------------------------------------------------------------------------------------
483;
484; MAIN SUBROUTINE
485; ---------------
486;
487;----------------------------------------------------------------------------------------------
488;+
489;
490; pro write_ncdf, var01,var02,var03,var04,var05,var06,var07,var08,var09,var10               $
491;                ,var11,var12,var13,var14,var15,var16,var17,var18,var19,var20               $
492;                ,var21,var22,var23,var24,var25,var26,var27,var28,var29,var30               $
493;                ,FILENAME=filename                                                         $
494;                ,GLOBATTR=globattr                                                         $
495;                ,VARNAME=namevquick
496;
497; ---------------------------------------------------------------------------------------------
498;
499; @file_comments
500; Construct a netcdf file containing up to 30 variables of any
501; dimension (limited to 99 for now) with any attributes specified.
502; We use structures to pass the fields (var and their attributes, and
503; global attr)
504;
505; @returns
506; a netcdf file containing the variable in the format specified
507; through keywords and variables
508;
509; @param var01 {in}{required}
510;   - It can be simply a variable (scalar or array, of type :
511;     byte,int,long,float,double or string), or a structure
512;     containing the variable and its properties and attributes. At
513;     least one variable must be specified.
514;   - If a structure is given it should be of the following form (exple):
515;     vv1 = {var:xaxis,name:'nav_lon',dname:'x',at0:{a:'units',b:'degrees_east'},at1:{a:'title',b:'longitude'}}
516;     vv4 = {var:rain, name:'rain', unlim:1, dname:['x','y','t'],at0:{a:'units',b:'mm/day'},at4:{a:'missing_value',b:-9999.}}
517;     Namely, the if vv1 is a structure it MUST follow the following points:
518;       - attributes fields for the variable (at0,at1...) MUST be the last fields of the vv1 structure
519;         and name of those fields (at0,at1...) are not important.
520;       - attributes MUST themselves be given in the form of a 2 field structure, containing the
521;         name of the attribute (a string), and its value (can be any type as the ones of variable)
522;       - order of the first fields is not important but they MUST have the names:
523;           'var'      : for the variable (scalar or array, of type:byte,int,long,float,double or string)
524;           'name'     : for its name (a string), default value is var01,var02 etc...
525;           'unlim'    : = 1 to specify that the last dim of the var must be UNLIMITED, =0 or not specified otherwise
526;           'dname'    : to give the names of the dimensions of the variable, in the same order as the var dimensions.
527;                        it is an array of string of dim = nbre de dim de la var. default is d01,d02 etc...
528;       - the field 'var' MUST be there (a variable) but every others are optional
529;       - if a missing value exists for the variable and one wants to specify it, it MUST be specified
530;         somewhere in one of the attributes and the name of this attribute MUST be 'missing_value' (to be taken
531;         into account in the computing of the min-max of the variable), missing_value being not case sensitive
532;         (MISSING_VALUE is also ok)
533;
534; @param  var02, var03, .... var30 {in}{optional}
535; All the variables/attributes to be written in the netcdf file, in
536; the same way as the var01 (cf info above)
537;
538; @keyword filename {in}{optional}
539;  - a string giving the filename (including the path of the file)
540;  - if not specified, it is set to iodir+'writenclem.nc'
541;
542; @keyword globattr {in}{optional}
543;  - a structure containing the global attributes for the
544;    file. Similarly as for the attributes of the variable, this
545;    structure contains 2-fields structures which are the global
546;    attribute (first their name and second their value)
547;    exple: glbatt = {gb1:{a:'Grid',b:'regular 0.25'},gb2:{a:'Production',b:'clem'+systime()}}
548;  - if not specified in globattr, default case set production='date of
549;    day' as a global attribute
550;
551; @keyword VARNAME {in}{optional}
552;  - an array of char, same number of elements as the number of given
553;    var
554;  - if specified, it gives the names of the variables as an array for
555;    the default name values (if one of the var is structure and also has
556;    the name field given, then the latter will be the one chosen and not namevquick)
557;
558; @uses
559; <pro>cm_general</pro> for iodir variable
560;
561; @examples
562;
563; 1)
564;   IDL> write_ncdf, vvsst, btoa
565;
566; 2)
567;   IDL> write_ncdf, a1, {var:a2,name:'rain'}, ['up','down','fix'], a4, a5, {var:a6,unlim:1,name:'sst',dname:['x','y','z','time']}
568;
569; 3)
570;   IDL> write_ncdf,v031tr,msf031dn,msf031up,v031,vmaskloc,btoa,runame,titplo1,vargrid,nytt                                    $
571;           ,varname = ['v031tr','msf031dn','msf031up','v031','vmaskloc','btoa','runame','titplo1','vargrid','nytt'] $
572;           ,filename = iodir+'IDL_DATA/'+'waza3.nc'
573;
574; 4)
575;   IDL> fileoutnc = iodir+'OBS/TRMM/'+'trmm_1d_'+iyystr+'0101_'+iyystr+'1231_reg0.25.nc'
576;   IDL> vv1 = {var:xaxis,name:'nav_lon',dname:'x',at1:{a:'units',b:'degrees_east'},at2:{a:'title',b:'longitude'}}
577;   IDL> vv2 = {var:yaxis,name:'nav_lat',dname:'y',at1:{a:'units',b:'degrees_north'},at2:{a:'title',b:'latitude'}}
578;   IDL> vv3 = {var:ttt,name:'time',dname:'time_counter',unlim:1,at1:{a:'units',b:timeunit},at2:{a:'title',b:'julian days'}  $
579;   IDL> vv4 = {var:rain_i2, name:'rain' $
580;        ,at1:{a:'units',b:'mm/day'} $
581;        ,at2:{a:'title',b:'trmm daily accumulated rainfall derived from the 3-hourly product (mm)'}  $
582;        ,at3:{a:'scale_factor',b:scala_factor} $
583;        ,at4:{a:'add_offset',b:adda_offset}    $
584;        ,at5:{a:'missing_value',b:missaval_i2} $
585;       }
586;   IDL> glbatt={  gb1:{a:'File_Name', b:'trmm_1d_'+iyystr+'0101_'+iyystr+'1231_reg0.25.nc'} $
587;          ,gb2:{a:'Model_Name', b:'TRMM 3B42_V6 derived product'} $
588;          ,gb3:{a:'Source_File',b:'ftp://disc2.nascom.nasa.gov/data/TRMM/Gridded/Derived_Products/3B42_V6/Daily/'+iyystr+'/*.bin'} $
589;          ,gb4:{a:'IDL_Program_Name', b:'zz08_read_plot_row_trmm_precip.pro (clement@jamstec.go.jp)'}                              $
590;          ,gb5:{a:'Grid', b:'regular 0.25 degres resolution'}$
591;        }
592;   IDL> write_ncdf, vv1, vv2, vv3, vv4, filename=fileoutnc, globattr=glbatt
593;
594; @history
595; CBM 2007-09-10
596;
597; @todo
598; clem
599;
600;-
601pro write_ncdf, var01,var02,var03,var04,var05,var06,var07,var08,var09,var10    $ ; RQ : if more than 30 variables is needed, simply add
602               ,var11,var12,var13,var14,var15,var16,var17,var18,var19,var20    $ ;      var31,var32 etc... here and change nmaxvv to 32 ...
603               ,var21,var22,var23,var24,var25,var26,var27,var28,var29,var30    $
604               ,FILENAME=filename                                              $
605               ,GLOBATTR=globattr                                              $
606               ,VARNAME=namevquick                                             $
607                                                                               $
608               ,NOT_SDISV=flag1                                              $ ; mots cles non utiles sauf cas particuliers...
609               ,NOT_OUASSALU=flag2                                           $
610               ,OKNAN=oknan
611
612;
613; --> subroutine a tester avec le prog zz10_test_write_ncdf.pro par exemple...
614;     ou bien zz08_read_plot_row_trmm_precip_b
615;
616; -------
617
618compile_opt idl2, strictarrsubs ; idl2 --> les entiers sont des long par defaut ET [...] obligatoire pour les tablo
619                                ; strictarrsubs --> pas de depassement de tableau
620
621@cm_general   ; pour iodir si filename n est pas defini
622
623; -------
624
625writeout = 1  ; 1 pour ecrire info de base a l ecriture des vars, 0 sinon
626
627; -------
628
629; not_samedimname_in_same_var :
630; 1 : si on rencontre 2 dim de meme taille et meme unlim type ds une var on
631;     cree 2 dim differentes pour ne pas avoir 2 ou plus meme noms de dim
632;     dans une meme var (default)
633; 0 : on ne cree pas de dim nouvelle si on a la la meme taille et meme
634;     unlim dim definie deja pour cette var, exple: fltarr(n1,n1) ne
635;     creera qu une dim de nom 'x1' de taille n1
636
637if keyword_set(flag1) then not_samedimname_in_same_var = 0 else not_samedimname_in_same_var = 1
638
639; -------
640
641; ci-dessous
642; 0 pour definir une nouvelle dim par sa taille ET sa nature unlim, uniquement
643; 1 pour definir une nouvelle dim de la meme maniere, ET que si une dim est definie en unlim ALORS toutes les dim
644;   de meme taille ET last dim definie avant ou apres deviennent identiques a cette dim (ne font plus qu une), plutot que de
645;   definir, une dim de taille n0 ET not unlim en last dim de var01, ET une dim de taille n0 ET unlim=1 en last dim de var02 -->
646;   on defini la meme dim de taille n0 ET unlim pour les 2 vars var01 et var02 !! (default)
647
648if keyword_set(flag2) then oneunlim_all_samesizeandlast_unlim = 0 else oneunlim_all_samesizeandlast_unlim = 1
649
650; -------
651
652if writeout then print,'-------write_ncdf-------'
653
654; -------
655
656structfd_v = 'var'
657structfd_n = 'name'
658structfd_unl = 'unlim'
659structfd_dn = 'dname'
660
661ncfile_default = 'write_ncdf.nc'
662
663nmaxvv = 30
664nbdimmax = 99
665
666fmtbase='(i2.2)' ; lie au max de var et dim definissable, si moins de 99 i2.2 ok, sinon passer a i3.3 etc...
667
668; -------
669
670nbvars = n_params()
671
672if nbvars lt 1 then message,'ERR : donner au moins une var stp ... stop'
673if nbvars gt nmaxvv then message,'ERR : la fonction write_ncdf est pour le moment definie pour '+string(nmaxvv,format=fmtbase) $
674  +' variables. Pour l utiliser avec plus, simplement ajouter var31,var32 etc ds l''entete de la subroutine... stop'
675
676; -------
677
678if n_elements(namevquick) ne 0 and n_elements(namevquick) ne nbvars then $
679  message,'PB : varname=... (nom des vars par defaut) doit avoir le meme nombre d elements que le nbre de vars... stop'
680
681; -----------------------------------------------------------------------------------------------------------
682;
683; creation du fichier netcdf
684;
685; -----------------------------------------------------------------------------------------------------------
686
687if not(keyword_set(filename)) then ncfile=iodir+ncfile_default else ncfile=filename
688
689nposdir = strpos(ncfile,'/',/reverse_search)           ; --> controle de l existence du path menant au fichier
690dirr=strmid(ncfile,0,nposdir+1)
691if file_test(dirr,/directory) eq 0 then message,'ERR : le directory donne pour le fichier .nc n existe pas --> dir = '+dirr
692
693idout = ncdf_create(ncfile,/clobber)  ; --> create a netcdf file, automatically placed into define mode (/clobber = erase previous file)
694ncdf_control, idout, /nofill          ; --> data in the netcdf file is not pre-filled with default fill values
695
696; -----------------------------------------------------------------------------------------------------------
697;
698; define mode --> 1ere boucle sur les vars pour trouver les dimensions a definir et leurs caracteristiques
699;
700; -----------------------------------------------------------------------------------------------------------
701
702oktypcodarr = [1,2,3,4,5,7] ; --> correspond au type de var accepte par ncdf_vardef de idl : byte,int,long,float,double,string,
703
704varst='var'
705dst='d'
706
707dimiss='--'
708dim_gene=dimiss
709
710arr_struct = intarr(nbvars) - 1
711iattrv0 = intarr(nbvars) ; indice du premier attribut ds la structure
712typcodvv = intarr(nbvars) - 1
713nama = strarr(nbvars)
714nbdimvv = intarr(nbvars)
715nbtags = intarr(nbvars)
716listofdimnams = strarr(nbvars)
717;fieldfd = intarr(nbvars)
718
719firstdimcreated = 0
720ndimtot = 0
721
722for inv=0,nbvars-1 do begin
723
724    dnames_imposed = 0
725    unl_imposed = 0
726
727    ; init de var, qui doivent etre non def si non attribuee (cf plus bas)
728    dnama = 12 & zorglub = temporary(dnama)
729    lasdd = 12 & zorglub = temporary(lasdd)
730    notlasdd = 12 & zorglub = temporary(notlasdd)
731
732    invp1=inv+1
733    nviv=string(invp1,format=fmtbase)
734    commande= 'vvtmpstr=var'+nviv
735    if not execute(commande) then message,'PB : attribution a vvtmp de la var numero '+nviv+'... stop'
736
737    ;
738    ; attribution des elements de la structure ou du tablo au vars de base pour ecrire definir la var-attr ds le ncdf
739    ;
740
741    sstr = size(vvtmpstr)
742    nbdim = sstr[0]
743    typcod = sstr[nbdim+1]
744    if (where(oktypcodarr-typcod eq 0))[0] ne -1 then arr_struct[inv] = 0 ; --> var = scal or array of int, real, char, etc...
745    if typcod eq 8 then arr_struct[inv] = 1                               ; --> var = structure
746    if arr_struct[inv] eq -1 then message,'PB : la var numero '+nviv+' est ni un array (int, float, string etc...) ni une structure... stop'
747
748    case arr_struct[inv] of
749
750        0:begin   ; --> var = scal or array of int, real, char, etc...
751
752            vvtmp = vvtmpstr
753            ssvv  = size(vvtmp)
754            nbdimvv[inv] = ssvv[0]
755            typcodvv[inv] = ssvv[nbdimvv[inv]+1]
756
757            if typcodvv[inv] eq 7 then begin ; les chaines de char ont un format particulier en tant que tablo pour ecriture netcdf...
758                if nbdimvv[inv] eq 0 then ssvvdims = [ max(strlen(vvtmp))+1] else ssvvdims = [ max(strlen(vvtmp))+1,ssvv[1:nbdimvv[inv]] ]
759                nbdimvv[inv] = nbdimvv[inv] + 1
760            endif else begin
761                if nbdimvv[inv] eq 0 then ssvvdims = -12 else ssvvdims = ssvv[1:nbdimvv[inv]]
762            endelse
763
764            if n_elements(namevquick) eq 0 then nama[inv] = varst+nviv else nama[inv] = namevquick[inv]
765
766            unlima = 0
767
768            ;dnama = zorglub ; non defini (car init avec temporary), default value fixed when dim are created (cf hereunder)
769
770        end
771
772        1:begin   ; --> var = structure
773
774            nbtags[inv] = n_tags(vvtmpstr)
775            tagnamas = tag_names(vvtmpstr)
776
777            ; controle de la forme de la structure et def des elements
778
779            ; 1) champ necessaire --> la variable
780            fieldfound=0
781            for itg=0,nbtags[inv]-1 do begin
782                if strlowcase(tagnamas[itg]) eq structfd_v then begin
783                    com= 'vvtmp=vvtmpstr.'+structfd_v
784                    if not execute(com) then message,'ERR : attribution de vvtmp, 1ere boucle sur les vars, var num '+nviv+'... stop'
785                    ssvv  = size(vvtmp)
786                    nbdimvv[inv] = ssvv[0]
787                    typcodvv[inv] = ssvv[nbdimvv[inv]+1]
788                    if typcodvv[inv] eq 7 then begin ; les chaines de char ont un format particulier en tant que tablo pour ecriture netcdf...
789                        if nbdimvv[inv] eq 0 then ssvvdims = [ max(strlen(vvtmp))+1] $
790                          else ssvvdims = [ max(strlen(vvtmp))+1,ssvv[1:nbdimvv[inv]] ]
791                        nbdimvv[inv] = nbdimvv[inv] + 1
792                    endif else begin
793                        if nbdimvv[inv] eq 0 then ssvvdims = -12 else ssvvdims = ssvv[1:nbdimvv[inv]]
794                    endelse
795                    iattrv0[inv] = iattrv0[inv]+1
796                    fieldfound=1
797                endif
798                if fieldfound eq 1 then break
799            endfor
800            if fieldfound eq 0 then message,'ERR : le champ ''var'' est pas ds la structure (var num'+nviv+')... stop'
801
802            ; 2) champ optionnel --> le nom de la var
803            fieldfound=0
804            for itg=0,nbtags[inv]-1 do begin
805                if strlowcase(tagnamas[itg]) eq structfd_n then begin
806                    iattrv0[inv] = iattrv0[inv]+1
807                    com= 'nama[inv]=strcompress(vvtmpstr.'+structfd_n+')'
808                    if not execute(com) then message,'ERR : attribution de name of var num '+nviv+', 1ere boucle sur les vars... stop'
809                    if strlen(nama[inv]) eq 0 then message,'PB : nom de variable numero '+nviv+' vide, a respecifier...'
810                    fieldfound=1
811                endif
812                if fieldfound eq 1 then break
813            endfor
814            if fieldfound eq 0 then if n_elements(namevquick) eq 0 then nama[inv] = varst+nviv else nama[inv] = namevquick[inv]
815            ;fieldfd[inv] = fieldfound
816
817            ; 3) champ optionnel --> si last dimension est unlimited
818            fieldfound=0
819            for itg=0,nbtags[inv]-1 do begin
820                if strlowcase(tagnamas[itg]) eq structfd_unl then begin
821                    iattrv0[inv] = iattrv0[inv]+1
822                    com= 'unlima=vvtmpstr.'+structfd_unl
823                    if not execute(com) then message,'ERR : attribution de unlim of var num '+nviv+', 1ere boucle sur les vars... stop'
824                    if unlima ne 0 and unlima ne 1 then message,'PB : unlim vaut pas 0 ou 1 pour la var num '+nviv+'... stop'
825                    fieldfound=1
826                    unl_imposed = 1
827                endif
828                if fieldfound eq 1 then break
829            endfor
830            if fieldfound eq 0 then unlima = 0 ; unlimited=0 par defaut
831
832            ; 4) champ optionnel --> nom des dimensions
833            fieldfound=0
834            for itg=0,nbtags[inv]-1 do begin
835                if strlowcase(tagnamas[itg]) eq structfd_dn then begin
836                    iattrv0[inv] = iattrv0[inv]+1
837                    com= 'dnama=strcompress(vvtmpstr.'+structfd_dn+')'
838                    if not execute(com) then message,'ERR : attribution des dim name of var num '+nviv+', 1ere boucle sur les vars... stop'
839                    if n_elements(dnama) ne nbdimvv[inv] then message, 'PB : si on donne des noms de dim pour une var,' $
840                      +' donner autant de noms que de dims pour la var... stop'
841                    aahh = strlen(dnama)
842                    if (where(aahh eq 0))[0] eq -1 or n_elements(where(aahh eq 0)) ne n_elements(dnama) then begin
843                        ; si on a pas que des chaines vides -> ok
844                        if (where(aahh eq 0))[0] ne -1 then $
845                          message,'PB : un des noms (mais pas tous) des dim en input est vide... a respecifier... stop'
846                        if typcodvv[inv] eq 7 then dnama = ['d_strlen',dnama] ; on ajoute une dim donc un nom de dim aussi
847                        fieldfound=1
848                        dnames_imposed = 1 ; si on donne des noms de dim, alors elles seront creees a coup sur
849                                           ; (pas assimilees a d autres de meme taille ou autre...)
850                    endif else begin
851                        ; au cas ou on donne un tablo avec que des noms vide='', on considere que c est comme rien donner et on efface dnama
852                        zorglub = temporary(dnama)
853                    endelse
854                    ;print,'dnama=',dnama
855                endif
856                if fieldfound eq 1 then break
857            endfor
858            ;if fieldfound eq 0 then dnama = ... ; non def (car init avec temporary), default value fixed when dim are created (cf hereunder)
859
860        end
861
862        else:message,'wada t es pas la, impossible animal 1...'
863
864    endcase
865
866    if nbdimvv[inv] lt 0 or nbdimvv[inv] gt nbdimmax then message,'PB : sorry ben... moins de une ou plus de 99 dims... impossible... stop'
867    if inv ge 1 then begin
868        for invloc=0,inv-1 do if nama[inv] eq nama[invloc] then message,'PB : impossible de donner 2 noms identiques a 2 vars... stop'
869    endif
870
871    ;print,'NVIV = ',nviv
872
873    ; on cree les structures pour chaque dim, afin de definir celles-ci ensuite
874
875    if nbdimvv[inv] ne 0 then begin ; on a un vrai tablo, pas un scalaire
876
877        ;print, 'var numero', nviv, ' , ssvv=', ssvv
878
879        for iid = 0, nbdimvv[inv]-1 do begin
880
881            iidp1 = iid+1
882            iidp1st = string(iidp1, format = fmtbase)
883            ;nn = ssvv[iidp1]
884            nn = ssvvdims[iid]
885
886            ;print,'iidp1st = ',iidp1st
887
888            ;if n_elements(strd02) ne 0 then begin
889            ;    ;print,'unlim d02 = ',strd02.unlimz
890            ;endif
891
892            if firstdimcreated eq 0 then aadd = [-1] else begin
893
894                case iidp1 of
895
896                    ; (1) la dim de la var is the last one --> it can be unlimited
897
898                    nbdimvv[inv]:begin
899
900                        if oneunlim_all_samesizeandlast_unlim eq 1 then begin ; --> on update/create unlimited dimensions according to this one
901                            ptr_free,ptr_valid()
902                            for ikd=0,ndimtot-1 do begin ; loop on dims pour mettre les champs vardep_ndim des struc dim en liste chainee
903                                ikdp1st = string(ikd+1,format=fmtbase)
904                                com = 'strdlc = writenc_str2strlc(strd'+ikdp1st+')'
905                                if not execute(com) then message,'PB : loop on dim tot ('+ikdp1st+'), dim '+iidp1st+', var '+nviv+'... stop'
906                                if ikd eq 0 then supertab = [strdlc] else supertab = [supertab, strdlc]
907                            endfor ; on obtient ici supertab = [strd01lc ,strd02lc ....]
908                            writenc_unlimdim_update, dnames_imposed, unl_imposed, fmtbase, nviv, iidp1st, nn, dst,iid                   $
909                                                   , supertabu = supertab, dimsizesu=dimsizes, unlimtabau=unlimtaba, unlimau=unlima     $
910                                                   , dimidasu=dimidas, ndimtotu=ndimtot, dnamossu=dnamoss, dnamau=dnama                 $
911                                                   , impose_dnm_unlu = impose_dnm_unl
912                            for ikd=0,ndimtot-1 do begin ; on remet les struc avec liste chain en structures classiques du main prog
913                                ikdp1st = string(ikd+1,format=fmtbase)
914                                com = 'strd'+ikdp1st+' = writenc_strlc2str(supertab[ikd])'
915                                if not execute(com) then message,'PB : loop on dim tot ('+ikdp1st+'), dim '+iidp1st+', var '+nviv+'... stop'
916                            endfor
917                        endif ; oneunlim_all_samesizeandlast_unlim
918
919                         if dnames_imposed eq 1 then                                                             $
920                           aadd = where(dimsizes-nn eq 0 and unlimtaba eq unlima and dnamoss eq dnama[iid]) else $ ; case sensitive sur EQ char
921                           aadd = where(dimsizes-nn eq 0 and unlimtaba eq unlima) ; la dim cherchee peut etre unlim car last
922
923                    end
924
925                    ; (2) la dim de la var is not last --> cannot be unlimited
926
927                    else : begin
928
929                        if dnames_imposed eq 1 then                                                          $
930                          aadd = where(dimsizes - nn eq 0 and unlimtaba eq 0 and dnamoss eq dnama[iid]) else $ ; case sensitive sur EQ character
931                          aadd = where(dimsizes - nn eq 0 and unlimtaba eq 0)
932
933                    end
934
935                endcase
936
937            endelse
938
939            ;if inv eq 3 and iid eq 2 then begin
940            ;if inv eq 2 and iid eq 0 then begin
941            ;    ;print,'aadd inv 2, iid 0 =',aadd
942            ;    ;stop
943            ;endif
944
945            if aadd[0] eq -1 then begin
946
947                ; cette taille de dim existe pas deja ou pas en meme unlimited style, donc on cree la dim
948
949                ndimtot = ndimtot+1
950                ndst = string(ndimtot, format = fmtbase)
951                if firstdimcreated eq 0 and iid eq 0 then begin ; premiere dim cree
952                    dimsizes = [nn]
953                    dimidas = [dst+ndst]
954                    if iidp1 eq nbdimvv[inv] then unlimtaba = [unlima] else unlimtaba = [0]
955                    if n_elements(dnama) ne 0 then dnamoss = [dnama[iid]] else dnamoss = [dimidas[ndimtot-1]]
956                    impose_dnm_unl = [dnames_imposed,unl_imposed]
957                    firstdimcreated = 1
958                endif else begin
959                    dimsizes = [dimsizes, nn]
960                    dimidas = [dimidas, dst+ndst]
961                    if iidp1 eq nbdimvv[inv] then unlimtaba = [unlimtaba,unlima] else unlimtaba = [unlimtaba,0]
962                    if n_elements(dnama) ne 0 then dnamoss = [dnamoss, dnama[iid]] else dnamoss = [dnamoss, dimidas[ndimtot-1]]
963                    impose_dnm_unl = [[impose_dnm_unl],[dnames_imposed,unl_imposed]] ; tablo: ix=2, jy=ndimtot
964                endelse
965                if iidp1 eq nbdimvv[inv] then lasto=1 else lasto=0
966                com = 'strd'+ndst+' = { dimid:dimidas[ndimtot-1],taille:nn,nomdim:dnamoss[ndimtot-1],unlimz:unlimtaba[ndimtot-1]' $
967                                       +',vardep_ndim:{a:[nama[inv]],b:[iidp1],c:[invp1],d:[lasto],impos:impose_dnm_unl[ndimtot-1]} } '
968                if not execute(com) then message, 'ERR : a la def (1) de la structure de dim'+iidp1st+', var'+nviv+'... stop'
969
970            endif else begin
971
972                ; cette taille de dim existe avec same unlimited style, on checke si c est ds la meme var ou pas
973
974                nbsamedim = n_elements(aadd) ; au moins egal a 1 ou plus
975
976                if dnames_imposed eq 1 then if nbsamedim gt 1 then message,'PB : impossible d avoir 2 dim identiques deja definies... stop'
977
978                nbdsaminvar = 0
979                if not_samedimname_in_same_var eq 1 then begin
980                    ; ci-dessous:
981                    ; soit check 1ere dim of var: no same dim in var(nbdsaminvar=0), or elle existe deja, donc on utilise la 1ere identique
982                    ; soit on check la last (qui peut aussi etre la 1st), et si unlim=1 alors again: no same dim in var(nbdsaminvar=0), or ...
983                    ; soit on checke la last avec unlim=0 ou une var not last (donc unlim=0), et donc si size idem alors nbdsaminvar+1
984                    if dnames_imposed eq 0 then begin
985                        if not (iid eq 0 or (iidp1 eq nbdimvv[inv] and unlima eq 1) ) then $
986                          for iidloc = 0, iid-1 do if ssvvdims[iidloc] eq nn then nbdsaminvar = nbdsaminvar+1
987                    endif ; else nbdsaminvar = 0 --> arrive si dnames_imposed = 1
988                endif ; else nbdsaminvar = 0
989
990                if nbdsaminvar lt nbsamedim then begin
991
992                    ; pas besoin de creer, on peut se servir d une dim deja definie, juste mise a jour de strd de aadd[nbdsaminvar]+1
993
994                    ; on ne peut arriver que ici avec dnames_imposed = 1 car nbdsaminvar = 0 cf ci-dessus
995
996                    ;if inv eq 3 and iid eq 2 then ;print,'wada'
997
998                    strnbd = string(aadd[nbdsaminvar]+1, format = fmtbase)
999                    com = 'strdtmp = strd'+strnbd
1000                    if not execute(com) then message, 'ERR : attribution strdtmp 1 (dim'+iidp1st+', var'+nviv+')...stop'
1001                    if iidp1 eq nbdimvv[inv] then lasto=1 else lasto=0
1002                    aavardep_ndim = { a:[strdtmp.vardep_ndim.(0),nama[inv]],b:[strdtmp.vardep_ndim.(1),iidp1] $
1003                                     ,c:[strdtmp.vardep_ndim.(2),invp1],d:[strdtmp.vardep_ndim.(3),lasto]}
1004                    ;if iidp1 eq nbdimvv[inv] and unlima eq 1 then unlimnew = unlima else unlimnew = strdtmp.unlimz --> obsolete !!!
1005                    unlimnew = strdtmp.unlimz ; unlimz reste inchange car la dim re-utilisee est selectionnee sur taille ET unlim
1006                    ;if n_elements(dnama) ne 0 then dnamo = dnama[iid] else dnamo=strdtmp.nomdim
1007                    if n_elements(dnama) ne 0 then if dnama[iid] ne strdtmp.nomdim then $
1008                      message,'PB : impossible d etre la, car update une dim qui a un nom impose different... stop'
1009                    dnamo=strdtmp.nomdim ; on utilise le meme nom de l ancienne dim ok
1010                    com='strd'+strnbd+'={dimid:strdtmp.dimid,taille:nn,nomdim:dnamo,unlimz:unlimnew,vardep_ndim:aavardep_ndim} '
1011                    if not execute(com) then message, 'ERR : update vardep,unlimz, dim'+strnbd+', loop: dim'+iidp1st+', var'+nviv+'... stop'
1012
1013                    ;if inv eq 3 and iid eq 2 then stop
1014
1015                endif else if nbdsaminvar eq nbsamedim then begin
1016
1017                    ; on cree nouvelle dim, car cette taille de dim existe par exemple 2 fois avec 2 dimid noms differents
1018                    ; mais on doit en creer une troisieme (meme taille, nom different) car une var contient 3 fois cette taille de dim...
1019
1020                    ; pour pouvoir etre ici, une condition necessaire est (car sinon nbdsaminvar=0 or nbsamedim > 0):
1021                    ; not (iid eq 0 or (iidp1 eq nbdimvv[inv] and unlima eq 1))
1022                    ; donc on est (pas 1ere dim of var) ET (pas last dim of var OU pas unlim=1)
1023                    ; donc je peux etre last dim mais alors en unlim=0 seulement, sinon je suis une dim du milieu (pas 1ere, ni last)
1024                    ; DONC on ne cree jamais de dim unlim ici
1025
1026                    ndimtot = ndimtot+1
1027                    ndst = string(ndimtot, format = fmtbase)
1028                    dimsizes = [dimsizes, nn]
1029                    dimidas = [dimidas, dst+ndst]
1030                    if iidp1 eq nbdimvv[inv] then unlimtaba = [unlimtaba,unlima] else unlimtaba = [unlimtaba,0]
1031                    if unlimtaba[ndimtot-1] eq 1 then message,'PB : impossible de definir une structure de dim unlimited ici... stop'
1032                    if n_elements(dnama) ne 0 then dnamoss = [dnamoss, dnama[iid]] else dnamoss = [dnamoss, dimidas[ndimtot-1]]
1033                    if iidp1 eq nbdimvv[inv] then lasto=1 else lasto=0
1034                    impose_dnm_unl = [[impose_dnm_unl],[dnames_imposed,unl_imposed]] ; tablo: ix=2, jy=ndimtot, mis a jour
1035                    com = 'strd'+ndst+' = { dimid:dimidas[ndimtot-1],taille:nn,nomdim:dnamoss[ndimtot-1],unlimz:unlimtaba[ndimtot-1]' $
1036                                                                  +',vardep_ndim:{a:[nama[inv]],b:[iidp1],c:[invp1],d:[lasto] }} '
1037                    if not execute(com) then message, 'ERR : a la def (2) de la structure de dim'+iidp1st+', var'+nviv+'... stop'
1038
1039                endif else message, 'ERR : impossible d avoir plus de dim identiques '+iidp1st+' ds la var'+nviv+'que deja definies... stop'
1040
1041            endelse
1042
1043            ; checke que l on ne vient pas de creer une 2e dim differentes en unlimited...
1044            ; (ncdf_dimdef stop autrement, car une seule dim unlimited allowed)
1045
1046            if n_elements(where(unlimtaba eq 1)) ge 2 then message,'ERR : une 2e structure-dim unlimited (dim '+iidp1st+') vient '  $
1047              +'d etre creee, mais on ne peut definir qu une unique dim unlimited en netcdf... stop'
1048
1049        endfor
1050
1051    endif   ; else --> pas de dim a creer pour cette var qui est un scalaire ou string simple
1052
1053endfor
1054
1055; -------------------------------------------------------------------
1056;
1057; definition des dimensions
1058;
1059; -------------------------------------------------------------------
1060
1061; checke que l on n a pas mis deux dimensions differentes en unlimited... (ncdf_dimdef stop autrement, une seule dim unlimited)
1062
1063if n_elements(where(unlimtaba eq 1)) ge 2 then message,'ERR : plus de 2 dimensions unlimited ont ete prescrites... stop'
1064
1065; commande de base pour definir une dim :
1066;
1067; idout_of_the_dim = NCDF_DIMDEF(idout_of_the_nc_file, 'name_of_dim', n_size_of_dim)
1068;
1069; EXAMPLES:
1070;
1071; xidout = NCDF_DIMDEF(idout, 'x', n1)
1072; ou pour unlimited :
1073; tidout = NCDF_DIMDEF(idout, 'time', /unlimited) ; sans donner la taille de la dim !!!
1074;
1075; RQ :
1076;
1077; - si on a deux dim avec le meme nom, la definition des dim renvoie un message d erreur, OK
1078;
1079; - si on definit une dim unlimited (t1idout par exemple), et si 2 var a1=fltarr(5) et a2=fltarr(7) se reclament de cette dim
1080;   au moment du ncdf_vadef par id1=NCDF_VARDEF(idout,'a1',[t1idout],/FLOAT) et id2=...'a2'... ALORS la taille de la dim
1081;   unlimited sera egale a la plus grde des 2 dims (ici 7) et les valeurs pour a1[5] et a1[6]seront mises a 9.96921e+36 ds le netcdf !!!
1082;   --> ici on previent ce genre de choses, toutes les vars avec la dim unlim en dernier doivent avoir la meme taille pour
1083;       cette dim, quitte a mettre des missing_value au prealable pour combler certains tablos a la bonne taille
1084;       (plutot que des 9.96921e+36 non reconnaissable a priori)
1085;
1086; - avec une var tablo avec 2 (ou plus) dim de meme taille exple: fltarr(5,5), on peut
1087;   soit definir 2 dim de nom differents et de meme taille d01idout=NCDF_DIMDEF(idout,'d01',5) et d02..= 'd02' puis ncdf_vardef([d01,d02])
1088;   soit definir UNE SEULE DIM d01idout de taille 5 et faire pour la var: ncdf_vardef(... [d01idout,d01idout] ...), aussi accepte
1089
1090for ind=0,ndimtot-1 do begin
1091    indp1st = string(ind+1,format=fmtbase)
1092    char1 = 'strd' & char2 = '.taille,' & char3 = ''
1093    com = 'if strd'+indp1st+'.unlimz eq 0 then ndstr= char1+indp1st+char2 else ndstr=char3'
1094    if not execute(com) then message,'ERR : computing de ndstr pour la def de la dim'+indp1st+'... stop'
1095    com = 'dimida = strd'+indp1st+'.dimid'
1096    if not execute(com) then message, 'ERR : attrib dim id, pour la def de la dim '+indp1st+'... stop'
1097    dimida = dimida+'idout'
1098    com = dimida+' = ncdf_dimdef(idout, strd'+indp1st+'.nomdim, '+ndstr+' unlimited=strd'+indp1st+'.unlimz)'
1099    if not execute(com) then message,'ERR : definition de la dim '+indp1st+'... stop'
1100endfor
1101
1102; -------------------------------------------------------------------
1103;
1104; define mode --> 2e boucle sur les vars pour definir celles-ci
1105;
1106; -------------------------------------------------------------------
1107
1108; commande de base pour definir une var :
1109;
1110; id_of_the_var  = NCDF_VARDEF(id_of_the_nc_file, 'name_of_the_var', [id_of_the_dim_of_the_var_in_the_right_order], /type_of_var)
1111;
1112; RQ :
1113; - si on veut definir une var unlimited, ca doit etre la derniere
1114;   dim des variables. Si a2 = fltarr(n1, n4, n5, n3) alors la unlim ne
1115;   peut etre que n3
1116; - si on veut definir 2 vars avec le meme nom, on a un diag error par idl, ok
1117;
1118; EXAMPLE:
1119; id0  = NCDF_VARDEF(idout, 'a2', [xidout,tidout,yidout,zidout], /FLOAT)
1120;
1121
1122for inv=0,nbvars-1 do begin
1123
1124    ;
1125    ; --> Def des vars
1126    ;     ------------
1127
1128    nviv=string(inv+1,format=fmtbase)
1129
1130    ; type de la var a ecrire
1131    tpv = intarr(6)
1132    case typcodvv[inv] of
1133        1:tpv[0]=1 ; byte
1134        2:tpv[1]=1 ; short (int)
1135        3:tpv[2]=1 ; long
1136        4:tpv[3]=1 ; float
1137        5:tpv[4]=1 ; dble
1138        7:tpv[5]=1 ; char
1139        else:message,'PB : le type de la var num '+nviv+' est pas accepte par ncdf idl (not byte,int,real...) ... stop'
1140    end
1141    flagstype = 'BYTE=tpv[0],SHORT=tpv[1],LONG=tpv[2],FLOAT=tpv[3],DOUBLE=tpv[4],CHAR=tpv[5]'
1142
1143    listofdims = ''
1144    listofdimnams[inv] = ''
1145    if nbdimvv[inv] ne 0 then begin ; on a un vrai tablo, pas un scalaire --> on recherche le nom des dims de la var a mettre ds listofdims=...
1146
1147        for iid = 0, nbdimvv[inv]-1 do begin ; boucle sur les dims de la var ds ordre des dim de la var
1148
1149            iidp1 = iid+1
1150            iidp1st = string(iid+1,format=fmtbase)
1151
1152            ndimdepfd = 0
1153            for ind=0,ndimtot-1 do begin     ; boucle sur les dims globales qui ont ete definies precedemment
1154                indp1st = string(ind+1,format=fmtbase)
1155                com = 'namvararr = strd'+indp1st+'.vardep_ndim.(0)'
1156                if not execute(com) then message, 'ERR : attrib namvararr, dim glob '+indp1st+',dim var '+iidp1st+',var num '+nviv+'... stop'
1157                com = 'numdimvararr = strd'+indp1st+'.vardep_ndim.(1)'
1158                if not execute(com) then message, 'ERR : attrib numdimvararr, dim glob '+indp1st+',dim var '+iidp1st+',var num '+nviv+'... stop'
1159                aaa = where(namvararr eq nama[inv] and numdimvararr eq iidp1)
1160                if aaa[0] ne -1 then begin
1161                    com = 'dimnam = strd'+indp1st+'.nomdim'
1162                    if not execute(com) then message, 'ERR : attrib dimnam, dim glob '+indp1st+',dim var '+iidp1st+',var num '+nviv+'... stop'
1163                    com = 'dimdep = strd'+indp1st+'.dimid'
1164                    if not execute(com) then message, 'ERR : attrib dimdep, dim glob '+indp1st+',dim var '+iidp1st+',var num '+nviv+'... stop'
1165                    dimdep = dimdep+'idout'
1166                    ; check unlim en last dim ok
1167                    com = 'unlimdd = strd'+indp1st+'.unlimz'
1168                    if not execute(com) then message, 'ERR : attrib unlimdd, dim glob '+indp1st+',dim var '+iidp1st+',var num '+nviv+'... stop'
1169                    if unlimdd eq 1 and iidp1 ne nbdimvv[inv] then $
1170                      message,'PB : cannot define var with unlim dim '+iidp1st+' which is not last of var'+nviv+' (dimglo'+indp1st+')... stop'
1171                    IF unlimdd EQ 1 THEN dimnam = dimnam+'*'
1172                    ; ---
1173                    ndimdepfd=ndimdepfd + 1
1174                endif
1175            endfor
1176
1177            case ndimdepfd of
1178                0:message,'PB : on ne trouve aucun nom de dim glob pour la dim '+iidp1st+' de la var '+nviv+'... stop'
1179                1:begin
1180                    if iid eq 0 then listofdims=dimdep else listofdims=listofdims+','+dimdep
1181                    if iid eq 0 then listofdimnams[inv]=dimnam else listofdimnams[inv]=listofdimnams[inv]+','+dimnam
1182                end
1183                else:message,'PB : on trouve plus de 1 nom de dim glob pour la dim '+iidp1st+' de la var '+nviv+'... stop'
1184            endcase
1185
1186        endfor
1187
1188        listofdims='['+listofdims+'],' ; listofdims doit etre de la forme : '[...] ,'
1189
1190    endif ; else listofdims = ''
1191
1192    com='id'+nviv+'=NCDF_VARDEF(idout,nama[inv],'+listofdims+flagstype+')'
1193    if not execute(com) then message,'ERR : definition de la var '+nviv+' ... stop'
1194
1195    ;
1196    ; --> Def des attributs de la var
1197    ;     ---------------------------
1198
1199    ; ds le cas d une structure: la def des attributs (si existent) a ete specifiee ds la structure
1200
1201    missaval_flag = 0
1202
1203    if arr_struct[inv] eq 1 then begin ; --> ok var00 est une structure
1204
1205        com= 'vvtmpstr=var'+nviv
1206        if not execute(com) then message,'ERR : attribution de vvtmpstr, 2e boucle sur les var, var num '+nviv+'... stop'
1207
1208        if nbtags[inv] gt iattrv0[inv] then begin ; --> on a des attributs en plus
1209            nbattr = nbtags[inv] - iattrv0[inv]
1210            for iatr=0,nbattr-1 do begin
1211                iatrstp1=string(iatr+1,format=fmtbase)
1212                ;print, nviv, '--', iattrv0[inv], '--', iatr
1213                ss = size(vvtmpstr.(iattrv0[inv]+iatr))
1214                if ss[0] ne 1 or ss[2] ne 8 or n_tags(vvtmpstr.(iattrv0[inv]+iatr)) ne 2 then $
1215                  message, 'PB : l attribut numero '+iatrstp1+' de la var'+nviv+' n est pas une struc de 2 elements... stop'
1216                attnamtmp =  vvtmpstr.(iattrv0[inv]+iatr).(0)
1217                attxttmp = vvtmpstr.(iattrv0[inv]+iatr).(1)
1218                comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, attxttmp'
1219                if not execute(comm) then message,'PB : def attr numero'+iatrstp1+', var numero '+nviv+'... stop'
1220                if strlowcase(attnamtmp) eq 'missing_value' then begin ; --> si on trouve un attribut missval on memorise
1221                    missaval_flag = 1
1222                    missaval = attxttmp
1223                endif
1224            endfor
1225        endif
1226
1227    endif
1228
1229    ; attributs par defaut: valid_min et valid_max et infos sur missing value
1230
1231    if typcodvv[inv] ne 7 then begin ; --> si var est pas un char on peut calculer min et max
1232
1233        case arr_struct[inv] of
1234            0:com= 'vvtmp=var'+nviv
1235            1:com= 'vvtmp=vvtmpstr.'+structfd_v
1236            else:message,'ERR : impossible to be there... stop'
1237        endcase
1238
1239        if not execute(com) then message,'ERR : attribution de vvtmp, 2e boucle sur les var, var num '+nviv+'... stop'
1240
1241        if not keyword_set(oknan) then begin
1242            aak = where(not(float(finite(vvtmp))))
1243            if aak[0] ne -1 then $
1244              message,'PB : la var numero '+nviv+' contient des nan... pas propre ds un fichier netcdf (cf utilisation ferret et autre soft)' $
1245                     +', remplacer par des missing ou bien activer le mot-cle /oknan pour tolerer l''ecriture de Nan ds le fichier nc... stop'
1246        endif
1247
1248        writevalidminmax = 1 ; a priori on va ecrire un min et max value mais si que des missing alors on ne l ecrit pas en fait
1249
1250        if missaval_flag eq 1 then begin
1251
1252            ss = size(missaval)
1253            if ss[0] ne 0 or ss[1] ne typcodvv[inv] then message,'PB : la miss val est pas scalaire ou pas meme type que var '+nviv+'... stop'
1254            whhmiss = where(vvtmp eq missaval,complement=whhok)
1255            if whhmiss[0] eq -1 then begin
1256                if n_elements(vvtmp) gt 1 then begin
1257                    attnamtmp = 'valid_min_max'
1258                    attxttmp = 'missing value never occurs'
1259                    comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, attxttmp'
1260                    if not execute(comm) then message,'ERR : def extra attr miss val 0, var numero '+nviv+'... stop'
1261                endif
1262                aamax = max(vvtmp,min=aamin)
1263            endif else begin
1264                if whhok[0] ne -1 then begin
1265                    if n_elements(vvtmp) gt 1 then begin
1266                        attnamtmp = 'valid_min_max'
1267                        attxttmp = 'missing value occurs'
1268                        comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, attxttmp'
1269                        if not execute(comm) then message,'ERR : def extra attr miss val 1, var numero '+nviv+'... stop'
1270                    endif
1271                    aamax = max(vvtmp[whhok],min=aamin)
1272                endif else begin ; on a que des missing value
1273                    if n_elements(vvtmp) gt 1 then begin
1274                        attnamtmp = 'valid_min_max'
1275                        attxttmp = 'missing value always occurs'
1276                        comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, attxttmp'
1277                        if not execute(comm) then message,'ERR : def extra attr miss val 2, var numero '+nviv+'... stop'
1278                        writevalidminmax = 0
1279                    endif else aamax = max(vvtmp,min=aamin)
1280                endelse
1281            endelse
1282
1283        endif else begin
1284
1285            aamax = max(vvtmp,min=aamin)
1286            attnamtmp = 'valid_min_max'
1287            attxttmp = 'no missing value defined'
1288            comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, attxttmp'
1289            if not execute(comm) then message,'ERR : def extra attr miss val 3, var numero '+nviv+'... stop'
1290
1291        endelse
1292
1293        if writevalidminmax then begin
1294            attnamtmp = 'valid_min'
1295            comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, aamin'
1296            if not execute(comm) then message,'ERR : def miss val attr min, var numero '+nviv+'... stop'
1297            attnamtmp = 'valid_max'
1298            comm = 'NCDF_ATTPUT, idout, id'+nviv+', attnamtmp, aamax'
1299            if not execute(comm) then message,'ERR : def miss val attr max, var numero '+nviv+'... stop'
1300        endif
1301
1302    endif
1303
1304endfor
1305
1306; --------------------------------------------------------
1307;
1308; Definition des  attributs globaux
1309;
1310; --------------------------------------------------------
1311
1312attprod = 0
1313
1314if n_elements(globattr) ne 0 then begin ; --> on a prescrit des attributs globaux
1315
1316  if (size(globattr))[0] ne 1 or (size(globattr))[2] ne 8 then message, 'PB : les global attr doivent etre donne sous forme de struct... stop'
1317  nbtagsgb = n_tags(globattr)
1318  for igat = 0, nbtagsgb-1 do begin
1319    igatst = string(igat, format = '(i2.2)')
1320    ss = size(globattr.(igat))
1321    if ss[0] ne 1 or ss[2] ne 8 or n_tags(globattr.(igat)) ne 2 then $
1322      message, 'ERR : au glob attr numero'+igatst+' qui n est pas un structure de 2 elements... stop'
1323    gbatn = globattr.(igat).(0)
1324    gbatt = globattr.(igat).(1)
1325    NCDF_ATTPUT, idout, gbatn, gbatt, /global
1326    if gbatn eq 'Production' then attprod = 1
1327  endfor
1328
1329endif
1330
1331if attprod eq 0 then begin
1332  producta = systime()
1333  NCDF_ATTPUT, idout, 'Production', producta, /GLOBAL
1334endif
1335
1336; --------------------------------------------------------
1337;
1338; Fin de definition des variables
1339;
1340; --------------------------------------------------------
1341
1342NCDF_CONTROL, idout, /ENDEF ; --> take the open netCDF file out of define mode and into data mode
1343
1344; --------------------------------------------------------
1345;
1346; Ecriture des variables
1347;
1348; --------------------------------------------------------
1349
1350for inv=0,nbvars-1 do begin
1351
1352    nviv=string(inv+1,format='(i2.2)')
1353
1354    case arr_struct[inv] of
1355        0: comm = 'NCDF_VARPUT, idout, id'+nviv+', var'+nviv ; --> tablo
1356        1: comm = 'NCDF_VARPUT, idout, id'+nviv+', var'+nviv+'.'+structfd_v ; --> struct
1357        else:message,'ERR : ncdf_varput case...'
1358    endcase
1359
1360    if writeout and inv eq 0 then print,'Writing fields : '
1361    if writeout then print,'  '+nama[inv]+'['+listofdimnams[inv]+'] = var'+nviv
1362
1363    if not execute(comm) then message,'PB : ncdf_varput final... stop'
1364
1365endfor
1366
1367; --------------------------------------------------------
1368;
1369; Fermeture fichier netcdf
1370;
1371; --------------------------------------------------------
1372
1373NCDF_CLOSE, idout
1374
1375if writeout then print,'Written to '+ncfile
1376if writeout then print,'------------------------'
1377
1378; --------------------------------------------------------
1379; --------------------------------------------------------
1380; --------------------------------------------------------
1381
1382end
1383
1384; exemples of var  attr :
1385; -----------------------
1386; rain:units = "mm/day"
1387; rain:valid_min = -32700
1388; rain:valid_max = 32700
1389; rain:valid_range = -32700, 32700
1390; rain:standard_name = "rain1"
1391; rain:long_name = "monthly precipitation by merging gauge, 5 kinds of satellite estimates (GPI,OPI,SSM/I scattering, SSM/I emission and MSU)"
1392; rain:title = "monthly precipitation by merging gauge, 5 kinds of satellite estimates (GPI,OPI,SSM/I scattering, SSM/I emission and MSU)"
1393; rain:add_offset = 31.7f
1394; rain:scale_factor = 0.001f
1395; rain:missing_value = -1.f
1396; rain:lon = "nav_lon"
1397; rain:lat = "nav_lat"
1398
1399; exemples  of global attr :
1400; --------------------------
1401;
1402; File_Name        : trmm_1d_19980101_19981231_reg0.25.nc
1403; Model_Name       : TRMM 3B42_V6 derived product
1404; Source_File      : ftp://disc2.nascom.nasa.gov/data/TRMM/Gridded/Derived_Products/3B42_V6/Daily/'+iyystr+'/*.bin'
1405; IDL_Program_Name : zz08_read_plot_row_trmm_precip.pro
1406; Grid             : regular 0.25 degres resolution
1407; Title            : Weekly Topex/ers sea surface anomaly from oct 14th 1992 to feb 13th 2002
1408; Associate_file   :  ...
1409; Description      :  ...
1410
1411;
1412; exemple de creation fic ncdf avec fcts idl :
1413; --------------------------------------------
1414;
1415; ; creation du fichier de sortie et ecriture des vars
1416; idout = NCDF_CREATE(fic+'2',/clobber)
1417; NCDF_CONTROL, idout, /nofill
1418; ;
1419; ; Dimension
1420; xidout = NCDF_DIMDEF(idout, 'x', nxx)
1421; yidout = NCDF_DIMDEF(idout, 'y', nyy)
1422; tidout = NCDF_DIMDEF(idout, 'time_counter', /unlimited)
1423; ;
1424; ; Attributs globaux
1425; NCDF_ATTPUT, idout, 'title', 'Weekly Topex/ers sea surface anomaly from oct 14th 1992 to feb 13th 2002', /GLOBAL
1426; NCDF_ATTPUT, idout, 'production', 'Clement de Boyer (cdblod@lodyc.jussieu.fr)', /GLOBAL
1427; ;NCDF_ATTPUT, idout, 'description' $
1428; ;                  , ' ncecat 488 files of Topex/ers data on Indian Ocean and add a time counter', /GLOBAL
1429; NCDF_ATTPUT, idout, 'associate_file', prev_fic, /GLOBAL
1430; NCDF_ATTPUT, idout, 'time_stamp', systime(), /GLOBAL
1431; ;
1432; ; Def des variables
1433; id0  = NCDF_VARDEF(idout, 'nav_lon'      , [xidout, yidout        ], /FLOAT)
1434; id1  = NCDF_VARDEF(idout, 'nav_lat'      , [xidout, yidout        ], /FLOAT)
1435; id2  = NCDF_VARDEF(idout, 'time_counter' , [                tidout], /FLOAT)
1436; id3  = NCDF_VARDEF(idout, 'sla'          , [xidout, yidout, tidout], /FLOAT)
1437; ;
1438; ; Attributs variable 0 : lon
1439; NCDF_ATTPUT, idout, id0, 'units', 'degrees_east'
1440; NCDF_ATTPUT, idout, id0, 'valid_min', min(lon)
1441; NCDF_ATTPUT, idout, id0, 'valid_max', max(lon)
1442; NCDF_ATTPUT, idout, id0, 'long_name', 'Longitude at t-point'
1443; ;
1444; ; Attributs variable 1 : lat
1445; NCDF_ATTPUT, idout, id1, 'units', 'degrees_north'
1446; NCDF_ATTPUT, idout, id1, 'valid_min', min(lat)
1447; NCDF_ATTPUT, idout, id1, 'valid_max', max(lat)
1448; NCDF_ATTPUT, idout, id1, 'long_name', 'Latitude at t-point'
1449; ;
1450; ; Attributs variable 2 :
1451; NCDF_ATTPUT, idout, id2, 'units', origt
1452; NCDF_ATTPUT, idout, id2, 'calendar','leap'
1453; NCDF_ATTPUT, idout, id2, 'title', 'Time'
1454; NCDF_ATTPUT, idout, id2, 'long_name', 'Time axis'
1455; NCDF_ATTPUT, idout, id2, 'time_origin ', origt
1456; ; christophe style
1457; ;ayear=strtrim(string(year(0)),1)
1458; ;amonth=strtrim(string(month(0),format="(i2.2)"),1)
1459; ;aday=strtrim(string(day(0),format="(i2.2)"),1)
1460; ;NCDF_ATTPUT, idout, id3, 'units', 'days since '+ayear+'-'+amonth+'-'+aday+' 00:00:00'
1461; ;NCDF_ATTPUT, idout, id3, 'calendar', 'gregorian'
1462; ;NCDF_ATTPUT, idout, id3, 'long_name', 'Time axis'
1463; ;NCDF_ATTPUT, idout, id3, 'time_origin ', ayear+'-'+b(month(0)-1)+'-'+aday+' 00:00:00'
1464; ;
1465; ; Attributs variable 3 : vv
1466; NCDF_ATTPUT, idout, id3, 'units', 'M'
1467; NCDF_ATTPUT, idout, id3, 'missing_value',missval
1468; NCDF_ATTPUT, idout, id3, 'valid_min', min(vv)
1469; if countnomiss ne 0 then vvmw=vv[vvw]
1470; NCDF_ATTPUT, idout, id3, 'valid_max', max(vvmw)
1471; NCDF_ATTPUT, idout, id3, 'long_name', 'sea level anomaly'
1472; NCDF_ATTPUT, idout, id3, 'short_name', 'sla'
1473; ;
1474; ; fin def des variables
1475; NCDF_CONTROL, idout, /ENDEF
1476; ;
1477; ; Ecriture des variables
1478; NCDF_VARPUT, idout, id0, lon ; la longitude, var 0
1479; NCDF_VARPUT, idout, id1, lat ; la latitude, var 1
1480; NCDF_VARPUT, idout, id2, ttt ; le time (calendrier), var 2
1481; NCDF_VARPUT, idout, id3, vv ; la vv, var 3
1482; ;
1483; ; Fermeture fichier netcdf
1484; NCDF_CLOSE, idout
1485
1486; EXAMPLE de ncdf quickwrite... bof quoi...:
1487;
1488;              ncfile='!my.nc'
1489;              angle_attr={units:'degrees'}
1490;              wind_attr={units:'m s-1'}
1491;              press_attr={units:'pascals',missing_value:1e10}
1492;              g_attr={units:'m s-2'}
1493;              globattr={source:'My program',version:2}
1494;
1495;              ncfields = 'pressure[longitude,latitude,time]=p:press_attr; ' $
1496;                       + 'longitude[]=lons:angle_attr; ' $
1497;                       + 'latitude[]=lats:angle_attr; ' $
1498;                       + 'ubar[latitude,time]:wind_attr; ' $
1499;                       + 'year[*time]=yr; ' $
1500;                       + 'g=9.8:g_attr @ globattr'
1501;
1502;              @ncdf_quickwrite
1503;
Note: See TracBrowser for help on using the repository browser.