source: trunk/src/struct2nc.m @ 917

Last change on this file since 917 was 913, checked in by sommeria, 9 years ago

netcdf4 introduced, turb_correlation added

File size: 11.4 KB
Line 
1% 'struct2nc': create a netcdf file from a Matlab structure
2%---------------------------------------------------------------------
3% errormsg=struct2nc(flname,Data)
4%
5% OUTPUT:
6% errormsg=error message, =[]: default, no error
7%
8% INPUT:
9% flname: name of the netcdf file to create (must end with the extension '.nc')
10%  Data: structure containing all the information of the netcdf file (or netcdf object)
11%           with fields:
12%       (optional) .ListGlobalAttribute: list (cell array of character strings) of the names of the global attributes Att_1, Att_2...
13%                  .Att_1,Att_2...: values of the global attributes
14%      (requested) .ListVarName: list of the variable names Var_1, Var_2....(cell array of character strings).
15%      (requested) .VarDimName: list of dimension names for each element of .ListVarName (cell array of string cells)
16%       (optional) .VarAttribute: cell array of structures of the form .VarAttribute{ivar}.key=value, defining an attribute key name and value for the variable #ivar
17%      (requested) .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
18
19%=======================================================================
20% Copyright 2008-2015, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
21%   http://www.legi.grenoble-inp.fr
22%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
23%
24%     This file is part of the toolbox UVMAT.
25%
26%     UVMAT is free software; you can redistribute it and/or modify
27%     it under the terms of the GNU General Public License as published
28%     by the Free Software Foundation; either version 2 of the license,
29%     or (at your option) any later version.
30%
31%     UVMAT is distributed in the hope that it will be useful,
32%     but WITHOUT ANY WARRANTY; without even the implied warranty of
33%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34%     GNU General Public License (see LICENSE.txt) for more details.
35%=======================================================================
36
37function errormsg=struct2nc(flname,Data)
38if ~ischar(flname)
39    errormsg='invalid input for the netcf file name';
40    return
41end
42if ~exist('Data','var')
43     errormsg='no data  input for the netcdf file';
44    return
45end
46FilePath=fileparts(flname);
47if ~strcmp(FilePath,'') && ~exist(FilePath,'dir')
48    errormsg=['directory ' FilePath ' needs to be created'];
49    return
50end
51%check the validity of the input field structure
52[errormsg,ListDimName,DimValue,VarDimIndex]=check_field_structure(Data);
53if ~isempty(errormsg)
54    errormsg=['error in struct2nc:invalid input structure_' errormsg];
55    return
56end
57ListVarName=Data.ListVarName;
58%nc=netcdf.create(flname,'NC_CLOBBER');%,'clobber'); %create the netcdf file with name flname
59cmode = netcdf.getConstant('NETCDF4');
60cmode = bitor(cmode, netcdf.getConstant('CLASSIC_MODEL'));
61cmode = bitor(cmode, netcdf.getConstant('CLOBBER'));
62nc = netcdf.create(flname, cmode)
63
64%write global constants
65if isfield(Data,'ListGlobalAttribute')
66    keys=Data.ListGlobalAttribute;
67    for iattr=1:length(keys)
68        if isfield(Data,keys{iattr})
69             testvar=0;
70            for ivar=1:length(ListVarName)% eliminate possible global attributes with the same name as a variable
71                if isequal(ListVarName{ivar}, keys{iattr})
72                    testvar=1;
73                    break
74                end
75            end
76            if ~testvar               
77                eval(['cte=Data.' keys{iattr} ';'])
78                if (ischar(cte) ||isnumeric(cte)) &&  ~isempty(cte)%&& ~isequal(cte,'')
79                    %write constant only if it is numeric or char string, and not empty
80                    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),keys{iattr},cte)
81                end
82            end
83        end
84    end
85end
86%create dimensions
87dimid=zeros(1,length(ListDimName));
88for idim=1:length(ListDimName)
89     dimid(idim) = netcdf.defDim(nc,ListDimName{idim},DimValue(idim));
90end
91VarAttribute={}; %default
92testattr=0;
93if isfield(Data,'VarAttribute')
94    VarAttribute=Data.VarAttribute;
95    testattr=1;
96end
97varid=zeros(1,length(Data.ListVarName));
98for ivar=1:length(ListVarName)
99    varid(ivar)=netcdf.defVar(nc,ListVarName{ivar},'nc_double',dimid(VarDimIndex{ivar}));%define variable 
100end
101 %write variable attributes
102if testattr
103    for ivar=1:min(numel(VarAttribute),numel(ListVarName)) 
104        if isstruct(VarAttribute{ivar})
105            attr_names=fields(VarAttribute{ivar});
106            for iattr=1:length(attr_names)
107                attr_val=VarAttribute{ivar}.(attr_names{iattr});
108                if ~isempty(attr_names{iattr})&& ~isempty(attr_val)&&~iscell(attr_val)
109                    netcdf.putAtt(nc,varid(ivar),attr_names{iattr},attr_val);
110                end
111            end
112        end
113    end
114end
115netcdf.endDef(nc); %put in data mode
116for ivar=1:length(ListVarName)
117    if isfield(Data,ListVarName{ivar})
118        VarVal=Data.(ListVarName{ivar});
119        %varval=values of the current variable
120%        VarDimIndex=Data.VarDimIndex{ivar}; %indices of the variable dimensions in the list of dimensions
121        VarDimName=Data.VarDimName{ivar};
122        if ischar(VarDimName)
123            VarDimName={VarDimName};
124        end
125        siz=size(VarVal);
126        testrange=(numel(VarDimName)==1 && strcmp(VarDimName{1},ListVarName{ivar}) && numel(VarVal)==2);% case of a coordinate defined on a regular mesh by the first and last values.
127        testline=isequal(length(siz),2) && isequal(siz(1),1)&& isequal(siz(2), DimValue(VarDimIndex{ivar}));%matlab vector
128        testcolumn=isequal(length(siz),2) && isequal(siz(1), DimValue(VarDimIndex{ivar}))&& isequal(siz(2),1);%matlab column vector
129%             if ~testrange && ~testline && ~testcolumn && ~isequal(siz,DimValue(VarDimIndex))
130%                 errormsg=['wrong dimensions declared for ' ListVarName{ivar} ' in struct2nc.m'];
131%                 break
132%             end
133        if testline || testrange
134            if testrange
135                VarVal=linspace(VarVal(1),VarVal(2),DimValue(VarDimIndex{ivar}));% restitute the whole array of coordinate values
136            end
137            netcdf.putVar(nc,varid(ivar), double(VarVal'));
138        else
139            netcdf.putVar(nc,varid(ivar), double(VarVal));
140        end     
141    end
142end
143netcdf.close(nc)
144
145
146%'check_field_structure': check the validity of the field struture representation consistant with the netcdf format
147%------------------------------------------------------------------------
148% [errormsg,ListDimName,DimValue,VarDimIndex]=check_field_structure(Data)
149%
150% OUTPUT:
151% errormsg: error message which is not empty when the input structure does not have the right form
152% ListDimName: list of dimension names (cell array of cahr strings)
153% DimValue: list of dimension values (numerical array with the same dimension as ListDimName)
154% VarDimIndex: cell array of dimension index (in the list ListDimName) for each element of Data.ListVarName
155%
156% INPUT:
157% Data:   structure containing
158%         (optional) .ListGlobalAttribute: cell listing the names of the global attributes
159%                    .Att_1,Att_2... : values of the global attributes
160%         (requested)  .ListVarName: list of variable names to select (cell array of  char strings {'VarName1', 'VarName2',...} )
161%         (requested)  .VarDimName: list of dimension names for each element of .ListVarName (cell array of string cells)                         
162%         (requested) .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
163
164
165function [errormsg,ListDimName,DimValue,VarDimIndex]=check_field_structure(Data)
166errormsg='';
167ListDimName={};
168DimValue=[]; %default
169VarDimIndex={};
170if ~isstruct(Data)
171    errormsg='input field is not a structure';
172    return
173end
174if isfield(Data,'ListVarName') && iscell(Data.ListVarName)
175    nbfield=numel(Data.ListVarName);
176else
177    errormsg='input field does not contain the cell array of variable names .ListVarName';
178    return
179end
180%check dimension names
181if (isfield(Data,'VarDimName') && iscell(Data.VarDimName))
182    if  numel(Data.VarDimName)~=nbfield
183       errormsg=' .ListVarName and .VarDimName have different lengths';
184        return
185    end
186else
187    errormsg='input field does not contain the  cell array of dimension names .VarDimName';
188    return
189end
190nbdim=0;
191ListDimName={};
192
193%% main loop on the list of variables
194VarDimIndex=cell(1,nbfield);
195for ivar=1:nbfield
196    VarName=Data.ListVarName{ivar};
197    if ~isfield(Data,VarName)
198        errormsg=['the listed variable ' VarName ' is not found'];
199        return
200    end
201    sizvar=size(Data.(VarName));% sizvar = dimension of variable
202    DimCell=Data.VarDimName{ivar};
203    if ischar(DimCell)
204        DimCell={DimCell};%case of a single dimension name, defined by a string
205    elseif ~iscell(DimCell)
206        errormsg=['wrong format for .VarDimName{' num2str(ivar) ' (must be the cell of dimension names of the variable ' VarName];
207        return       
208    end
209    nbcoord=numel(sizvar);%nbre of coordinates for variable named VarName
210    testrange=0;
211    if numel(DimCell)==0
212        errormsg=['empty declared dimension .VarDimName{' num2str(ivar) '} for ' VarName];
213        return
214    elseif numel(DimCell)==1% one dimension declared
215        if nbcoord==2
216            if sizvar(1)==1
217                sizvar(1)=sizvar(2);
218            elseif sizvar(2)==1
219            else
220                errormsg=['1 dimension declared in .VarDimName{' num2str(ivar) '} inconsistent with the nbre of dimensions =2 of the variable ' VarName];
221                return
222            end
223            if sizvar(1)==2 && isequal(VarName,DimCell{1})
224                testrange=1;% test for a dimension variable representing a range
225            end
226        else
227            errormsg=['1 dimension declared in .VarDimName{' num2str(ivar) '} inconsistent with the nbre of dimensions =' num2str(nbcoord) ' of the variable ' VarName];
228            return
229        end
230    else
231        if numel(DimCell)>nbcoord
232            sizvar(nbcoord+1:numel(DimCell))=1;% case of singleton dimensions (not seen by the function size)
233        elseif nbcoord > numel(DimCell)
234            errormsg=['nbre of declared dimensions in .VarDimName{' num2str(ivar) '} smaller than the nbre of dimensions =' num2str(nbcoord) ' of the variable ' VarName];
235            return
236        end
237    end
238    DimIndex=[];
239    for idim=1:numel(DimCell) %loop on the coordinates of variable #ivar
240        DimName=DimCell{idim};
241        iprev=find(strcmp(DimName,ListDimName),1);%look for dimension name DimName in the current list
242        if isempty(iprev)% append the dimension name to the current list
243            nbdim=nbdim+1;
244            RangeTest(nbdim)=0; %default
245            if sizvar(idim)==2 && strcmp(DimName,VarName)%case of a coordinate defined by the two end values (regular spacing)
246                RangeTest(nbdim)=1; %to be updated for a later variable 
247            end
248            DimValue(nbdim)=sizvar(idim);
249            ListDimName{nbdim}=DimName;
250            DimIndex=[DimIndex nbdim];
251        else % DimName is detected in the current list of dimension names
252            if ~isequal(DimValue(iprev),sizvar(idim))
253                if isequal(DimValue(iprev),2)&& RangeTest(iprev)  % the dimension has been already detected as a range [min max]
254                    DimValue(iprev)=sizvar(idim); %update with actual value
255                elseif ~testrange               
256                    errormsg=['dimension declaration inconsistent with the size =[' num2str(sizvar) '] for ' VarName];
257                    return
258                end
259            end
260            DimIndex=[DimIndex iprev];
261        end
262    end
263    VarDimIndex{ivar}=DimIndex;
264end
Note: See TracBrowser for help on using the repository browser.