source: trunk/src/series/merge_proj.m @ 1194

Last change on this file since 1194 was 1194, checked in by sommeria, 8 days ago

several bugs repaired

File size: 24.6 KB
Line 
1%'merge_proj': concatene several fields from series, can project them on a regular grid in phys coordinates
2%------------------------------------------------------------------------
3% function ParamOut=merge_proj(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(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='off';% 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='one';% 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    %%%%% list of possible transform functions (needed only for compilation)
70    if 0==1 %never satisfied but trigger compilation with the appropriate transform functions ('eval' inactive for compilation)
71        phys
72        phys_polar
73        sub_field
74    end
75
76    ParamOut.TransformPath=fullfile(fileparts(which('uvmat')),'transform_field');% path to transform functions
77    %%%%%%%%
78    ParamOut.ProjObject='on';%can use projection object(option 'off'/'on',
79    ParamOut.Mask='on';%can use mask option   (option 'off'/'on', 'off' by default)
80    ParamOut.OutputDirExt='.mproj';%set the output dir extension
81    ParamOut.OutputFileMode='NbInput';% '=NbInput': 1 output file per input file index, '=NbInput_i': 1 file per input file index i, '=NbSlice': 1 file per slice
82      %check the input files
83    ParamOut.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
84    first_j=[];
85    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
86    PairString='';
87    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
88    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
89    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
90        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
91    if ~exist(FirstFileName,'file')
92        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
93    end
94    return
95end
96
97%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
98ParamOut=[]; %default output
99RUNHandle=[];
100WaitbarHandle=[];
101%% read input parameters from an xml file if input is a file name (batch mode)
102checkrun=1;
103if ischar(Param)
104    Param=xml2struct(Param);% read Param as input file (batch case)
105    checkrun=0;
106else
107    hseries=findobj(allchild(0),'Tag','series');
108    RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
109    WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
110end
111
112%% define the directory for result file (with path=RootPath{1})
113OutputDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
114
115if ~isfield(Param,'InputFields')
116    Param.InputFields.FieldName='';
117end
118
119%% root input file(s) name, type and index series
120RootPath=Param.InputTable(:,1);
121RootFile=Param.InputTable(:,3);
122SubDir=Param.InputTable(:,2);
123FileExt=Param.InputTable(:,5);
124
125hdisp=disp_uvmat('WAITING...','checking the file series',checkrun);
126% gives the series of input file names and indices set by the input parameters:
127[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
128% filecell{iview,fileindex}:
129%        iview: line in the table corresponding to a given file series
130%        fileindex: file index with i and j reshaped as a 1D array
131% 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
132% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
133if ~isempty(hdisp),delete(hdisp),end %end the waiting display
134
135NbView=numel(i1_series);%number of input file series (lines in InputTable)
136NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
137NbField_i=size(i1_series{1},2); %nb of fields for the i index
138NbField=NbField_j*NbField_i; %total number of fields
139
140%% determine the file type on each line from the first input file
141NcTypeOptions={'netcdf','civx','civdata','pivdata_fluidimage'};
142for iview=1:NbView
143    if ~exist(filecell{iview,1}','file')
144        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
145        return
146    end
147    [FileInfo{iview},MovieObject{iview}]=get_file_info(filecell{iview,1});
148    FileType{iview}=FileInfo{iview}.FileType;
149    if strcmp(FileType{iview},'civdata')&&  ~isfield(Param.InputFields,'VelType')
150        FileType{iview}='netcdf';
151    end
152    CheckImage{iview}=strcmp(FileInfo{iview}.FieldType,'image');% =1 for images
153    if CheckImage{iview}
154        ParamIn{iview}=MovieObject{iview};
155    else
156        ParamIn{iview}=Param.InputFields;
157    end
158    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
159    if ~isempty(j1_series{iview})
160        frame_index{iview}=j1_series{iview};
161    else
162        frame_index{iview}=i1_series{iview};
163    end
164end
165if NbView >1 && max(cell2mat(CheckImage))>0 && ~isfield(Param,'ProjObject')
166    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)
167    return
168end
169
170%% calibration data and timing: read the ImaDoc files
171[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
172if size(time,1)>1
173    diff_time=max(max(diff(time)));
174    if diff_time>0
175        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time) ': the mean time is chosen in result'],checkrun)
176    end   
177end
178if ~isempty(errormsg)
179    disp_uvmat('WARNING',errormsg,checkrun)
180end
181time=mean(time,1); %averaged time taken for the merged field
182
183%% coordinate transform or other user defined transform
184transform_fct='';%default fct handle
185 checksub=0;
186if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
187    currentdir=pwd;
188    cd(Param.FieldTransform.TransformPath)
189    if strcmp(Param.FieldTransform.TransformName,'sub_field')
190        checksub=2;% the two into field series will be subtracted
191    end
192    transform_fct=str2func(Param.FieldTransform.TransformName);
193    cd (currentdir)
194    if isfield(Param,'TransformInput')
195        for iview=1:NbView
196            XmlData{iview}.TransformInput=Param.TransformInput;
197        end
198    end
199    if checksub>2 && NbView>2
200        disp_uvmat('WARNING',['only the two first input file series will be combined by ' Param.FieldTransform.TransformName],checkrun)
201    end
202end
203%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
204 % EDIT FROM HERE
205
206%% check the validity of  input file types
207for iview=1:NbView
208    if ~isequal(CheckImage{iview},1)&&~isequal(CheckNc{iview},1)
209        disp_uvmat('ERROR','input set of input series: need  either netcdf either image series',checkrun)
210        return
211    end
212end
213
214%% output file type
215if min(cell2mat(CheckImage))==1 && (~Param.CheckObject || strcmp(Param.ProjObject.Type,'plane'))
216    FileExtOut='.png'; %image output (input and proj result = image)
217else
218    FileExtOut='.nc'; %netcdf output
219end
220if isempty(j1_series{1})
221    NomTypeOut='_1';
222else
223    NomTypeOut='_1_1';
224end
225RootFileOut=RootFile{1};
226for iview=2:NbView
227    if ~strcmp(RootFile{iview},RootFile{1})
228        RootFileOut='mproj';
229        break
230    end
231end
232
233
234%% Set field names and velocity types
235%use Param.InputFields for all views
236
237%% MAIN LOOP ON FIELDS
238%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
239
240    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
241tstart=tic; %used to record the computing time
242CheckOverwrite=1;%default
243if isfield(Param,'CheckOverwrite')
244    CheckOverwrite=Param.CheckOverwrite;
245end
246OutputPath=fullfile(Param.OutputPath,num2str(Param.Experiment),num2str(Param.Device));
247
248for index=1:NbField
249        update_waitbar(WaitbarHandle,index/NbField)
250    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
251        disp('program stopped by user')
252        return
253    end
254   
255     %% generating the name of the merged field
256    i1=i1_series{1}(index);
257    if ~isempty(i2_series{end})
258        i2=i2_series{end}(index);
259    else
260        i2=i1;
261    end
262    j1=1;
263    j2=1;
264    if ~isempty(j1_series{1})
265        j1=j1_series{1}(index);
266    end
267    i_out=floor((i1+i2)/2);
268    OutputFile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,FileExtOut,NomTypeOut,i_out,[],j1);
269    if ~CheckOverwrite && exist(OutputFile,'file')
270            disp(['existing output file ' OutputFile ' already exists, skip to next field'])
271            continue% skip iteration if the mode overwrite is desactivated and the result file already exists
272    end
273       
274    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
275    Data=cell(1,NbView);%initiate the set Data
276    timeread=zeros(1,NbView);
277    for iview=1:NbView
278        %% reading input file(s)     
279        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},ParamIn{iview},frame_index{iview}(index));
280        if isempty(errormsg)
281            disp([filecell{iview,index} ' read OK'])
282        else
283            disp_uvmat('ERROR',['ERROR in merge_proj/read_field/' errormsg],checkrun)
284            return
285        end
286       
287        ListVar=Data{iview}.ListVarName;
288        for ilist=1:numel(ListVar)
289            Data{iview}.(ListVar{ilist})=double(Data{iview}.(ListVar{ilist}));% transform all fields in double before all operations
290        end
291        % get the time defined in the current file if not already defined from the xml file
292        if isempty(time) && isfield(Data{iview},'Time')
293            timeread(iview)=Data{iview}.Time;
294        end
295        if ~isempty(NbSlice_calib)
296            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
297        end
298       
299        %% transform the input field iview (e.g; phys) if requested (no transform involving two input fields at this stage)
300        if ~isempty(transform_fct)&& checksub==0
301            if nargin(transform_fct)>=2
302                Data{iview}=transform_fct(Data{iview},XmlData{iview});
303            else
304                Data{iview}=transform_fct(Data{iview});
305            end
306        end
307       
308        %% calculate tps coefficients if needed
309
310        check_proj_tps= strcmp(FileType{iview},'civdata') && isfield(Param,'ProjObject')&&~isempty(Param.ProjObject)...
311            && strcmp(Param.ProjObject.ProjMode,'interp_tps')&&~isfield(Data{iview},'Coord_tps');
312        if check_proj_tps
313        Data{iview}=tps_coeff_field(Data{iview},check_proj_tps);
314        end
315       
316        %% projection on object (gridded plane)
317        if Param.CheckObject
318            [Data{iview},errormsg]=proj_field(Data{iview},Param.ProjObject);
319            if ~isempty(errormsg)
320                disp_uvmat('ERROR',['ERROR in merge_proge/proj_field: ' errormsg],checkrun)
321                return
322            end
323        end
324       
325        %% mask
326        if Param.CheckMask % introduce multilevel mask like for civ
327            NbSlice=Param.MaskTable{iview,2};
328            [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.MaskTable{iview,1});
329            i1_mask=mod(i1-1,NbSlice)+1;
330            maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
331            if ~exist(maskname,'file')
332                maskname=Param.MaskTable{iview,1};
333            end
334            [MaskData,~,errormsg] = read_field(maskname,'image');
335            if ~isempty(NbSlice_calib)
336            MaskData.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
337        end
338            if ~isempty(transform_fct) && nargin(transform_fct)>=2
339                MaskData=transform_fct(MaskData,XmlData{iview});
340            end
341            if  ~isempty(MaskData)
342                [Data{iview},errormsg]=mask_proj(Data{iview},MaskData);
343            end
344        end
345    end
346    %%%%%%%%%%%%%%%% END LOOP ON VIEWS %%%%%%%%%%%%%%%%
347
348    %% merge the NbView fields
349    if checksub==0
350        [MergeData,errormsg]=merge_field(Data);%concatene all the input field series by fct merge_data
351    else
352        MergeData=transform_fct(Data{1},XmlData{1},Data{2}); %combine the two input file series
353    % else
354    %     MergeData=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});%combine the two input file series with calibration parameters
355    end
356    if ~isempty(errormsg)
357        disp_uvmat('ERROR',errormsg,checkrun);
358        return
359    end
360
361    %% time of the merged field: take the average of the different views
362    if ~isempty(time)
363        timeread=time(index);   
364    elseif ~isempty(find(timeread))% time defined from ImaDoc
365        timeread=mean(timeread(timeread~=0));% take average over times form the files (when defined)
366    else
367        timeread=index;% take time=file index
368    end
369
370 
371    %% recording the merged field
372    if strcmp(FileExtOut,'.png')    %output as image
373        if index==1
374            if strcmp(class(MergeData.A),'uint8')
375            BitDepth=8;
376            else
377              BitDepth=16; 
378            end
379            %write xml calibration file, using the first file
380            siz=size(MergeData.A);
381            npy=siz(1);
382            npx=siz(2);
383            if isfield(MergeData,'Coord_x') && isfield(MergeData,'Coord_y')
384                Rangx=MergeData.Coord_x;
385                Rangy=MergeData.Coord_y;
386            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
387                Rangx=[MergeData.AX(1) MergeData.AX(end)];
388                Rangy=[MergeData.AY(1) MergeData.AY(end)];
389            else
390                Rangx=[0.5 npx-0.5];
391                Rangy=[npy-0.5 0.5];%default
392            end
393            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
394            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
395            T_x=-pxcmx*Rangx(1)+0.5;
396            T_y=-pxcmy*Rangy(2)+0.5;
397            GeometryCal.CalibrationType='rescale';
398            GeometryCal.CoordUnit=MergeData.CoordUnit;
399            GeometryCal.focal=1;
400            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
401            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
402            ImaDoc.GeometryCalib=GeometryCal;
403            t=struct2xml(ImaDoc);
404            t=set(t,1,'name','ImaDoc');
405            save(t,[fileparts(OutputFile) '.xml'])
406        end
407        if BitDepth==8
408            imwrite(uint8(MergeData.A),OutputFile,'BitDepth',8)
409        else
410            imwrite(uint16(MergeData.A),OutputFile,'BitDepth',16)
411        end
412    else   %output as netcdf files
413        MergeData.ListGlobalAttribute={'Conventions','Project','InputFile_1','InputFile_end','NbCoord','NbDim'};
414        MergeData.Conventions='uvmat';
415        MergeData.NbCoord=2;
416        MergeData.NbDim=2;
417        % time interval of PIV
418        Dt=[];
419        if isfield(Data{1},'Dt')&& isnumeric(Data{1}.Dt)
420            Dt=Data{1}.Dt;
421        end
422        for iview =2:numel(Data)
423            if ~(isfield(Data{iview},'Dt')&& isequal(Data{iview}.Dt,Dt))
424                Dt=[];%dt not the same for all fields
425            end
426        end
427        if ~isempty(timeread)
428            MergeData.ListGlobalAttribute=[MergeData.ListGlobalAttribute {'Time'}];
429            MergeData.Time=timeread;
430        end
431        % position of projection plane
432        if isfield(Data{1},'ProjObjectCoord')&& isfield(Data{1},'ProjObjectAngle')
433            ProjObjectCoord=Data{1}.ProjObjectCoord;
434            ProjObjectAngle=Data{1}.ProjObjectAngle;
435            for iview =2:numel(Data)
436                if ~(isfield(Data{iview},'ProjObjectCoord')&& isequal(Data{iview}.ProjObjectCoord,ProjObjectCoord))...
437                        ||~(isfield(Data{iview},'ProjObjectAngle')&& isequal(Data{iview}.ProjObjectAngle,ProjObjectAngle))
438                    ProjObjectCoord=[];%dt not the same for all fields
439                end
440            end
441            if ~isempty(ProjObjectCoord)
442                MergeData.ListGlobalAttribute=[MergeData.ListGlobalAttribute {'ProjObjectCoord'} {'ProjObjectAngle'}];
443                MergeData.ProjObjectCoord=ProjObjectCoord;
444                MergeData.ProjObjectAngle=ProjObjectAngle;
445            end
446        end
447        % coord unit
448        if isfield(Data{1},'CoordUnit')
449            CoordUnit=Data{1}.CoordUnit;
450            for iview =2:numel(Data)
451                if ~(isfield(Data{iview},'CoordUnit')&& isequal(Data{iview}.CoordUnit,CoordUnit))
452                    CoordUnit=[];%CoordUnit not the same for all fields
453                end
454            end
455            if ~isempty(CoordUnit)
456                MergeData.ListGlobalAttribute=[MergeData.ListGlobalAttribute {'CoordUnit'}];
457                MergeData.CoordUnit=CoordUnit;
458            end
459        end
460        % time unit
461        if isfield(Data{1},'TimeUnit')
462            TimeUnit=Data{1}.TimeUnit;
463            for iview =2:numel(Data)
464                if ~(isfield(Data{iview},'TimeUnit')&& isequal(Data{iview}.TimeUnit,TimeUnit))
465                    TimeUnit=[];%TimeUnit not the same for all fields
466                end
467            end
468            if ~isempty(TimeUnit)
469                MergeData.ListGlobalAttribute=[MergeData.ListGlobalAttribute {'TimeUnit'}];
470                MergeData.TimeUnit=TimeUnit;
471            end
472        end
473        error=struct2nc(OutputFile,MergeData);%save result file
474        if isempty(error)
475            disp(['output file ' OutputFile ' written'])
476        else
477            disp(error)
478        end
479    end
480end
481ellapsed_time=toc(tstart);
482disp(['total ellapsed time ' num2str(ellapsed_time/60,2) ' minutes'])
483disp([ num2str(ellapsed_time/(60*NbField),3) ' minutes per iteration'])
484
485%'merge_field': concatene fields
486%------------------------------------------------------------------------
487function [MergeData,errormsg]=merge_field(Data)
488%% default output
489if isempty(Data)||~iscell(Data)
490    MergeData=[];
491    return
492end
493errormsg='';
494MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
495NbView=length(Data);
496if NbView==1% if there is only one field, just reproduce it in MergeData
497    return
498end
499
500%% group the variables (fields of 'Data') in cells of variables with the same dimensions
501[CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
502if ~isempty(errormsg)
503    return
504end
505
506%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
507for icell=1:length(CellInfo)
508    if NbDim(icell)~=1 % skip field cells which are of dim 1
509        switch CellInfo{icell}.CoordType
510            case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
511                for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
512                    VarName=Data{1}.ListVarName{ivar};
513                    for iview=2:NbView
514                        MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
515                    end
516                end
517            case 'grid'        %case of fields defined on a structured  grid
518                FFName='';
519                if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
520                    FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
521                    MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
522                    MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
523                    MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
524                end
525                % select good data on each view
526                for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
527                    VarName=Data{1}.ListVarName{ivar};
528                    for iview=1:NbView
529                        if isempty(FFName)
530                            check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
531                        else
532                            check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
533                        end
534                        Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
535                        if iview==1
536                            %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
537                            MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
538                            NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
539                        elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
540                            errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
541                            return
542                        else                             
543                            MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
544                            NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
545                        end
546                    end
547                    MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
548                    MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
549                end
550        end
551    end
552end
553
554
555   
Note: See TracBrowser for help on using the repository browser.