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

Last change on this file since 1197 was 1197, checked in by sommeria, 3 days ago

bugs repaired

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