source: trunk/src/series/merge_proj_polar_singlefile.m @ 1055

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