source: trunk/src/series/merge_proj_volume.m @ 1121

Last change on this file since 1121 was 1121, checked in by sommeria, 22 months ago

merge_proj_volume added

File size: 24.7 KB
Line 
1%'merge_proj_volume': concatene several fields from series, project on volumes
2%------------------------------------------------------------------------
3% function ParamOut=merge_proj_volume(Param)
4%------------------------------------------------------------------------
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
6%
7%OUTPUT
8% ParamOut: sets options in the GUI series.fig needed for the function
9%
10%INPUT:
11% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
12% In batch mode, Param is the name of the corresponding xml file containing the same information
13% when Param.Action.RUN=0 (as activated when the current Action is selected
14% in series), the function ouput paramOut set the activation of the needed GUI elements
15%
16% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
17% see the current structure Param)
18%    .InputTable: cell of input file names, (several lines for multiple input)
19%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
20%    .OutputSubDir: name of the subdirectory for data outputs
21%    .OutputDirExt: directory extension for data outputs
22%    .Action: .ActionName: name of the current activated function
23%             .ActionPath:   path of the current activated function
24%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
25%             .RUN =0 for GUI input, =1 for function activation
26%             .RunMode='local','background', 'cluster': type of function  use
27%             
28%    .IndexRange: set the file or frame indices on which the action must be performed
29%    .FieldTransform: .TransformName: name of the selected transform function
30%                     .TransformPath:   path  of the selected transform function
31%    .InputFields: sub structure describing the input fields withfields
32%              .FieldName: name(s) of the field
33%              .VelType: velocity type
34%              .FieldName_1: name of the second field in case of two input series
35%              .VelType_1: velocity type of the second field in case of two input series
36%              .Coord_y: name of y coordinate variable
37%              .Coord_x: name of x coordinate variable
38%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
41%=======================================================================
42% Copyright 2008-2022, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
43%   http://www.legi.grenoble-inp.fr
44%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
45%
46%     This file is part of the toolbox UVMAT.
47%
48%     UVMAT is free software; you can redistribute it and/or modify
49%     it under the terms of the GNU General Public License as published
50%     by the Free Software Foundation; either version 2 of the license,
51%     or (at your option) any later version.
52%
53%     UVMAT is distributed in the hope that it will be useful,
54%     but WITHOUT ANY WARRANTY; without even the implied warranty of
55%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
56%     GNU General Public License (see LICENSE.txt) for more details.
57%=======================================================================
58
59function ParamOut=merge_proj_volume(Param)
60
61%% set the input elements needed on the GUI series when the function is selected in the menu ActionName or InputTable refreshed
62if isstruct(Param) && isequal(Param.Action.RUN,0)
63    ParamOut.AllowInputSort='on';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
64    ParamOut.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
65    ParamOut.NbSlice='off'; %nbre of slices ('off' by default)
66    ParamOut.VelType='one';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
67    ParamOut.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
68    ParamOut.FieldTransform = 'on';%can use a transform function
69    ParamOut.TransformPath=fullfile(fileparts(which('uvmat')),'transform_field');% path to transform functions (needed for compilation only)
70    ParamOut.ProjObject='on';%can use projection object(option 'off'/'on',
71    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
72    ParamOut.OutputDirExt='.volume';%set the output dir extension
73    ParamOut.OutputFileMode='NbInput_i';% '=NbInput': 1 output file per input file index, '=NbInput_i': 1 file per input file index i, '=NbSlice': 1 file per slice
74      %check the input files
75    ParamOut.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
76    first_j=[];
77    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
78    PairString='';
79    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
80    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
81    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
82        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
83    if ~exist(FirstFileName,'file')
84        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
85    end
86    return
87end
88
89%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
90ParamOut=[]; %default output
91RUNHandle=[];
92WaitbarHandle=[];
93
94%% read input parameters from an xml file if input is a file name (batch mode)
95checkrun=1;
96if ischar(Param)
97    Param=xml2struct(Param);% read Param as input file (batch case)
98    checkrun=0;
99else
100    hseries=findobj(allchild(0),'Tag','series');
101    RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
102    WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
103end
104if ~(isfield(Param,'ProjObject') && strcmp(Param.ProjObject.Type,'volume')&& strcmp(Param.ProjObject.ProjMode,'interp_lin'))
105 msgbox_uvmat('ERROR','a projection object of type volume with ProjMode interp_lin must be introduced')
106 return
107end
108
109%% root input file type
110RootPath=Param.InputTable(:,1);
111RootFile=Param.InputTable(:,3);
112SubDir=Param.InputTable(:,2);
113%NomType=Param.InputTable(:,4);
114FileExt=Param.InputTable(:,5);
115[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
116%%%%%%%%%%%%
117% The cell array filecell is the list of input file names, while
118% filecell{iview,fileindex}:
119%        iview: line in the table corresponding to a given file series
120%        fileindex: file index within  the file series,
121% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
122% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
123%%%%%%%%%%%%
124NbView=numel(i1_series);%number of input file series (lines in InputTable)
125NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
126NbField_i=size(i1_series{1},2); %nb of fields for the i index
127NbField=NbField_j*NbField_i; %total number of fields
128
129%% define the name for result file (with path=RootPath{1})
130OutputDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
131
132if ~isfield(Param,'InputFields')
133    Param.InputFields.FieldName='';
134end
135
136
137%% determine the file type on each line from the first input file
138ImageTypeOptions={'image','multimage','mmreader','video','cine_phantom'};
139NcTypeOptions={'netcdf','civx','civdata'};
140for iview=1:NbView
141    if ~exist(filecell{iview,1}','file')
142        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
143        return
144    end
145    [FileInfo{iview},MovieObject{iview}]=get_file_info(filecell{iview,1});
146    FileType{iview}=FileInfo{iview}.FileType;
147    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
148    if CheckImage{iview}
149        ParamIn{iview}=MovieObject{iview};
150    else
151        ParamIn{iview}=Param.InputFields;
152    end
153    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
154    if ~isempty(j1_series{iview})
155        frame_index{iview}=j1_series{iview};
156    else
157        frame_index{iview}=i1_series{iview};
158    end
159end
160if NbView >1 && max(cell2mat(CheckImage))>0 && ~isfield(Param,'ProjObject')
161    disp_uvmat('ERROR','projection on a common grid is needed to concatene images: use a Projection Object of type ''plane'' with ProjMode=''interp_lin''',checkrun)
162    return
163end
164
165%% calibration data and timing: read the ImaDoc files
166[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
167if size(time,1)>1
168    diff_time=max(max(diff(time)));
169    if diff_time>0
170        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time) ': the mean time is chosen in result'],checkrun)
171    end   
172end
173if ~isempty(errormsg)
174    disp_uvmat('WARNING',errormsg,checkrun)
175end
176time=mean(time,1); %averaged time taken for the merged field
177
178%% check calibration data
179for iview=1:NbView
180    if isfield(XmlData{iview}.GeometryCalib,'CheckVolumeScan')  %old convention (<2022)
181        CheckVolumeScan{iview}=XmlData{iview}.GeometryCalib.CheckVolumeScan;
182        XmlData{iview}.Slice.SliceCoord=XmlData{iview}.GeometryCalib.SliceCoord;
183        XmlData{iview}.Slice.SliceAngle=XmlData{iview}.GeometryCalib.SliceAngle;
184    elseif isfield(XmlData{1},'Slice')&& isfield(XmlData{iview}.Slice,'CheckVolumeScan')  %new convention (>=2022)
185        CheckVolumeScan{iview}=XmlData{iview}.Slice.CheckVolumeScan;
186    else
187        disp('no volume info in calibration data (xml file)')
188        return
189    end
190    if CheckVolumeScan{iview}==0
191         disp('input field sereis with volume scan (index j) is needed')
192        return
193    end
194end
195
196%% initiate output field
197DataVol.ListGlobalAttribute={'Conventions','CoordUnit','Time'};
198DataVol.Conventions='uvmat';
199DataVol.CoordUnit=XmlData{1}.GeometryCalib.CoordUnit;
200DataVol.Time=0; %TO UPDATE
201DataVol.ListVarName={'coord_x','coord_y','coord_z','A'};
202DataVol.VarDimName={'coord_x','coord_y','coord_z',{'coord_z','coord_y','coord_x'}};
203DataVol.VarAttribute{1}.Role='coord_x';
204DataVol.VarAttribute{2}.Role='coord_y';
205DataVol.VarAttribute{3}.Role='coord_z';
206DataVol.VarAttribute{4}.Role='scalar';
207DataVol.coord_x=Param.ProjObject.RangeX(1):Param.ProjObject.DX:Param.ProjObject.RangeX(2);
208DataVol.coord_y=Param.ProjObject.RangeY(1):Param.ProjObject.DY:Param.ProjObject.RangeY(2);
209DataVol.coord_z=Param.ProjObject.RangeZ(1):Param.ProjObject.DZ:Param.ProjObject.RangeZ(2);
210DataVol.A=zeros(numel(DataVol.coord_z),numel(DataVol.coord_y),numel(DataVol.coord_x));
211%% coordinate transform or other user defined transform
212% transform_fct='';%default fct handle
213% if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
214%         currentdir=pwd;
215%         cd(Param.FieldTransform.TransformPath)
216%         transform_fct=str2func(Param.FieldTransform.TransformName);
217%         cd (currentdir)
218%         if isfield(Param,'TransformInput')
219%             for iview=1:NbView
220%             XmlData{iview}.TransformInput=Param.TransformInput;
221%             end
222%         end
223% end
224%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
225% EDIT FROM HERE
226
227% %% output file type
228if isempty(j1_series{1})
229    disp('error: no index j for z position label')
230    return
231end
232NomTypeOut='_1';
233
234RootFileOut=RootFile{1};
235for iview=2:NbView
236    if ~strcmp(RootFile{iview},RootFile{1})
237        RootFileOut='mproj';
238        break
239    end
240end
241
242
243%% MAIN LOOP ON FIELDS
244%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
245% for i_slice=1:NbSlice
246%     index_slice=i_slice:NbSlice:NbField;% select file indices of the slice
247%     NbFiles=0;
248%     nbmissing=0;
249
250%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
251tstart=tic; %used to record the computing time
252CheckOverwrite=1;%default
253if isfield(Param,'CheckOverwrite')
254    CheckOverwrite=Param.CheckOverwrite;
255end
256
257
258for index_i=1:NbField_i
259    AMerge=zeros(NbField_j,numel(DataVol.coord_y),numel(DataVol.coord_x));
260    for index_j=1:NbField_j
261        index_j
262        %% generating the name of the merged field
263        OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFileOut,'.nc',NomTypeOut,index_i);
264        if ~CheckOverwrite && exist(OutputFile,'file')
265            disp(['existing output file ' OutputFile ' already exists, skip to next field'])
266            continue% skip iteration if the mode overwrite is desactivated and the result file already exists
267        end
268
269        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
270        Data=cell(1,NbView);%initiate the set Data
271        timeread=zeros(1,NbView);
272        for iview=1:NbView
273            %% reading input file(s)
274            [Data{iview},tild,errormsg] = read_field(filecell{iview,index_j},FileType{iview},ParamIn{iview},frame_index{iview}(index_j));
275            if ~isempty(errormsg)
276                disp_uvmat('ERROR',['ERROR in merge_proj/read_field/' errormsg],checkrun)
277                return
278            end
279            ListVar=Data{iview}.ListVarName;
280            for ilist=1:numel(ListVar)
281                Data{iview}.(ListVar{ilist})=double(Data{iview}.(ListVar{ilist}));% transform all fields in double before all operations
282            end
283            % get the time defined in the current file if not already defined from the xml file
284            if ~isempty(time) && isfield(Data{iview},'Time')
285                timeread(iview)=Data{iview}.Time;
286            end
287            Data{iview}.ZIndex=index_j;
288            [X,Y]=meshgrid(DataVol.coord_x,DataVol.coord_y);%grid in physical coordinates
289            Data{iview}=proj_plane(Data{iview},XmlData{iview},X,Y); %project on the common x,y plane
290        end
291        % merge the NbView fields only to merge views from several cameras)
292
293        %     [MergeData,errormsg]=merge_field(ProjData);
294        %     if ~isempty(errormsg)
295        %         disp_uvmat('ERROR',errormsg,checkrun);
296        %         return
297        %     end
298        AMerge(index_j,:,:)=Data{iview}.A;
299
300        %%%%%%%%%%%%%%%% END LOOP FOR VOLUME SCAN %%%%%%%%%%%%%%%%
301    end
302    %interpolate on the vertical grid
303    Z=zeros(1,NbField_j);
304    for j_index=1:numel(DataVol.coord_y)
305        for i_index=1:numel(DataVol.coord_x)
306            for ZIndex=1:NbField_j
307            Z(ZIndex)=Zpos(XmlData{iview},ZIndex,X(j_index,i_index),Y(j_index,i_index));
308            end
309            DataVol.A(:,j_index,i_index) = interp1(Z,AMerge(:,j_index,i_index),DataVol.coord_z);
310        end
311    end
312    error=struct2nc(OutputFile,DataVol)%save result file
313
314
315    %     if index==1
316    %         TimeData.ListGlobalAttribute={'Conventions','Project','CoordUnit','TimeUnit','ZPos','Time'};
317    %         TimeData.Conventions='uvmat';
318    %         TimeData.Project='2016_Circumpolar';
319    %         TimeData.CoordUnit='cm';
320    %         TimeData.TimeUnit='s';
321    % %         TimeData.ZPos=ZPos;
322    %         TimeData.ListVarName={'radius','azimuth','U','V','curl','div'};
323    %         TimeData.VarDimName={'radius','azimuth',{'radius','azimuth'},{'radius','azimuth'}...
324    %             {'radius','azimuth'},{'radius','azimuth'}};
325    %         TimeData.VarAttribute{1}.Role='';
326    %         TimeData.VarAttribute{2}.Role='';
327    %         TimeData.VarAttribute{3}.Role='vector_x';
328    %         TimeData.VarAttribute{4}.Role='vector_y';
329    %         TimeData.VarAttribute{5}.Role='scalar';
330    %         TimeData.VarAttribute{6}.Role='scalar';
331    %
332    %     end
333    %
334    %         %% append data to the netcdf file for next iterations
335    %
336    %
337    %             error=struct2nc(OutputFile,TimeData);%save result file
338    %         if isempty(error)
339    %             disp(['output file ' OutputFile ' written'])
340    %         else
341    %             disp(error)
342    %         end
343    %             ellapsed_time=toc(tstart);
344    %     disp(['ellapsed time since start ' num2str(ellapsed_time/60,2) ' minutes'])
345end
346
347% disp([ num2str(ellapsed_time/(60*NbField),3) ' minutes per iteration'])
348
349% %'merge_field': concatene fields
350% %------------------------------------------------------------------------
351% function [MergeData,errormsg]=merge_field(Data)
352% %% default output
353% if isempty(Data)||~iscell(Data)
354%     MergeData=[];
355%     return
356% end
357% errormsg='';
358% MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
359% NbView=length(Data);
360% if NbView==1% if there is only one field, just reproduce it in MergeData
361%     return
362% end
363%
364% %% group the variables (fields of 'Data') in cells of variables with the same dimensions
365% [CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
366% if ~isempty(errormsg)
367%     return
368% end
369%
370% %LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
371% for icell=1:length(CellInfo)
372%     if NbDim(icell)~=1 % skip field cells which are of dim 1
373%         switch CellInfo{icell}.CoordType
374%             case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
375%                 for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
376%                     VarName=Data{1}.ListVarName{ivar};
377%                     for iview=2:NbView
378%                         MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
379%                     end
380%                 end
381%             case 'grid'        %case of fields defined on a structured  grid
382%                 FFName='';
383%                 if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
384%                     FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
385%                     MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
386%                     MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
387%                     MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
388%                 end
389%                 % select good data on each view
390%                 for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
391%                     VarName=Data{1}.ListVarName{ivar};
392%                     for iview=1:NbView
393%                         if isempty(FFName)
394%                             check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
395%                         else
396%                             check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
397%                         end
398%                         Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
399%                         if iview==1
400%                             %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
401%                             MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
402%                             NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
403%                         elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
404%                             errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
405%                             return
406%                         else
407%                             MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
408%                             NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
409%                         end
410%                     end
411%                     MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
412%                     MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
413%                 end
414%         end
415%   
416%     end
417% end
418
419% get the X position corresponding to X,Y for a given plane (labelled by ZIndex)
420
421function Z=Zpos(XmlData,ZIndex,X,Y)% Z positions correspoonding to X,Y positions
422Z=XmlData.Slice.SliceCoord(ZIndex,3)*ones(size(X));
423if isfield(XmlData.Slice,'SliceAngle')&&~isequal(XmlData.Slice.SliceAngle,[0 0 0])
424    [norm_plane(1), norm_plane(2), norm_plane(3)] =rotate_vector(XmlData.SliceAngle(ZIndex,:)*pi/180,0,0,1);
425    Z=Z-(norm_plane(1)*(X-XmlData.Slice.SliceCoord(ZIndex,1))+norm_plane(2)*(Y-XmlData.Slice.SliceCoord(ZIndex,2)))/norm_plane(3);
426end
427
428% proj_plane: poject each image on a common grid given by coord_x and coord_y
429function DataOut=proj_plane(DataIn,XmlData,X,Y)
430
431DataOut=DataIn; %default output
432
433%% initial image coordinates
434[npy,npx]=size(DataIn.A);
435xima=0.5:npx-0.5;%image coordinates of corners
436yima=npy-0.5:-1:0.5;
437[XIMA_init,YIMA_init]=meshgrid(xima,yima);%grid of initial image in px coordinates
438
439%% projected coordinates
440Z=Zpos(XmlData,DataIn.ZIndex,X,Y);% Z positions correspoonding to X,Y positions
441
442%% interpolation on the new grid
443[XIMA,YIMA]=px_XYZ(XmlData.GeometryCalib,XmlData.Slice,X,Y,Z);% image coordinates for each point in the real
444DataOut.A=interp2(XIMA_init,YIMA_init,DataIn.A,XIMA,YIMA);
445
446
447
448
449
450%'merge_field': concatene fields
451%------------------------------------------------------------------------
452function [MergeData,errormsg]=merge_field(Data)
453%% default output
454if isempty(Data)||~iscell(Data)
455    MergeData=[];
456    return
457end
458errormsg='';
459MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
460NbView=length(Data);
461if NbView==1% if there is only one field, just reproduce it in MergeData
462    return
463end
464
465%% group the variables (fields of 'Data') in cells of variables with the same dimensions
466[CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
467if ~isempty(errormsg)
468    return
469end
470
471%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
472for icell=1:length(CellInfo)
473    if NbDim(icell)~=1 % skip field cells which are of dim 1
474        switch CellInfo{icell}.CoordType
475            case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
476                for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
477                    VarName=Data{1}.ListVarName{ivar};
478                    for iview=2:NbView
479                        MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
480                    end
481                end
482            case 'grid'        %case of fields defined on a structured  grid
483                FFName='';
484                if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
485                    FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
486                    MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
487                    MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
488                    MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
489                end
490                % select good data on each view
491                for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
492                    VarName=Data{1}.ListVarName{ivar};
493                    for iview=1:NbView
494                        if isempty(FFName)
495                            check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
496                        else
497                            check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
498                        end
499                        Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
500                        if iview==1
501                            %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
502                            MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
503                            NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
504                        elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
505                            errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
506                            return
507                        else                             
508                            MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
509                            NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
510                        end
511                    end
512                    MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
513                    MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
514                end
515        end
516    end
517end   
Note: See TracBrowser for help on using the repository browser.