source: trunk/src/nc2struct.m @ 140

Last change on this file since 140 was 140, checked in by sommeria, 10 years ago

bug repair in netcdf file reading, dealing with unavailable variables, + cleaning

File size: 10.1 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]=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%  var_detect: vector with same length as the cell array ListVarName, = 1 for each detected variable and 0 else.
18%            var_detect=[] in the absence of input cell array
19%  ichoice: index of the selected line in the case of multiple choice
20%        (cell array of varible names with multiple lines) , =[] by default
21%INPUT:
22%  nc:  name of a netcdf file (char string) or netcdf object   
23%  additional arguments:
24%       -no additional arguments: all the variables of the netcdf fiel are read.
25%       -a cell array, ListVarName, made of  char strings {'VarName1', 'VarName2',...} )
26%         if ListVarName=[] or {}, no variables is read (only global attributes)
27%         if ListVarName is absent, or = '*', ALL the variables of the netcdf file are read.
28%         if ListVarName is a cell array with n lines, the set of variables will be sought by order of priority
29%                  in the list, while output names will be set by the first line
30%        - the string 'ListGlobalAttribute' followed by a list of attribute  names: reads only these attributes (fast reading)
31%
32%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
33%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
34%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
35%     This file is part of the toolbox UVMAT.
36%
37%     UVMAT is free software; you can redistribute it and/or modify
38%     it under the terms of the GNU General Public License as published by
39%     the Free Software Foundation; either version 2 of the License, or
40%     (at your option) any later version.
41%
42%     UVMAT is distributed in the hope that it will be useful,
43%     but WITHOUT ANY WARRANTY; without even the implied warranty of
44%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
46%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
47   
48function [Data,var_detect,ichoice]=nc2struct(nc,varargin)
49
50if isempty(varargin)
51    varargin{1}='*';
52end
53hhh=which('netcdf.open');% look for built-in matlab netcdf library
54
55if ~isequal(hhh,'')
56    %% default output
57    Data=[];%default
58    var_detect=[];%default
59    ichoice=[];%default
60   
61    %% open the netcdf file for reading
62    if ischar(nc)
63        if exist(nc,'file')
64            nc=netcdf.open(nc,'NC_NOWRITE');
65            testfile=1;
66        else
67           Data.Txt=['ERROR:file ' nc ' does not exist'];
68           return
69        end
70    else
71        testfile=0;
72    end
73   
74    %% short reading opion for global attributes only, if the first argument is 'ListGlobalAttribute'
75    if isequal(varargin{1},'ListGlobalAttribute')
76        for ilist=2:numel(varargin)
77            try
78            valuestr = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),varargin{ilist});
79            catch
80                valuestr=[];
81            end
82            eval(['Data.' varargin{ilist} '=valuestr;'])
83        end
84        netcdf.close(nc)
85       return
86    end
87
88    %% full reading: get the nbre of dimensions, variables, global attributes
89    ListVarName=varargin{1};
90    [ndims,nvars,ngatts]=netcdf.inq(nc);%nbre of dimensions, variables, global attributes, in the netcdf file
91   
92    %%  -------- read all global attributes (constants)-----------
93    att_key={};%default
94    iatt_g=0;
95    Data.ListGlobalAttribute={};%default
96    for iatt=1:ngatts
97        keystr= netcdf.inqAttName(nc,netcdf.getConstant('NC_GLOBAL'),iatt-1);
98        indstr1=regexp(keystr,'\\','once');%detect '\\'
99        indstr2=regexp(keystr,'\.','once');%detect '\.'
100        if isempty(indstr1) && isempty(indstr2)
101           valuestr = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),keystr);
102           if ischar(valuestr) && length(valuestr)<200
103                iatt_g=iatt_g+1;
104                indstr1=regexp(keystr,'\\','once');%detect '\\'
105                indstr2=regexp(keystr,'\.','once');%detect '\.'
106                if isempty(indstr1) && isempty(indstr2)
107                    eval(['Data.' keystr '=''' valuestr ''';'])
108                    att_key{iatt_g}=keystr;
109                end
110            elseif isempty(valuestr)
111                iatt_g=iatt_g+1;
112                eval(['Data.' keystr '=[];'])
113                att_key{iatt_g}=keystr;
114            elseif isnumeric(valuestr)
115                iatt_g=iatt_g+1;
116                eval(['Data.' keystr '=valuestr;'])
117                att_key{iatt_g}=keystr;
118            end
119        end
120    end
121    Data.ListGlobalAttribute=att_key;
122
123    %%  -------- read dimension names-----------
124    ListDimNameNetcdf={};
125    dim_value=[];
126    for idim=1:ndims %loop on the dimensions of the netcdf file
127        [ListDimNameNetcdf{idim},dim_value(idim)] = netcdf.inqDim(nc,idim-1);%get name and value of each dimension
128    end
129    if ~isempty(ListDimNameNetcdf)
130        flag_used=zeros(1,ndims);%initialize the flag indicating the selected dimensions in the list (0=unused)
131    end
132 
133    %%  -------- read names of variables -----------
134    ListVarNameNetcdf={}; %default
135    dimids={};
136    nbatt=[];
137    for ncvar=1:nvars %loop on the variables of the netcdf file
138        %get name, type, dimensions and attribute numbers of each variable
139        [ListVarNameNetcdf{ncvar},xtype,dimids{ncvar},nbatt(ncvar)] = netcdf.inqVar(nc,ncvar-1);
140    end 
141    testmulti=0;
142    if isequal(ListVarName,'*')||isempty(ListVarName)
143        var_index=1:nvars; %all the variables are selected in the netcdf file
144        Data.ListVarName=ListVarNameNetcdf;
145    else   %select input variables, if requested by the input ListVarName
146        sizvar=size(ListVarName);
147        testmulti=(sizvar(1)>1);%test for multiple choice of variable ranked by order of priority
148        var_index=zeros(1,sizvar(2));%default
149        if testmulti %multiple choice of variable ranked by order of priority
150            for iline=1:sizvar(1)
151                search_index=find(strcmp(ListVarName{iline,1},ListVarNameNetcdf),1);%look for the first variable name in the list of netcdf variables
152                if ~isempty(search_index)
153                    break % go to the next line
154                end
155            end
156            ichoice=iline-1;%selected line number in the list of input names of variables
157        else
158            iline=1;
159        end
160        for ivar=1:sizvar(2)
161            search_index=find(strcmp(ListVarName{iline,ivar},ListVarNameNetcdf),1);%look for the variable name in the list of netcdf file
162            if ~isempty(search_index)
163                var_index(ivar)=search_index;%index of the netcdf list corresponding to the input list index ivar
164            end
165        end
166        var_detect=(var_index~=0);%=1 for detected variables         
167        list_index=find(var_index);% indices in the input list corresponding to a detected variable
168        var_index=var_index(list_index);% netcdf variable indices corresponding to the output list of read variable
169        Data.ListVarName=ListVarName(1,list_index);%the first line of ListVarName sets the output names of the variables
170    end
171     
172  %% get the dimensions and attributes associated to  variables
173    for ivar=1:length(var_index)
174        var_dim{ivar}=dimids{var_index(ivar)}+1; %netcdf dimension indices used by the variable #ivar
175        Data.VarDimName{ivar}=ListDimNameNetcdf(var_dim{ivar});
176        flag_used(var_dim{ivar})=ones(size(var_dim{ivar}));%flag_used =1 for the indices of used dimensions
177        for iatt=1:nbatt(var_index(ivar))
178            attname = netcdf.inqAttName(nc,var_index(ivar)-1,iatt-1);
179            valuestr= netcdf.getAtt(nc,var_index(ivar)-1,attname);
180            if ischar(valuestr)
181                eval(['Data.VarAttribute{ivar}.' attname '=''' valuestr ''';'])
182            elseif isempty(valuestr)
183                eval(['Data.VarAttribute{ivar}.' attname '=[];'])
184            elseif isnumeric(valuestr)
185                eval(['Data.VarAttribute{ivar}.' attname '=valuestr;'])
186            end
187        end
188    end
189
190    %% select the dimensions used for the set of input variables
191    if ~isempty(var_index)     
192        dim_index=find(flag_used);%list of netcdf dimensions indices corresponding to used dimensions
193        Data.ListDimName=ListDimNameNetcdf(dim_index);
194        Data.DimValue=dim_value(dim_index);
195    end
196   
197    %% get the values of the input variables
198    if  ~isempty(ListVarName)
199        for ivar=1:length(var_index)
200            VarName=Data.ListVarName{ivar};
201            VarName=regexprep(VarName,'-',''); %suppress '-' if it exists in the netcdf variable name
202            eval(['Data.' VarName '=double(netcdf.getVar(nc,var_index(ivar)-1));'])%read the variable data
203        end
204    end
205   
206    %%  -------- close fle-----------
207    if testfile==1
208        netcdf.close(nc)
209    end
210   
211%% old netcdf library
212else
213    [Data,var_detect,ichoice]=nc2struct_toolbox(nc,varargin);
214end
Note: See TracBrowser for help on using the repository browser.