source: trunk/src/nc2struct.m @ 45

Last change on this file since 45 was 45, checked in by gostiaux, 15 years ago

adaptation for movies

File size: 11.1 KB
RevLine 
[8]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%%%%%% TODO: add the possibility to read only attributes, see  nc2struct_toolbox %%%
5%----------------------------------------------------------------------
6% function [Data,var_detect,ichoice]=nc2struct(nc,ListVarName)
7%
8% OUTPUT:
9%  Data: structure containing all the information of the netcdf file (or netcdf object)
10%           with fields:
11%    .ListGlobalAttribute: cell listing the names of the global attributes
12%        .Att_1,Att_2... : values of the global attributes
13%            .ListDimName: cell listing the names of the array dimensions
14%               .DimValue: array dimension values (Matlab vector with the same length as .ListDimName
15%            .ListVarName: cell listing the names of the variables
16%            .VarDimIndex: cell containing the set of dimension indices (in list .ListDimName) for each variable of .ListVarName
17%            .VarDimName: cell containing a cell of dimension names (in list .ListDimName) for each variable of .ListVarName
18%           .VarAttribute: cell of structures s containing names and values of variable attributes (s.name=value) for each variable of .ListVarName
19%        .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
20%  var_detect: vector with same length as ListVarName, with 1 for each detected variable and 0 else.
21%  ichoice: = line
22%
23%INPUT:
24%     nc:      name of a netcdf file (char string) or netcdf object   
25% ListVarName: optional list of variable names to select (cell array of  char strings {'VarName1', 'VarName2',...} )
26%         if ListVarName=[] or {}, no variables is read (only global attributes and lists of dimensions, variables and attriburtes)
27%         if ListVarName is absent, or = '*', ALL the variables are read.
28%        if ListVarName is a cell array with n lines, the set of variables
29%                        will be sought by order of priority in the list, while output names will be set by the first line
30%
31%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
32%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
33%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
34%     This file is part of the toolbox UVMAT.
35%
36%     UVMAT is free software; you can redistribute it and/or modify
37%     it under the terms of the GNU General Public License as published by
38%     the Free Software Foundation; either version 2 of the License, or
39%     (at your option) any later version.
40%
41%     UVMAT is distributed in the hope that it will be useful,
42%     but WITHOUT ANY WARRANTY; without even the implied warranty of
43%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
44%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
45%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
46   
47function [Data,var_detect,ichoice]=nc2struct(nc,varargin)
48List=varargin;
49if nargin==0
50    List{1}='*';
51end
52% if ~exist('ListVarName','var')
53%     ListVarName='*';
54% end
55hhh=which('netcdf.open');% look for built-in matlab netcdf library
56
57if ~isequal(hhh,'')
58    %default output
59    Data=[];
60    var_detect=[];
61    ichoice=[];%default
62    %open the netcdf file for reading
63    if ischar(nc)
64        if exist(nc,'file')
65            nc=netcdf.open(nc,'NC_NOWRITE');
66            testfile=1;
67        else
68           Data.Txt=['ERROR:file ' nc ' does not exist'];
69           return
70        end
71    else
72        testfile=0;
73    end
74    % short reading of global attributes
75    if isequal(List{1},'ListGlobalAttribute')
76        for ilist=2:numel(List)
[45]77            try
[8]78            valuestr = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),List{ilist});
[45]79            catch
80                valuestr=[];
81            end
[8]82            eval(['Data.' List{ilist} '=valuestr;'])
83        end
84        netcdf.close(nc)
85       return
86    end
87
88    % reading of variables, including attributes
89    ListVarName=List{1}; 
90    [ndims,nvars,ngatts]=netcdf.inq(nc);%nbre of dimensions, variables, attributes
91   
92    %  -------- read 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,'\\');%detect '\\'
99        indstr2=regexp(keystr,'\.');%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,'\\');%detect '\\'
105                indstr2=regexp(keystr,'\.');%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 dimensions -----------
124    dim_name={};
125    dim_value=[];
126    for idim=1:ndims%length(dim_read);
127        [dim_name{idim},dim_value(idim)] = netcdf.inqDim(nc,idim-1);
128    end
129    if ~isempty(dim_name) && ~isempty(dim_value)
130        Data.ListDimName=dim_name;
131        Data.DimValue=dim_value;
132%         DimIndices=[1:ndims]; %index of the dimension in the netcdf file
133        dim_used=zeros(1,ndims);%initialize test of used dimensions
134    end
135 
136    %  -------- read variables -----------
137    var_read={}; %default
138    dimids={};
139    nbatt=[];
140    for ivar=1:nvars
141        [var_read{ivar},xtype,dimids{ivar},nbatt(ivar)] = netcdf.inqVar(nc,ivar-1);
142    end 
143    var_index=1:nvars; %default set of variable indices in the netcdf file
144    testmulti=0;
145    OutputList=[];
146    %select input variables, if requested by the input ListVarName
147    if ~(isequal(ListVarName,'*')||isempty(ListVarName))
148        sizvar=size(ListVarName);
149        testmulti=(sizvar(1)>1);
150        var_index=zeros(1,sizvar(2));%default
151        if testmulti
152            OutputList=ListVarName(1,:);
153            testend=0;
154            for iline=1:sizvar(1)
155                if testend
156                    break
157                end
158          %      var_index=zeros(size(ListVarName));%default
159                for ivar=1:sizvar(2)
160                    if ~isempty(ListVarName{iline,ivar})
161                         for ilist=1:nvars
162                            if isequal(var_read{ilist},ListVarName{iline,ivar})
163                                var_index(ivar)=ilist;
164     %                          var_detect(ivar)=1;
165                            break
166                            end
167                         end
168                         if ivar==1
169                            if var_index(ivar)==0
170                                break%go to next line if the first nc variable is not found
171                            else
172                                testend=1; %this line will be read
173                                ichoice=iline-1; %selectedline number in the list of input names of variables
174                            end
175                         end
176                    end
177                end
178            end
179        else   %single list of input variables
180            for ivar=1:sizvar(2)
181                for ilist=1:nvars
182                    if isequal(var_read{ilist},ListVarName{ivar})
183                        var_index(ivar)=ilist;
184                        var_detect(ivar)=1;
185                        break
186                    end
187                end
188            end
189        end
190        list_index=find(var_index);
191        if ~isempty(list_index)
192            if testmulti
193                OutputList=OutputList(list_index);
194            end
195            var_index=var_index(list_index);
196            var_detect=(var_index~=0);
197            var_read=var_read(var_index);         
198        end
199    end
200   
201   
202    %select variable attributes and associate dimensions
203%     var_dim_index=[]; %default
204    Data.ListVarName={};%default
205    VarDimIndex={};%default
206    for ivar=1:length(var_read)
207        if testmulti
208            Data.ListVarName{ivar}=OutputList{ivar};%new name given by ListVarName(1,:)
209        else
210            Data.ListVarName{ivar}=var_read{ivar};%name of the variable
211        end
212        var_dim=dimids{var_index(ivar)}+1; %dimension indices used by the variable
213        dim_used(var_dim)=ones(size(var_dim));
214        VarDimIndex{ivar}=var_dim;
215
216        %variable attributes
217        if ivar==1
218            Data.VarAttribute={};%initialisation of the list of variable attributes
219        end
220        %variable attributes
221        for iatt=1:nbatt(var_index(ivar))
222            attname = netcdf.inqAttName(nc,var_index(ivar)-1,iatt-1);
223            valuestr= netcdf.getAtt(nc,var_index(ivar)-1,attname);
224            if ischar(valuestr)
225                eval(['Data.VarAttribute{ivar}.' attname '=''' valuestr ''';'])
226            elseif isempty(valuestr)
227                eval(['Data.VarAttribute{ivar}.' attname '=[];'])
228            elseif isnumeric(valuestr)
229                eval(['Data.VarAttribute{ivar}.' attname '=valuestr;'])
230            end
231        end
232    end
233
234    %select the used dimensions
235    if isempty(var_read)
236        if isfield(Data,'ListDimName') && isfield(Data,'DimValue')
237        Data=rmfield(Data,'ListDimName');
238        Data=rmfield(Data,'DimValue');
239        end
240    else
241%         list_dim=1:ndims;
242        dim_index=find(dim_used);
243%         list_dim=list_dim(dim_index);
244        old2new=cumsum(dim_used);
245        Data.ListDimName=Data.ListDimName(dim_index);
246        Data.DimValue=Data.DimValue(dim_index);
247    end
248    for ivar=1:length(var_read)
249        Data.VarDimIndex{ivar}=old2new(VarDimIndex{ivar});% ENLEVER Data.VarDimIndex ulterieurement
250        Data.VarDimName{ivar}=Data.ListDimName(Data.VarDimIndex{ivar});
251    end
252    %variable values
253    if  ~isempty(ListVarName)
254        for ivar=1:length(Data.ListVarName)
255            VarName=Data.ListVarName{ivar};
256            indstr=regexp(VarName,'-');%detect '-'
257            if ~isempty(indstr)
258                VarName(indstr)=[];
259            end
260            eval(['Data.' VarName '=netcdf.getVar(nc,var_index(ivar)-1);'])%read the variable data
261            eval(['siz=size(Data.' VarName ');'])
262            if numel(siz)<=2
263            eval(['Data.' VarName '=Data.' VarName ''';'])%read the variable data
264            end
265        end
266    end
267    %  -------- close fle-----------
268    if testfile==1
269        netcdf.close(nc)
270    end
271else
272    [Data,var_detect,ichoice]=nc2struct_toolbox(nc,varargin);
273end
Note: See TracBrowser for help on using the repository browser.