source: trunk/src/series/merge_proj_polar.m @ 1061

Last change on this file since 1061 was 1061, checked in by g7moreau, 6 years ago
  • Update copyright to year 2019
File size: 27.4 KB
Line 
1%'merge_proj': concatene several fields from series, project on a polar grid
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-2019, 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_polar(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='on'; %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='off';%can use projection object(option 'off'/'on',
71    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
72    ParamOut.OutputDirExt='.polar';%set the output dir extension
73    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
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%%%% specific input parameters
90% calculate the positions on which to interpolate
91radius_ref=450;% radius of the mountain top
92radius_shifted=-130:2:130;% radius shifted by the radius of the origin at the topography summit
93radius=radius_ref+radius_shifted;%radius from centre of the tank
94azimuth_arclength=(-150:2:400);%azimuth in arc length at origin position
95azimuth=pi/2-azimuth_arclength/radius_ref;%azimuth in radian
96[Radius,Azimuth]=meshgrid(radius,azimuth);
97XI=Radius.*cos(Azimuth);% set of x axis of the points where interpolqtion needs to be done
98YI=Radius.*sin(Azimuth)-radius_ref;% set of y axis of the points where interpolqtion needs to be done
99FieldNames={'vec(U,V)';'curl(U,V)';'div(U,V)'};
100HeadData.ListVarName= {'radius','azimuth'} ;
101HeadData.VarDimName={'radius','azimuth'};
102HeadData.VarAttribute{1}.Role='coord_y';
103HeadData.VarAttribute{2}.Role='coord_x';
104HeadData.radius=radius_shifted;
105HeadData.azimuth=azimuth_arclength;   
106thresh2=16; % square of the interpolation range
107
108%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
109ParamOut=[]; %default output
110RUNHandle=[];
111WaitbarHandle=[];
112%% read input parameters from an xml file if input is a file name (batch mode)
113checkrun=1;
114if ischar(Param)
115    Param=xml2struct(Param);% read Param as input file (batch case)
116    checkrun=0;
117else
118    hseries=findobj(allchild(0),'Tag','series');
119    RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
120    WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
121end
122
123%% root input file type
124RootPath=Param.InputTable(:,1);
125RootFile=Param.InputTable(:,3);
126SubDir=Param.InputTable(:,2);
127%NomType=Param.InputTable(:,4);
128FileExt=Param.InputTable(:,5);
129[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
130%%%%%%%%%%%%
131% The cell array filecell is the list of input file names, while
132% filecell{iview,fileindex}:
133%        iview: line in the table corresponding to a given file series
134%        fileindex: file index within  the file series,
135% 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
136% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
137%%%%%%%%%%%%
138% NbSlice=1;%default
139% if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
140%     NbSlice=Param.IndexRange.NbSlice;
141% end
142NbView=numel(i1_series);%number of input file series (lines in InputTable)
143NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
144NbField_i=size(i1_series{1},2); %nb of fields for the i index
145NbField=NbField_j*NbField_i; %total number of fields
146
147%% define the name for result file (with path=RootPath{1})
148OutputDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
149% OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},'.nc','_1',i1_series{1}(1));
150% CheckOverwrite=1;%default
151% if isfield(Param,'CheckOverwrite')
152%     CheckOverwrite=Param.CheckOverwrite;
153% end
154% if ~CheckOverwrite && exist(OutputFile,'file')
155%     disp(['existing output file ' OutputFile ' already exists, skip to next field'])
156%     return% skip iteration if the mode overwrite is desactivated and the result file already exists
157% end
158
159if ~isfield(Param,'InputFields')
160    Param.InputFields.FieldName='';
161end
162
163
164%% determine the file type on each line from the first input file
165ImageTypeOptions={'image','multimage','mmreader','video','cine_phantom'};
166NcTypeOptions={'netcdf','civx','civdata'};
167for iview=1:NbView
168    if ~exist(filecell{iview,1}','file')
169        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
170        return
171    end
172    [FileInfo{iview},MovieObject{iview}]=get_file_info(filecell{iview,1});
173    FileType{iview}=FileInfo{iview}.FileType;
174    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
175    if CheckImage{iview}
176        ParamIn{iview}=MovieObject{iview};
177    else
178        ParamIn{iview}=Param.InputFields;
179    end
180    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
181    if ~isempty(j1_series{iview})
182        frame_index{iview}=j1_series{iview};
183    else
184        frame_index{iview}=i1_series{iview};
185    end
186end
187if NbView >1 && max(cell2mat(CheckImage))>0 && ~isfield(Param,'ProjObject')
188    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)
189    return
190end
191
192%% calibration data and timing: read the ImaDoc files
193[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
194if size(time,1)>1
195    diff_time=max(max(diff(time)));
196    if diff_time>0
197        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time) ': the mean time is chosen in result'],checkrun)
198    end   
199end
200if ~isempty(errormsg)
201    disp_uvmat('WARNING',errormsg,checkrun)
202end
203time=mean(time,1); %averaged time taken for the merged field
204
205%% height z
206    % position of projection plane
207   
208ProjObjectCoord=XmlData{1}.GeometryCalib.SliceCoord;
209CoordUnit=XmlData{1}.GeometryCalib.CoordUnit;
210for iview =2:numel(XmlData)
211    if ~(isfield(XmlData{iview},'GeometryCalib')&& isequal(XmlData{iview}.GeometryCalib.SliceCoord,ProjObjectCoord))...
212        disp('error: geometric calibration missing or inconsistent plane positions')
213        return
214    end
215end
216
217
218%% coordinate transform or other user defined transform
219transform_fct='';%default fct handle
220if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
221        currentdir=pwd;
222        cd(Param.FieldTransform.TransformPath)
223        transform_fct=str2func(Param.FieldTransform.TransformName);
224        cd (currentdir)
225        if isfield(Param,'TransformInput')
226            for iview=1:NbView
227            XmlData{iview}.TransformInput=Param.TransformInput;
228            end
229        end       
230end
231%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
232 % EDIT FROM HERE
233
234%% check the validity of  input file types
235for iview=1:NbView
236    if ~isequal(CheckNc{iview},1)
237        disp_uvmat('ERROR','input files needs to be in netcdf (extension .nc)',checkrun)
238        return
239    end
240end
241
242% %% output file type
243if isempty(j1_series{1})
244    NomTypeOut='_1';
245else
246    NomTypeOut='_1_1';
247end
248RootFileOut=RootFile{1};
249for iview=2:NbView
250    if ~strcmp(RootFile{iview},RootFile{1})
251        RootFileOut='mproj';
252        break
253    end
254end
255
256
257%% MAIN LOOP ON FIELDS
258%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
259% for i_slice=1:NbSlice
260%     index_slice=i_slice:NbSlice:NbField;% select file indices of the slice
261%     NbFiles=0;
262%     nbmissing=0;
263
264%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
265tstart=tic; %used to record the computing time
266CheckOverwrite=1;%default
267if isfield(Param,'CheckOverwrite')
268    CheckOverwrite=Param.CheckOverwrite;
269end
270
271for index=1:NbField
272    disp(['index=' num2str(index)])
273    disp(['ellapsed time ' num2str(toc(tstart)/60,4) ' minutes'])
274    update_waitbar(WaitbarHandle,index/NbField)
275    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
276        disp('program stopped by user')
277        return
278    end
279   
280        %% generating the name of the merged field
281        i1=i1_series{1}(index);
282        if ~isempty(i2_series{end})
283            i2=i2_series{end}(index);
284        else
285            i2=i1;
286        end
287        j1=1;
288        j2=1;
289        if ~isempty(j1_series{1})
290            j1=j1_series{1}(index);
291            if ~isempty(j2_series{end})
292                j2=j2_series{end}(index);
293            else
294                j2=j1;
295            end
296        end
297       OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFileOut,'.nc',NomTypeOut,i1,i2,j1,j2);
298        if ~CheckOverwrite && exist(OutputFile,'file')
299            disp(['existing output file ' OutputFile ' already exists, skip to next field'])
300            continue% skip iteration if the mode overwrite is desactivated and the result file already exists
301        end
302   
303    %% z position
304    ZIndex=mod(i1_series{1}(index)-1,NbSlice_calib{1})+1;%Zindex for phys transform
305    ZPosNew=ProjObjectCoord(ZIndex,3);
306    if index==1
307        ZPos=ZPosNew;
308    else
309        if ZPosNew~=ZPos
310            disp('inconsistent z positions in the series')
311            return
312        end
313    end
314    % radius of the topography section at z position
315    ind_mask=[];
316    if ZPos<20
317        TopoRadius=40*sin(acos((20+ZPos)/40));
318        ind_mask=(XI'.*XI'+YI'.*YI')<TopoRadius*TopoRadius;% indidces of data to mask
319    end
320   
321    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
322    Data=cell(1,NbView);%initiate the set Data
323    timeread=zeros(1,NbView);
324    for iview=1:NbView
325        %% reading input file(s)
326        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},ParamIn{iview},frame_index{iview}(index));
327        if ~isempty(errormsg)
328            disp_uvmat('ERROR',['ERROR in merge_proj/read_field/' errormsg],checkrun)
329            return
330        end
331        ListVar=Data{iview}.ListVarName;
332        for ilist=1:numel(ListVar)
333            Data{iview}.(ListVar{ilist})=double(Data{iview}.(ListVar{ilist}));% transform all fields in double before all operations
334        end
335        % get the time defined in the current file if not already defined from the xml file
336        if ~isempty(time) && isfield(Data{iview},'Time')
337            timeread(iview)=Data{iview}.Time;
338        end
339        if ~isempty(NbSlice_calib)
340            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
341        end
342       
343        %% transform the input field (e.g; phys) if requested (no transform involving two input fields)
344        if ~isempty(transform_fct)
345            if nargin(transform_fct)>=2
346                Data{iview}=transform_fct(Data{iview},XmlData{iview});
347            else
348                Data{iview}=transform_fct(Data{iview});
349            end
350        end
351       
352        %% calculate tps coefficients
353        Data{iview}=tps_coeff_field(Data{iview},1);
354       
355        %% projection on the polar grid
356        [DataOut,VarAttribute,errormsg]=calc_field_tps(Data{iview}.Coord_tps,Data{iview}.NbCentre,Data{iview}.SubRange,...
357            cat(3,Data{iview}.U_tps,Data{iview}.V_tps),FieldNames,cat(3,XI,YI));
358        % set to NaN interpolation points which are too far from any initial data (more than 2 CoordMesh)
359        Coord=permute(Data{iview}.Coord_tps,[1 3 2]);
360        Coord=reshape(Coord,size(Coord,1)*size(Coord,2),2);
361        if exist('scatteredInterpolant','file')%recent Matlab versions
362            F=scatteredInterpolant(Coord,Coord(:,1),'nearest');
363            G=scatteredInterpolant(Coord,Coord(:,2),'nearest');
364        else
365            F=TriScatteredInterp(Coord,Coord(:,1),'nearest');
366            G=TriScatteredInterp(Coord,Coord(:,2),'nearest');
367        end
368        Distx=F(XI,YI)-XI;% diff of x coordinates with the nearest measurement point
369        Disty=G(XI,YI)-YI;% diff of y coordinates with the nearest measurement point
370        Dist=Distx.*Distx+Disty.*Disty;
371        ListVarName=(fieldnames(DataOut))';
372        VarDimName=cell(size(ListVarName));
373        ProjData{iview}=HeadData;
374        ProjData{iview}.ListVarName= [ProjData{iview}.ListVarName ListVarName];
375        ProjData{iview}.VarDimName={'radius','azimuth'};
376%         ProjData{iview}.VarAttribute{1}.Role='coord_y';
377%         ProjData{iview}.VarAttribute{2}.Role='coord_x';
378        ProjData{iview}.VarAttribute=[ProjData{iview}.VarAttribute VarAttribute];
379        for ivar=1:numel(ListVarName)
380            ProjData{iview}.VarDimName{ivar+2}={'radius','azimuth'};
381            VarName=ListVarName{ivar};
382            if ~isempty(thresh2)
383                DataOut.(VarName)(Dist>thresh2)=NaN;% put to NaN interpolated positions further than RangeInterp from initial data
384            end
385            ProjData{iview}.(VarName)=(DataOut.(VarName))';
386        end
387       
388    end
389    %%%%%%%%%%%%%%%% END LOOP ON VIEWS %%%%%%%%%%%%%%%%
390   
391    %% merge the NbView fields
392    [MergeData,errormsg]=merge_field(ProjData);
393    if ~isempty(errormsg)
394        disp_uvmat('ERROR',errormsg,checkrun);
395        return
396    end
397   
398   
399    %% time of the merged field: take the average of the different views
400    if ~isempty(time)
401        timeread=time(index);
402    elseif ~isempty(find(timeread))% time defined from ImaDoc
403        timeread=mean(timeread(timeread~=0));% take average over times form the files (when defined)
404    else
405        timeread=index;% take time=file index
406    end
407   
408    %% rotating the velocity vectors to the local axis of the polatr coordinates
409    Unew=MergeData.U.*sin(Azimuth')-MergeData.V.*cos(Azimuth');
410    Vnew=MergeData.U.*cos(Azimuth')+MergeData.V.*sin(Azimuth');
411    if ~isempty(ind_mask)
412        Unew(ind_mask)=NaN;
413        Vnew(ind_mask)=NaN;
414        MergeData.curl(ind_mask)=NaN;
415        MergeData.div(ind_mask)=NaN;
416    end
417    [npy,npx]=size(Unew);
418   
419    %% create the output file for the first iteration of the loop
420    if index==1
421        TimeData.ListGlobalAttribute={'Conventions','Project','CoordUnit','TimeUnit','ZPos','Time'};
422        TimeData.Conventions='uvmat';
423        TimeData.Project='2016_Circumpolar';
424        TimeData.CoordUnit='cm';
425        TimeData.TimeUnit='s';
426        TimeData.ZPos=ZPos;
427        TimeData.ListVarName={'radius','azimuth','U','V','curl','div'};
428        TimeData.VarDimName={'radius','azimuth',{'radius','azimuth'},{'radius','azimuth'}...
429            {'radius','azimuth'},{'radius','azimuth'}};
430        TimeData.VarAttribute{1}.Role='';
431        TimeData.VarAttribute{2}.Role='';
432        TimeData.VarAttribute{3}.Role='vector_x';
433        TimeData.VarAttribute{4}.Role='vector_y';
434        TimeData.VarAttribute{5}.Role='scalar';
435        TimeData.VarAttribute{6}.Role='scalar';
436       
437        TimeData.radius=radius_shifted;
438        TimeData.azimuth=azimuth_arclength;
439    end
440       
441        %% append data to the netcdf file for next iterations
442        TimeData.Time=timeread;
443       TimeData.U=Unew;
444       TimeData.V=Vnew;
445       TimeData.curl=MergeData.curl;
446       TimeData.div=MergeData.div;
447
448            [error,ncid]=struct2nc(OutputFile,TimeData);%save result file
449        if isempty(error)
450            disp(['output file ' OutputFile ' written'])
451        else
452            disp(error)
453        end
454            ellapsed_time=toc(tstart);
455    disp(['total ellapsed time ' num2str(ellapsed_time/60,2) ' minutes'])
456end
457
458ellapsed_time=toc(tstart);
459disp(['total ellapsed time ' num2str(ellapsed_time/60,2) ' minutes'])
460disp([ num2str(ellapsed_time/(60*NbField),3) ' minutes per iteration'])
461
462% %'merge_field': concatene fields
463% %------------------------------------------------------------------------
464% function [MergeData,errormsg]=merge_field(Data)
465% %% default output
466% if isempty(Data)||~iscell(Data)
467%     MergeData=[];
468%     return
469% end
470% errormsg='';
471% MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
472% NbView=length(Data);
473% if NbView==1% if there is only one field, just reproduce it in MergeData
474%     return
475% end
476%
477% %% group the variables (fields of 'Data') in cells of variables with the same dimensions
478% [CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
479% if ~isempty(errormsg)
480%     return
481% end
482%
483% %LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
484% for icell=1:length(CellInfo)
485%     if NbDim(icell)~=1 % skip field cells which are of dim 1
486%         switch CellInfo{icell}.CoordType
487%             case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
488%                 for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
489%                     VarName=Data{1}.ListVarName{ivar};
490%                     for iview=2:NbView
491%                         MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
492%                     end
493%                 end
494%             case 'grid'        %case of fields defined on a structured  grid
495%                 FFName='';
496%                 if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
497%                     FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
498%                     MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
499%                     MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
500%                     MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
501%                 end
502%                 % select good data on each view
503%                 for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
504%                     VarName=Data{1}.ListVarName{ivar};
505%                     for iview=1:NbView
506%                         if isempty(FFName)
507%                             check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
508%                         else
509%                             check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
510%                         end
511%                         Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
512%                         if iview==1
513%                             %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
514%                             MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
515%                             NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
516%                         elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
517%                             errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
518%                             return
519%                         else
520%                             MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
521%                             NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
522%                         end
523%                     end
524%                     MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
525%                     MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
526%                 end
527%         end
528%   
529%     end
530% end
531
532
533%'merge_field': concatene fields
534%------------------------------------------------------------------------
535function [MergeData,errormsg]=merge_field(Data)
536%% default output
537if isempty(Data)||~iscell(Data)
538    MergeData=[];
539    return
540end
541errormsg='';
542MergeData=Data{1};% merged field= first field by default, reproduces the global attributes of the first field
543NbView=length(Data);
544if NbView==1% if there is only one field, just reproduce it in MergeData
545    return
546end
547
548%% group the variables (fields of 'Data') in cells of variables with the same dimensions
549[CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
550if ~isempty(errormsg)
551    return
552end
553
554%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
555for icell=1:length(CellInfo)
556    if NbDim(icell)~=1 % skip field cells which are of dim 1
557        switch CellInfo{icell}.CoordType
558            case 'scattered'  %case of input fields with unstructured coordinates: just concatene data
559                for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
560                    VarName=Data{1}.ListVarName{ivar};
561                    for iview=2:NbView
562                        MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
563                    end
564                end
565            case 'grid'        %case of fields defined on a structured  grid
566                FFName='';
567                if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
568                    FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
569                    MergeData.ListVarName(CellInfo{icell}.VarIndex_errorflag)=[];%remove error flag variable in MergeData (will use NaN instead)
570                    MergeData.VarDimName(CellInfo{icell}.VarIndex_errorflag)=[];
571                    MergeData.VarAttribute(CellInfo{icell}.VarIndex_errorflag)=[];
572                end
573                % select good data on each view
574                for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
575                    VarName=Data{1}.ListVarName{ivar};
576                    for iview=1:NbView
577                        if isempty(FFName)
578                            check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
579                        else
580                            check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
581                        end
582                        Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
583                        if iview==1
584                            %MergeData.(VarName)=Data{1}.(VarName);% initiate MergeData with the first field
585                            MergeData.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
586                            NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
587                        elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
588                            errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
589                            return
590                        else                             
591                            MergeData.(VarName)=MergeData.(VarName) +double(Data{iview}.(VarName));%add data
592                            NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
593                        end
594                    end
595                    MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
596                    MergeData.(VarName)(NbAver==0)=NaN;% set to NaN the points with no good data
597                end
598        end
599    end
600end   
Note: See TracBrowser for help on using the repository browser.