source: trunk/src/nc2struct.m @ 809

Last change on this file since 809 was 809, checked in by g7moreau, 10 years ago
  • Add license
File size: 14.5 KB
Line 
1%'nc2struct': transform a netcdf file in a corresponding matlab structure
2% it reads all the global attributes and all variables, or a selected list.
3% The corresponding dimensions and variable attributes are then extracted
4%----------------------------------------------------------------------
5% function [Data,var_detect,ichoice,errormsg]=nc2struct(nc,varargin)
6%
7% OUTPUT:
8%  Data: structure containing all the information of the netcdf file (or netcdf object)
9%           with (optional)fields:
10%                    .ListGlobalAttribute: cell listing the names of the global attributes
11%                    .Att_1,Att_2... : values of the global attributes
12%                    .ListVarName: list of variable names to select (cell array of  char strings {'VarName1', 'VarName2',...} )
13%                    .VarDimName: list of dimension names for each element of .ListVarName (cell array of string cells)                         
14%                    .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
15%                  .ListDimName=list of dimension (added information, not requested for field description)
16%                  .DimValue= vlalues of dimensions (added information, not requested for field description)
17%                  .VarType= integers giving the type of variable as coded by netcdf= 2 for char, =4 for single,=( for double
18%  var_detect: vector with same length as the cell array ListVarName, = 1 for each detected variable and 0 else.
19%            var_detect=[] in the absence of input cell array
20%  ichoice: index of the selected line in the case of multiple choice
21%        (cell array of varible names with multiple lines) , =[] by default
22%INPUT:
23%  nc:  name of a netcdf file (char string) or netcdf object   
24%  additional arguments:
25%       -no additional arguments: all the variables of the netcdf file are read.
26%       -a cell array, ListVarName, made of  char strings {'VarName1', 'VarName2',...} )
27%         if ListVarName=[] or {}, no variable value is read (only global attributes and list of variables and dimensions)
28%         if ListVarName is absent, or = '*', ALL the variables of the netcdf file are read.
29%         if ListVarName is a cell array with n lines, the set of variables will be sought by order of priority in the list,
30%            while output names will be set by the first line
31%       - the string 'ListGlobalAttribute' followed by a list of attribute  names: reads only these attributes (fast reading)
32%       - the string 'TimeVarName', a string (the name of the variable considered as time), an integer or vector with integer values
33%            representing time indices to select for each variable, the cell of other input variable names.
34%       - the string 'TimeDimName', a string (the name of the dimension considered as time), an integer or vector with integer values
35%            representing time indices to select for each variable, the cell of other input variable names.
36
37%=======================================================================
38% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
39%   http://www.legi.grenoble-inp.fr
40%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
41%
42%     This file is part of the toolbox UVMAT.
43%
44%     UVMAT is free software; you can redistribute it and/or modify
45%     it under the terms of the GNU General Public License as published
46%     by the Free Software Foundation; either version 2 of the license,
47%     or (at your option) any later version.
48%
49%     UVMAT is distributed in the hope that it will be useful,
50%     but WITHOUT ANY WARRANTY; without even the implied warranty of
51%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
52%     GNU General Public License (see LICENSE.txt) for more details.
53%=======================================================================
54   
55function [Data,var_detect,ichoice,errormsg]=nc2struct(nc,varargin)
56errormsg='';%default error message
57if isempty(varargin)
58    varargin{1}='*';
59end
60hhh=which('netcdf.open');% look for built-in matlab netcdf library
61
62if ~isequal(hhh,'')
63    %% default output
64    Data=[];%default
65    var_detect=[];%default
66    ichoice=[];%default
67   
68    %% open the netcdf file for reading
69    if ischar(nc)
70        if exist(nc,'file')
71            try
72                nc=netcdf.open(nc,'NC_NOWRITE');
73                testfile=1;
74            catch ME
75                errormsg=['ERROR opening ' nc ': ' ME.message];
76                return
77            end
78        else
79            errormsg=['ERROR:file ' nc ' does not exist'];
80            return
81        end
82    else
83        testfile=0;
84    end
85   
86    %% short reading option for global attributes only, if the first argument is 'ListGlobalAttribute'
87    if isequal(varargin{1},'ListGlobalAttribute')
88        for ilist=2:numel(varargin)
89            valuestr=[];%default
90            try
91                valuestr = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),varargin{ilist});
92            catch ME
93            end
94            eval(['Data.' varargin{ilist} '=valuestr;'])
95        end
96        netcdf.close(nc)
97        return
98    end
99   
100    %% time variable or dimension
101    input_index=1;
102    CheckTimeVar=0;
103    TimeVarName='';
104    if isequal(varargin{1},'TimeVarName')
105        TimeVarName=varargin{2};
106        CheckTimeVar=1;
107        TimeIndex=varargin{3};
108        input_index=4;% list of varibles to read is at fourth argument
109    elseif isequal(varargin{1},'TimeDimName')
110        TimeDimName=varargin{2};
111        TimeIndex=varargin{3};
112        input_index=4;
113    end
114   
115    %% full reading: get the nbre of dimensions, variables, global attributes
116    ListVarName=varargin{input_index};
117    [ndims,nvars,ngatts]=netcdf.inq(nc);%nbre of dimensions, variables, global attributes, in the netcdf file
118   
119    %%  -------- read all global attributes (constants)-----------
120    Data.ListGlobalAttribute={};%default
121    att_key=cell(1,ngatts);%default
122    for iatt=1:ngatts
123        keystr= netcdf.inqAttName(nc,netcdf.getConstant('NC_GLOBAL'),iatt-1);
124        valuestr = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),keystr);
125        keystr=regexprep(keystr,{'\','/','\.','-',' '},{'','','','',''});%remove  '\','.' or '-' if exists
126        if strcmp(keystr(1),'_')
127            keystr(1)=[];
128        end
129        try
130            if ischar(valuestr) %& length(valuestr)<200 & double(valuestr)<=122 & double(valuestr)>=48 %usual characters
131                eval(['Data.' keystr '=''' valuestr ''';'])
132            elseif isnumeric(valuestr)
133                eval(['Data.' keystr '=valuestr;'])
134            else
135                eval(['Data.' keystr '='';'])
136            end
137            att_key{iatt}=keystr;
138        catch ME
139            att_key{iatt}=['attr_' num2str(iatt)];
140            Data.(att_key{iatt})=[];
141        end
142    end
143    Data.ListGlobalAttribute=att_key;
144   
145    %%  -------- read dimension names-----------
146    ListDimNameNetcdf=cell(1,ndims);
147    dim_value=zeros(1,ndims);
148    for idim=1:ndims %loop on the dimensions of the netcdf file
149        [ListDimNameNetcdf{idim},dim_value(idim)] = netcdf.inqDim(nc,idim-1);%get name and value of each dimension
150    end
151    if ~isempty(ListDimNameNetcdf)
152        flag_used=zeros(1,ndims);%initialize the flag indicating the selected dimensions in the list (0=unused)
153    end
154    if isequal(varargin{1},'TimeDimName')% time dimension introduced
155        TimeDimIndex=find(strcmp(TimeDimName,ListDimNameNetcdf));
156        if isempty(TimeDimIndex)
157            errormsg=['requested time dimension ' varargin{2} ' not found'];
158            return
159        end
160        if dim_value(TimeDimIndex)<varargin{3}
161           errormsg=['requested time index ' num2str(varargin{3}) ' exceeds matrix dimension'];
162            return
163        end
164    end 
165   
166    %%  -------- read names of variables -----------
167    ListVarNameNetcdf=cell(1,nvars); %default
168    dimids=cell(1,nvars);
169    nbatt=zeros(1,nvars);
170    for ncvar=1:nvars %loop on the variables of the netcdf file
171        %get name, type, dimensions and attribute numbers of each variable
172        [ListVarNameNetcdf{ncvar},xtype(ncvar),dimids{ncvar},nbatt(ncvar)] = netcdf.inqVar(nc,ncvar-1);
173    end
174%     testmulti=0;
175    if isequal(ListVarName,'*')||isempty(ListVarName)
176        var_index=1:nvars; %all the variables are selected in the netcdf file
177        Data.ListVarName=ListVarNameNetcdf;
178    else   %select input variables, if requested by the input ListVarName
179        check_keep=ones(1,size(ListVarName,2));
180        for ivar=1:size(ListVarName,2) % check redondancy of variable names
181            if ~isempty(find(strcmp(ListVarName{1,ivar},ListVarName(1:ivar-1)), 1))
182                check_keep(ivar)=0;% the variable #ivar is already in the list
183            end
184        end
185        ListVarName=ListVarName(:,logical(check_keep));
186        if size(ListVarName,1)>1 %multiple choice of variable ranked by order of priority
187            for iline=1:size(ListVarName,1)
188                search_index=find(strcmp(ListVarName{iline,1},ListVarNameNetcdf),1);%look for the first variable name in the list of netcdf variables
189                if ~isempty(search_index)
190                    break % go to the next line
191                end
192            end
193            ichoice=iline-1;%selected line number in the list of input names of variables
194        else
195            iline=1;
196        end
197        %ListVarName=ListVarName(iline,:);% select the appropriate option for input variable (lin ein the input name matrix)
198        if CheckTimeVar
199            TimeVarIndex=find(strcmp(TimeVarName,ListVarNameNetcdf),1); %look for the index of the time variable in the netcdf list
200            if isempty(TimeVarIndex)
201                errormsg='requested variable for time is missing';
202                return
203            end
204            TimeDimIndex=dimids{TimeVarIndex}(1)+1;
205            ListVarName=[ListVarName {TimeVarName}];
206        end
207        var_index=zeros(1,size(ListVarName,2));%default list of variable indices
208        for ivar=1:size(ListVarName,2)
209            search_index=find(strcmp(ListVarName{iline,ivar},ListVarNameNetcdf),1);%look for the variable name in the list of netcdf file
210            if ~isempty(search_index)
211                var_index(ivar)=search_index;%index of the netcdf list corresponding to the input list index ivar
212            end
213        end
214        var_detect=(var_index~=0);%=1 for detected variables
215        list_index=find(var_index);% indices in the input list corresponding to a detected variable
216        var_index=var_index(list_index);% netcdf variable indices corresponding to the output list of read variable
217        Data.ListVarName=ListVarName(1,list_index);%the first line of ListVarName sets the output names of the variables
218    end
219   
220    %% get the dimensions and attributes associated to  variables
221    var_dim=cell(size(var_index));% initiate list of dimensions for variables
222    for ivar=1:length(var_index)
223        var_dim{ivar}=dimids{var_index(ivar)}+1; %netcdf dimension indices used by the variable #ivar
224        Data.VarDimName{ivar}=ListDimNameNetcdf(var_dim{ivar});
225        flag_used(var_dim{ivar})=ones(size(var_dim{ivar}));%flag_used =1 for the indices of used dimensions
226        for iatt=1:nbatt(var_index(ivar))
227            attname = netcdf.inqAttName(nc,var_index(ivar)-1,iatt-1);
228            valuestr= netcdf.getAtt(nc,var_index(ivar)-1,attname);
229            attname=regexprep(attname,{'\','/','\.','-',' '},{'','','','',''});%remove  '\','.' or '-' if exists
230            if strcmp(attname(1),'_')
231                attname(1)=[];
232            end
233            try
234                if isempty(valuestr)
235                    Data.VarAttribute{ivar}.(attname)=valuestr;
236                end
237            catch ME
238                display(attname)
239                display(valuestr)
240                display(ME.message)
241                Data.VarAttribute{ivar}.(['atrr_' num2str(iatt)])='not read';
242            end
243        end
244    end
245   
246    %% select the dimensions used for the set of input variables
247    if ~isempty(var_index)
248        dim_index=find(flag_used);%list of netcdf dimensions indices corresponding to used dimensions
249        Data.ListDimName=ListDimNameNetcdf(dim_index);
250        Data.DimValue=dim_value(dim_index);
251        if input_index==4% if a dimension is selected as time
252            Data.DimValue(TimeDimIndex)=numel(TimeIndex);
253        end
254    end
255   
256    %% get the values of the input variables
257    if  ~isempty(ListVarName)
258        for ivar=1:length(var_index)
259            VarName=Data.ListVarName{ivar};
260            VarName=regexprep(VarName,'-','_'); %suppress '-' if it exists in the netcdf variable name (leads to errors in matlab)
261%             CheckSub=0;
262            if input_index==4% if a dimension is selected as time
263                ind_vec=zeros(1,numel(var_dim{ivar}));% vector with zeros corresponding to al the dimensions of the variable VarName
264                ind_size=dim_value(var_dim{ivar});% vector giving the size (for each dimension) of the variable VarName
265                index_time=find(var_dim{ivar}==TimeDimIndex);
266                if ~isempty(index_time)
267                    if ind_size(index_time)<max(TimeIndex)
268                        errormsg=['requested index ' num2str(TimeIndex) ' exceeds matrix dimension'];
269                        return
270                    end
271                    ind_vec(index_time)=TimeIndex-1;% selected index(or indices) to read
272                    ind_size(index_time)=numel(TimeIndex);%length of the selected set of time indices
273                    if numel(TimeIndex)==1 && ~strcmp(VarName,TimeVarName)
274                        Data.VarDimName{ivar}(index_time)=[];% for a single selected time remove the time in the list of dimensions (except for tTime itself)
275                    end
276                end                   
277                Data.(VarName)=double(netcdf.getVar(nc,var_index(ivar)-1,ind_vec,ind_size)); %read the variable data
278                Data.(VarName)=squeeze(Data.(VarName));%remove singeton dimension
279            else
280                Data.(VarName)=netcdf.getVar(nc,var_index(ivar)-1); %read the whole variable data
281            end
282            if xtype(var_index(ivar))==5
283                Data.(VarName)=double(Data.(VarName)); %transform to double for single pecision
284            end
285        end
286    end
287    Data.VarType=xtype(var_index);
288   
289    %%  -------- close fle-----------
290    if testfile==1
291        netcdf.close(nc)
292    end
293   
294    %% old netcdf library
295else
296    [Data,var_detect,ichoice]=nc2struct_toolbox(nc,varargin);
297end
Note: See TracBrowser for help on using the repository browser.