source: trunk/src/series/merge_proj_volume.m

Last change on this file was 1127, checked in by g7moreau, 4 months ago

Update Joel email

File size: 24.8 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-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
43%   http://www.legi.grenoble-inp.fr
44%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.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_y','coord_x','coord_z'}};
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   
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       
271        timeread=zeros(1,NbView);
272%         for iview=1:NbView
273            %% reading input file(s)
274            [Data,tild,errormsg] = read_field(filecell{1,index_j},FileType{1},ParamIn{1},frame_index{1}(index_j));
275            if ~isempty(errormsg)
276                disp_uvmat('ERROR',['ERROR in merge_proj/read_field/' errormsg],checkrun)
277                return
278            end
279            Data.A=Data.A(1:4:end,1:4:end);% reduce the mage size
280            ListVar=Data.ListVarName;
281            %reduce the image size
282            for ilist=1:numel(ListVar)
283                Data.(ListVar{ilist})=double(Data.(ListVar{ilist}));% transform all fields in double before all operations
284            end
285            % get the time defined in the current file if not already defined from the xml file
286            if ~isempty(time) && isfield(Data,'Time')
287                timeread(iview)=Data.Time;
288            end
289            Data.ZIndex=index_j;
290            [X,Y,Z]=meshgrid(DataVol.coord_x,DataVol.coord_y,DataVol.coord_z);%grid in physical coordinates
291            %Data{iview}=proj_plane(Data{iview},XmlData{iview},X,Y); %project on the common x,y plane
292
293        if index_j==1
294            AMerge=zeros(size(Data.A,1),size(Data.A,2),NbField_j);
295        end
296        AMerge(:,:,index_j)=Data.A;
297
298        %%%%%%%%%%%%%%%% END LOOP FOR VOLUME SCAN %%%%%%%%%%%%%%%%
299    end
300    %interpolate on the vertical grid
301    DataVol.A=proj_volume(AMerge,XmlData{1},X,Y,Z);
302%     Z=zeros(1,NbField_j);
303%     for j_index=1:numel(DataVol.coord_y)
304%         for i_index=1:numel(DataVol.coord_x)
305%             for ZIndex=1:NbField_j
306%             Z(ZIndex)=Zpos(XmlData{iview},ZIndex,X(j_index,i_index),Y(j_index,i_index));
307%             end
308%             DataVol.A(:,j_index,i_index) = interp1(Z,AMerge(:,j_index,i_index),DataVol.coord_z);
309%         end
310%     end
311    error=struct2nc(OutputFile,DataVol)%save result file
312
313end
314
315% disp([ num2str(ellapsed_time/(60*NbField),3) ' minutes per iteration'])
316
317% %'merge_field': concatene fields
318% %------------------------------------------------------------------------
319% function [MergeData,errormsg]=merge_field(Data)
320% %% default output
321% if isempty(Data)||~iscell(Data)
322%     MergeData=[];
323%     return
324% end
325% errormsg='';
326% MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
327% NbView=length(Data);
328% if NbView==1% if there is only one field, just reproduce it in MergeData
329%     return
330% end
331%
332% %% group the variables (fields of 'Data') in cells of variables with the same dimensions
333% [CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
334% if ~isempty(errormsg)
335%     return
336% end
337%
338% %LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
339% for icell=1:length(CellInfo)
340%     if NbDim(icell)~=1 % skip field cells which are of dim 1
341%         switch CellInfo{icell}.CoordType
342%             case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
343%                 for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
344%                     VarName=Data{1}.ListVarName{ivar};
345%                     for iview=2:NbView
346%                         MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
347%                     end
348%                 end
349%             case 'grid'        %case of fields defined on a structured  grid
350%                 FFName='';
351%                 if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
352%                     FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
353%                     MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
354%                     MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
355%                     MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
356%                 end
357%                 % select good data on each view
358%                 for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
359%                     VarName=Data{1}.ListVarName{ivar};
360%                     for iview=1:NbView
361%                         if isempty(FFName)
362%                             check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
363%                         else
364%                             check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
365%                         end
366%                         Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
367%                         if iview==1
368%                             %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
369%                             MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
370%                             NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
371%                         elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
372%                             errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
373%                             return
374%                         else
375%                             MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
376%                             NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
377%                         end
378%                     end
379%                     MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
380%                     MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
381%                 end
382%         end
383%   
384%     end
385% end
386
387% get the X position corresponding to X,Y for a given plane (labelled by ZIndex)
388
389function Z=Zpos(XmlData,ZIndex,X,Y)% Z positions correspoonding to X,Y positions
390Z=XmlData.Slice.SliceCoord(ZIndex,3)*ones(size(X));
391if isfield(XmlData.Slice,'SliceAngle')&&~isequal(XmlData.Slice.SliceAngle,[0 0 0])
392    [norm_plane(1), norm_plane(2), norm_plane(3)] =rotate_vector(XmlData.SliceAngle(ZIndex,:)*pi/180,0,0,1);
393    Z=Z-(norm_plane(1)*(X-XmlData.Slice.SliceCoord(ZIndex,1))+norm_plane(2)*(Y-XmlData.Slice.SliceCoord(ZIndex,2)))/norm_plane(3);
394end
395
396
397function ZIndex=XYZtoIndex(XmlData,X,Y,Z)% Z positions corresponding to X,Y positions
398Zp=Z-XmlData.Slice.SliceCoord(1,3);
399DZ=XmlData.Slice.SliceCoord(end,3)-XmlData.Slice.SliceCoord(1,3)/(size(XmlData.Slice.SliceCoord,1)-1);
400if DZ~=0
401ZIndex=(Z-XmlData.Slice.SliceCoord(1,3))/DZ+1;% Z=XmlData.SliceCoord(1,3)+(ZIndex-1)*DZ
402end
403% effect of angular deviation
404SliceAngleMax=XmlData.Slice.SliceAngle(end,:)-XmlData.Slice.SliceAngle(1,:);
405normAxe=norm(SliceAngleMax);
406if normAxe>0 % case of angle scan
407a=-SliceAngleMax(2)/normAxe;
408b=-SliceAngleMax(1)/normAxe;
409c=-a*XmlData.Slice.SliceCoord(1,1)+b*XmlData.Slice.SliceCoord(1,2);%equation of the axis ax+by+c=0
410DNormal=norm(a*X+b*Y+c);
411Ang=atand(Zp./DNormal);
412ZIndex=ZIndex+Ang-norm(XmlData.Slice.SliceAngle(1,:))+1;
413end
414
415%------------------------------------------------------------
416% proj_volume: poject each image on a common grid given by coord_x and coord_y
417function A=proj_volume(AMerge,XmlData,X,Y,Z)
418
419A=[]; %default output
420
421%% initial image coordinates
422[npy,npx,npz]=size(AMerge);
423xima=0.5:npx-0.5;%image coordinates of corners
424%yima=npy-0.5:-1:0.5;
425yima=0.5:npy-0.5;
426zima=0.5:npz-0.5;
427[XIMA_init,YIMA_init,ZIMA_init]=meshgrid(xima,yima,zima);%grid of initial image in px coordinates
428
429%% projected coordinates
430ZIndex=XYZtoIndex(XmlData,X,Y,Z);% Z positions correspoonding to X,Y positions
431
432%% interpolation on the new grid
433[XIMA,YIMA]=px_XYZ(XmlData.GeometryCalib,XmlData.Slice,X,Y,Z);% image coordinates for each point in the real
434A=interp3(XIMA_init,YIMA_init,ZIMA_init,AMerge,XIMA,YIMA,ZIndex);
435
436
437
438% proj_plane: poject each image on a common grid given by coord_x and coord_y
439function DataOut=proj_plane(DataIn,XmlData,X,Y)
440
441DataOut=DataIn; %default output
442
443%% initial image coordinates
444[npy,npx]=size(DataIn.A);
445xima=0.5:npx-0.5;%image coordinates of corners
446yima=npy-0.5:-1:0.5;
447[XIMA_init,YIMA_init]=meshgrid(xima,yima);%grid of initial image in px coordinates
448
449%% projected coordinates
450Z=Zpos(XmlData,DataIn.ZIndex,X,Y);% Z positions correspoonding to X,Y positions
451
452%% interpolation on the new grid
453[XIMA,YIMA]=px_XYZ(XmlData.GeometryCalib,XmlData.Slice,X,Y,Z);% image coordinates for each point in the real
454DataOut.A=interp2(XIMA_init,YIMA_init,DataIn.A,XIMA,YIMA);
455
456
457
458
459
460%'merge_field': concatene fields
461%------------------------------------------------------------------------
462function [MergeData,errormsg]=merge_field(Data)
463%% default output
464if isempty(Data)||~iscell(Data)
465    MergeData=[];
466    return
467end
468errormsg='';
469MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
470NbView=length(Data);
471if NbView==1% if there is only one field, just reproduce it in MergeData
472    return
473end
474
475%% group the variables (fields of 'Data') in cells of variables with the same dimensions
476[CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
477if ~isempty(errormsg)
478    return
479end
480
481%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
482for icell=1:length(CellInfo)
483    if NbDim(icell)~=1 % skip field cells which are of dim 1
484        switch CellInfo{icell}.CoordType
485            case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
486                for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
487                    VarName=Data{1}.ListVarName{ivar};
488                    for iview=2:NbView
489                        MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
490                    end
491                end
492            case 'grid'        %case of fields defined on a structured  grid
493                FFName='';
494                if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
495                    FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
496                    MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
497                    MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
498                    MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
499                end
500                % select good data on each view
501                for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
502                    VarName=Data{1}.ListVarName{ivar};
503                    for iview=1:NbView
504                        if isempty(FFName)
505                            check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
506                        else
507                            check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
508                        end
509                        Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
510                        if iview==1
511                            %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
512                            MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
513                            NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
514                        elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
515                            errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
516                            return
517                        else                             
518                            MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
519                            NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
520                        end
521                    end
522                    MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
523                    MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
524                end
525        end
526    end
527end   
Note: See TracBrowser for help on using the repository browser.