source: trunk/src/series/civ_series.m @ 1010

Last change on this file since 1010 was 1010, checked in by sommeria, 7 years ago

multimask introduced

File size: 66.3 KB
Line 
1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   filter_tps: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_series(Param)
8%
9%OUTPUT
10% Data=structure containing the PIV results and information on the processing parameters
11% errormsg=error message char string, decd ..fault=''
12% resul_conv: image inter-correlation function for the last grid point (used for tests)
13%
14%INPUT:
15% Param: Matlab structure of input  parameters
16%     Param contains info of the GUI series using the fct read_GUI.
17%     Param.Action.RUN = 0 (to set the status of the GUI series) or =1 to RUN the computation
18%     Param.InputTable: sets the input file(s)
19%           if absent, the fct looks for input data in Param.ActionInput     (test mode)
20%     Param.OutputSubDir: sets the folder name of output file(s,
21%           if absent no file is produced, result in the output structure Data (test mode)
22%     Param.ActionInput: substructure with the parameters provided by the GUI civ_input
23%                      .Civ1: parameters for civ1
24%                      .Fix1: parameters for fix1
25%                      .Patch1:
26%                      .Civ2: for civ2
27%                      .Fix2:
28%                      .Patch2:
29
30%=======================================================================
31% Copyright 2008-2017, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
32%   http://www.legi.grenoble-inp.fr
33%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
34%
35%     This file is part of the toolbox UVMAT.
36%
37%     UVMAT is free software; you can redistribute it and/or modify
38%     it under the terms of the GNU General Public License as published
39%     by the Free Software Foundation; either version 2 of the license,
40%     or (at your option) any later version.
41%
42%     UVMAT is distributed in the hope that it will be useful,
43%     but WITHOUT ANY WARRANTY; without even the implied warranty of
44%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45%     GNU General Public License (see LICENSE.txt) for more details.
46%=======================================================================
47
48function [Data,errormsg,result_conv]= civ_series(Param)
49errormsg='';
50
51%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
52if isstruct(Param) && isequal(Param.Action.RUN,0)% function activated from the GUI series but not RUN
53    path_series=fileparts(which('series'));
54    addpath(fullfile(path_series,'series'))
55    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
56    if isempty(Data)
57        Data=Param;% if  civ_input has been cancelled, keep previous parameters
58    end
59    Data.Program=mfilename;%gives the name of the current function
60    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
61    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
62    %     if isfield(Data,'ActionInput') && isfield(Data.ActionInput,'PairIndices')&& strcmp(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
63    %         Data.Desable_j_index='on';% hide the j index in series (set by the pair choice in civ_input)
64    %     end
65    Data.NbSlice='off'; %nbre of slices ('off' by default)
66    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
67    Data.FieldName='on';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
68    Data.FieldTransform = 'off';%can use a transform function
69    Data.ProjObject='off';%can use projection object(option 'off'/'on',
70    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
71    Data.OutputDirExt='.civ';%set the output dir extension
72    Data.OutputSubDirMode='last'; %select the last subDir in the input table as root of the output subdir name (option 'all'/'first'/'last', 'all' by default)
73    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
74    Data.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
75    if isequal(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
76        if isfield(Data.ActionInput.PairIndices,'ListPairCiv2')
77            str_civ=Data.ActionInput.PairIndices.ListPairCiv2;
78        else
79            str_civ=Data.ActionInput.PairIndices.ListPairCiv1;
80        end
81        r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
82        if isempty(r)
83            r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
84            if isempty(r)
85                r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
86            end
87        end
88        if ~isempty(r)
89            Data.j_index_1=stra2num(r.num1);
90            Data.j_index_2=stra2num(r.num2);
91        end
92    end
93    return
94end
95
96%% read input parameters from an xml file if input is a file name (batch mode)
97checkrun=1;
98if ischar(Param)
99    Param=xml2struct(Param);% read Param as input file (batch case)
100    checkrun=0;
101end
102
103%% test input
104if ~isfield(Param,'ActionInput')
105    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
106    return
107end
108iview_A=0;%default values
109NbField=1;
110RUNHandle=[];
111CheckInputFile=isfield(Param,'InputTable');%= 1 in test use for TestCiv (no nc file involved)
112CheckOutputFile=isfield(Param,'OutputSubDir');%= 1 in test use for TestPatch (no nc file produced)
113
114%% input files and indexing (skipped in Test mode)
115if CheckInputFile
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
119    MaxIndex_i=Param.IndexRange.MaxIndex_i;
120    MinIndex_i=Param.IndexRange.MinIndex_i;
121    MaxIndex_j=ones(size(MaxIndex_i));MinIndex_j=ones(size(MinIndex_i));
122    if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
123        MaxIndex_j=Param.IndexRange.MaxIndex_j;
124        MinIndex_j=Param.IndexRange.MinIndex_j;
125    end
126    if isfield(Param,'InputTable')
127        [tild,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
128        iview_A=0;% series index (iview) for the first image series
129        iview_B=0;% series index (iview) for the second image series (only non zero for option 'shift' comparing two image series )
130        if Param.ActionInput.CheckCiv1
131            iview_A=1;% usual PIV, the image series is on the first line of the table
132        elseif Param.ActionInput.CheckCiv2 % civ2 is performed without Civ1, a netcdf file series is needed in the first table line
133            iview_A=2;% the second line is used for the input images of Civ2
134        end
135        if strcmp(Param.ActionInput.ListCompareMode,'shift')
136            iview_B=iview_A+1; % the second image series is on the next line of the input table
137        end
138        if iview_A~=0
139            RootPath_A=Param.InputTable{iview_A,1};
140            RootFile_A=Param.InputTable{iview_A,3};
141            SubDir_A=Param.InputTable{iview_A,2};
142            NomType_A=Param.InputTable{iview_A,4};
143            FileExt_A=Param.InputTable{iview_A,5};
144            if iview_B==0
145                iview_B=iview_A;% the second image series is the same as the first
146            end
147            RootPath_B=Param.InputTable{iview_B,1};
148            RootFile_B=Param.InputTable{iview_B,3};
149            SubDir_B=Param.InputTable{iview_B,2};
150            NomType_B=Param.InputTable{iview_B,4};
151            FileExt_B=Param.InputTable{iview_B,5};
152        end
153       
154        PairCiv2='';
155        switch Param.ActionInput.ListCompareMode
156            case 'PIV'
157                PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
158                if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
159                    PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;%string which determines the civ2 pair
160                end
161                if iview_A==1% if Civ1 is performed
162                    [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
163                        find_pair_indices(PairCiv1,i1_series{1},j1_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
164                    if ~isempty(PairCiv2)
165                        [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
166                            find_pair_indices(PairCiv2,i1_series{1},j1_series{1},MinIndex_i(1),MaxIndex_i(1),MinIndex_j(1),MaxIndex_j(1));
167                        check_bounds=check_bounds | check_bounds_Civ2;
168                    end
169                else% we start from an existing Civ1 file
170                    i1_series_Civ1=i1_series{1};
171                    i2_series_Civ1=i2_series{1};
172                    j1_series_Civ1=j1_series{1};
173                    j2_series_Civ1=j2_series{1};
174                    NomTypeNc=Param.InputTable{1,4};
175                    if ~isempty(PairCiv2)
176                        [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds,NomTypeNc]=...
177                            find_pair_indices(PairCiv2,i1_series{2},j1_series{2},MinIndex_i(2),MaxIndex_i(2),MinIndex_j(2),MaxIndex_j(2));
178                    end
179                end
180            case 'displacement'
181                i1_series_Civ1=Param.ActionInput.OriginIndex*ones(size(i1_series{1}));
182                i2_series_Civ1=i1_series{1};i2_series_Civ2=i1_series{1};
183                j1_series_Civ1=ones(size(i1_series{1}));% first j index is 1
184                if isempty(j1_series_Civ1)
185                    j2_series_Civ1=ones(size(i1_series{1}));
186                else
187                    j2_series_Civ1=j1_series_Civ1;
188                end
189                i1_series_Civ2=i1_series_Civ1;
190                j1_series_Civ2=j1_series_Civ1;
191                j2_series_Civ2=j2_series_Civ1;
192                NomTypeNc=Param.InputTable{1,4};
193            case 'PIV volume'
194                % TODO, TODO
195        end
196        if isempty(j1_series_Civ1)
197            FrameIndex_A_Civ1=i1_series_Civ1;
198            FrameIndex_B_Civ1=i2_series_Civ1;
199            j1_series_Civ1=ones(size(i1_series_Civ1));
200            j2_series_Civ1=ones(size(i1_series_Civ1));
201        else
202            FrameIndex_A_Civ1=j1_series_Civ1;
203            FrameIndex_B_Civ1=j2_series_Civ1;
204        end
205        if isempty(PairCiv2)
206            FrameIndex_A_Civ2=FrameIndex_A_Civ1;
207            FrameIndex_B_Civ2=FrameIndex_B_Civ1;
208        else
209            if isempty(j1_series_Civ2)
210                FrameIndex_A_Civ2=i1_series_Civ2;
211                FrameIndex_B_Civ2=i2_series_Civ2;
212                j1_series_Civ2=ones(size(i1_series_Civ2));
213                j2_series_Civ2=ones(size(i1_series_Civ2));
214            else
215                FrameIndex_A_Civ2=j1_series_Civ2;
216                FrameIndex_B_Civ2=j2_series_Civ2;
217            end
218        end
219        if isempty(i1_series_Civ1)||(~isempty(PairCiv2) && isempty(i1_series_Civ2))
220            disp_uvmat('ERROR','no image pair for civ in the input file index range',checkrun)
221            return
222        end
223    end
224   
225    %% check the first image pair
226        if Param.ActionInput.CheckCiv1% Civ1 is performed
227            NbField=numel(i1_series_Civ1);
228        elseif Param.ActionInput.CheckCiv2 % Civ2 is performed without Civ1
229
230            NbField=numel(i1_series_Civ2);
231        else
232            NbField=numel(i1_series_Civ1);% no image used (only fix or patch) TO CHECK
233        end
234
235   
236   
237    %% Output directory
238    OutputDir='';
239    if CheckOutputFile
240        OutputDir=[Param.OutputSubDir Param.OutputDirExt];
241    end
242end
243
244%% prepare output Data
245ListGlobalAttribute={'Conventions','Program','CivStage'};
246Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
247Data.Program='civ_series';
248Data.CivStage=0;%default
249check_civx=0;%default
250
251%% get timing from the ImaDoc file or input video
252if iview_A~=0
253    XmlFileName=find_imadoc(RootPath_A,SubDir_A,RootFile_A,FileExt_A);
254    Time=[];
255    if ~isempty(XmlFileName)
256        XmlData=imadoc2struct(XmlFileName);
257        if isfield(XmlData,'Time')
258            Time=XmlData.Time;
259            TimeSource='xml';
260        end
261        if isfield(XmlData,'Camera')
262            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
263                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
264                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
265                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
266                end
267            end
268            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
269                TimeUnit=XmlData.Camera.TimeUnit;
270            end
271        end
272    end
273   
274
275end
276
277%%%%% MAIN LOOP %%%%%%
278maskoldname='';% initiate the mask name
279FileType_A='';
280FileType_B='';
281CheckOverwrite=1;%default
282if isfield(Param,'CheckOverwrite')
283    CheckOverwrite=Param.CheckOverwrite;
284end
285for ifield=1:NbField
286    tic
287    if ~isempty(RUNHandle)% update the waitbar in interactive mode with GUI series  (checkrun=1)
288        update_waitbar(WaitbarHandle,ifield/NbField)
289        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
290            disp('program stopped by user')
291            break
292        end
293    end
294    if CheckInputFile
295        if iview_A==0 % no nc file has been entered
296            ncfile=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},Param.InputTable{1,5},...
297                NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),j1_series_Civ1(ifield),j2_series_Civ1(ifield));
298        else% an existing nc file has been entered
299            if iview_A==1% if Civ1 is performed
300                Civ1Dir=OutputDir;
301            else
302                Civ1Dir=Param.InputTable{1,2};
303            end
304            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
305                ncfile=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
306                    j1_series_Civ1(ifield),j2_series_Civ1(ifield));
307            else
308                ncfile=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
309                    j1_series_Civ1(ifield),j2_series_Civ1(ifield));
310            end
311        end
312        ncfile_out=ncfile;% by default
313        if isfield (Param.ActionInput,'Civ2')
314            i1_civ2=i1_series_Civ2(ifield);
315            i2_civ2=i1_civ2;
316            if ~isempty(i2_series_Civ2)
317                i2_civ2=i2_series_Civ2(ifield);
318            end
319            j1_civ2=1;
320            if ~isempty(j1_series_Civ2)
321                j1_civ2=j1_series_Civ2(ifield);
322            end
323            j2_civ2=i1_civ2;
324            if ~isempty(j2_series_Civ2)
325                j2_civ2=j2_series_Civ2(ifield);
326            end
327            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
328                ncfile_out=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i1_civ2,i2_civ2,j1_civ2,j2_civ2);
329            else % displacement
330                ncfile_out=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i2_civ2,[],j2_civ2);
331            end
332        end
333        if ~CheckOverwrite && exist(ncfile_out,'file')
334            disp(['existing output file ' ncfile_out ' already exists, skip to next field'])
335            continue% skip iteration if the mode overwrite is desactivated and the result file already exists
336        end
337    end
338    %% Civ1
339    % if Civ1 computation is requested
340    if isfield (Param.ActionInput,'Civ1')
341        if CheckInputFile
342            disp('civ1 started')
343        end
344        par_civ1=Param.ActionInput.Civ1;
345        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
346            try
347                ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
348                if strcmp(FileExt_A,'.nc')% case of input images in format netcdf
349                    FieldName_A=Param.InputFields.FieldName;
350                    [DataIn,tild,tild,errormsg]=nc2struct(ImageName_A,{FieldName_A});
351                    par_civ1.ImageA=DataIn.(FieldName_A);
352                else % usual image formats for image A
353                    if isempty(FileType_A)
354                        [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A);
355                        FileType_A=FileInfo_A.FileType;
356                        if isempty(Time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video','cine_phantom'})))% case of video input
357                            Time=zeros(FileInfo_A.NumberOfFrames+1,2);
358                            Time(:,2)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate)';
359                            TimeSource='video';
360                            ColorType='truecolor';
361                        end
362                        if ~isempty(FileType_A) && isempty(Time)% Time = index i +0.001 index j by default
363                            MaxIndex_i=max(i2_series_Civ1);
364                            MaxIndex_j=max(j2_series_Civ1);
365                            Time=(1:MaxIndex_i)'*ones(1,MaxIndex_j);
366                            Time=Time+0.001*ones(MaxIndex_i,1)*(1:MaxIndex_j);
367                            Time=[zeros(1,MaxIndex_j);Time];% insert a first line of zeros
368                            Time=[zeros(MaxIndex_i+1,1) Time];% insert a first column of zeros
369                        end
370                    end
371                    if ~exist(ImageName_A,'file')
372                        disp([ImageName_A ' missing'])
373                        continue
374                    end
375                    [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ1(ifield));
376                end
377                ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
378                if strcmp(FileExt_B,'.nc') % case of input images in format netcdf
379                    FieldName_B=Param.InputFields.FieldName;
380                    [DataIn,tild,tild,errormsg]=nc2struct(ImageName_B,{FieldName_B});
381                    par_civ1.ImageB=DataIn.(FieldName_B);
382                else % usual image formats for image B
383                    if isempty(FileType_B)
384                        [FileInfo_B,VideoObject_B]=get_file_info(ImageName_B);
385                        FileType_B=FileInfo_B.FileType;
386                    end
387                    if ~exist(ImageName_B,'file')
388                        disp([ImageName_B ' missing'])
389                        continue
390                    end
391                    [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ1(ifield));
392                end
393            catch ME % display errors in reading input images
394                if ~isempty(ME.message)
395                    disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
396                    continue
397                end
398            end
399            par_civ1.ImageWidth=size(par_civ1.ImageA,2);
400            par_civ1.ImageHeight=size(par_civ1.ImageA,1);
401            list_param=(fieldnames(Param.ActionInput.Civ1))';
402            list_param(strcmp('TestCiv1',list_param))=[];% remove the parameter TestCiv1 from the list
403            Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
404            Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
405            %indicate the values of all the global attributes in the output data
406            Data.Civ1_ImageA=ImageName_A;
407            Data.Civ1_ImageB=ImageName_B;
408            i1=i1_series_Civ1(ifield);
409            i2=i1;
410            if ~isempty(i2_series_Civ1)
411                i2=i2_series_Civ1(ifield);
412            end
413            j1=1;
414            if ~isempty(j1_series_Civ1)
415                j1=j1_series_Civ1(ifield);
416            end
417            j2=j1;
418            if ~isempty(j2_series_Civ1)
419                j2=j2_series_Civ1(ifield);
420            end
421            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
422                Data.Civ1_Time=Time(i2+1,j2+1);% the Time is the Time of the secodn image
423                Data.Civ1_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
424            else
425                Data.Civ1_Time=(Time(i2+1,j2+1)+Time(i1+1,j1+1))/2;% the Time is the Time at the middle of the image pair
426                Data.Civ1_Dt=Time(i2+1,j2+1)-Time(i1+1,j1+1);
427            end
428            for ilist=1:length(list_param)
429                Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
430            end
431            Data.ListGlobalAttribute=[ListGlobalAttribute Civ1_param];
432            Data.CivStage=1;
433        end
434        % set the list of variables
435        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
436        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
437        Data.VarAttribute{1}.Role='coord_x';
438        Data.VarAttribute{2}.Role='coord_y';
439        Data.VarAttribute{3}.Role='vector_x';
440        Data.VarAttribute{4}.Role='vector_y';
441        Data.VarAttribute{5}.Role='warnflag';
442        % case of mask
443        if par_civ1.CheckMask&&~isempty(par_civ1.Mask)
444            if isfield(par_civ1,'NbSlice')
445                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ1.Mask);
446                i1_mask=mod(i1-1,par_civ1.NbSlice)+1;
447                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
448            else
449                maskname=Param.ActionInput.Civ1.Mask;
450            end
451            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
452                par_civ1.Mask=mask; %use mask already opened
453            else
454                try
455                    par_civ1.Mask=imread(maskname);%update the mask, an store it for future use
456                catch ME
457                    if ~isempty(ME.message)
458                        errormsg=['error reading input image: ' ME.message];
459                        disp_uvmat('ERROR',errormsg,checkrun)
460                        return
461                    end
462                end
463                mask=par_civ1.Mask;
464                maskoldname=maskname;
465            end
466        end
467        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
468            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
469            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
470            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
471            for ivol=1:NbSlice
472                % caluclate velocity data (y and v in indices, reverse to y component)
473                [xtable, ytable, utable, vtable, ctable, F, result_conv, errormsg] = civ (par_civ1);
474                if ~isempty(errormsg)
475                    disp_uvmat('ERROR',errormsg,checkrun)
476                    return
477                end
478                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
479                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
480                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
481                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
482                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
483                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
484                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
485            end
486        else %usual PIV
487            % caluclate velocity data (y and v in indices, reverse to y component)
488            [xtable, ytable, utable, vtable, ctable, F, result_conv, errormsg] = civ (par_civ1);
489            if ~isempty(errormsg)
490                disp_uvmat('ERROR',errormsg,checkrun)
491                return
492            end
493            Data.Civ1_X=reshape(xtable,[],1);
494            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
495            Data.Civ1_U=reshape(utable,[],1);
496            Data.Civ1_V=reshape(-vtable,[],1);
497            Data.Civ1_C=reshape(ctable,[],1);
498            Data.Civ1_F=reshape(F,[],1);
499        end
500    else% we use existing Civ1 data
501        if exist('ncfile','var')
502            CivFile=ncfile;
503            [Data,tild,tild,errormsg]=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
504            if ~isempty(errormsg)
505                disp_uvmat('ERROR',errormsg,checkrun)
506                return
507            end
508            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
509        elseif isfield(Param,'Civ1_X')
510            Data.ListGlobalAttribute={};
511            Data.ListVarName={};
512            Data.VarDimName={};
513            Data.Civ1_X=Param.Civ1_X;
514            Data.Civ1_Y=Param.Civ1_Y;
515            Data.Civ1_U=Param.Civ1_U;
516            Data.Civ1_V=Param.Civ1_V;
517            Data.Civ1_FF=Param.Civ1_FF;
518        end
519    end
520   
521    %% Fix1
522    if isfield (Param.ActionInput,'Fix1')
523        disp('fix1 started')
524        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
525            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
526            Data.ListGlobalAttribute(Fix1_attr)=[];
527            for ilist=1:numel(Fix1_attr)
528                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
529            end
530        end
531        list_param=fieldnames(Param.ActionInput.Fix1)';
532        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
533        %indicate the values of all the global attributes in the output data
534        for ilist=1:length(list_param)
535            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
536        end
537        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
538        Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
539        Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
540        nbvar=length(Data.ListVarName);
541        Data.VarAttribute{nbvar}.Role='errorflag';
542        Data.Civ1_FF=int8(fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V));
543        Data.CivStage=2;
544    end
545    %% Patch1
546    if isfield (Param.ActionInput,'Patch1')
547        disp('patch1 started')
548        if check_civx
549            errormsg='Civ Matlab input needed for patch';
550            disp_uvmat('ERROR',errormsg,checkrun)
551            return
552        end
553       
554        % record the processing parameters of Patch1 as global attributes in the result nc file
555        list_param=fieldnames(Param.ActionInput.Patch1)';
556        list_param(strcmp('TestPatch1',list_param))=[];% remove 'TestPatch1' from the list of parameters
557        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Patch1_' before  each parameter name
558        for ilist=1:length(list_param)
559            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
560        end
561        Data.CivStage=3;% record the new state of processing
562        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
563       
564        % list the variables to record
565        nbvar=length(Data.ListVarName);
566        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
567        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
568            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
569        Data.VarAttribute{nbvar+1}.Role='vector_x';
570        Data.VarAttribute{nbvar+2}.Role='vector_y';
571        Data.VarAttribute{nbvar+5}.Role='coord_tps';
572        Data.VarAttribute{nbvar+6}.Role='vector_x';
573        Data.VarAttribute{nbvar+7}.Role='vector_y';
574        Data.Civ1_U_smooth=Data.Civ1_U; % zeros(size(Data.Civ1_X));
575        Data.Civ1_V_smooth=Data.Civ1_V; %zeros(size(Data.Civ1_X));
576        if isfield(Data,'Civ1_FF')
577            ind_good=find(Data.Civ1_FF==0);
578        else
579            ind_good=1:numel(Data.Civ1_X);
580        end
581       
582        % perform Patch calculation using the UVMAT fct 'filter_tps'
583        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
584            filter_tps([Data.Civ1_X(ind_good) Data.Civ1_Y(ind_good)],Data.Civ1_U(ind_good),Data.Civ1_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
585        Data.Civ1_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
586        Data.Civ1_V_smooth(ind_good)=Vres;
587        Data.Civ1_FF(ind_good)=int8(FFres);
588        disp('patch1 performed')
589    end
590   
591    %% Civ2
592    if isfield (Param.ActionInput,'Civ2')
593        disp('civ2 started')
594        par_civ2=Param.ActionInput.Civ2;
595        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
596            par_civ2.ImageA=[];
597            par_civ2.ImageB=[];
598            %             i1_civ2=i1_series_Civ2(ifield);
599            %             i2_civ2=i1_civ2;
600            %             if ~isempty(i2_series_Civ2)
601            %                 i2_civ2=i2_series_Civ2(ifield);
602            %             end
603            %             j1_civ2=1;
604            %             if ~isempty(j1_series_Civ2)
605            %                 j1_civ2=j1_series_Civ2(ifield);
606            %             end
607            %             j2_civ2=i1_civ2;
608            %             if ~isempty(j2_series_Civ2)
609            %                 j2_civ2=j2_series_Civ2(ifield);
610            %             end
611            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
612           
613            if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
614                par_civ2.ImageA=par_civ1.ImageA;
615            else
616                [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
617            end
618            ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
619            if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
620                par_civ2.ImageB=par_civ1.ImageB;
621            else
622                [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
623            end
624            %             if strcmp(Param.ActionInput.ListCompareMode,'PIV')
625            %                 ncfile_out=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i1,i2,j1,j2);
626            %             else % displacement
627            %                 ncfile_out=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i2,[],j2);
628            %             end
629            par_civ2.ImageWidth=FileInfo_A.Width;
630            par_civ2.ImageHeight=FileInfo_A.Height;
631            if isfield(par_civ2,'Grid')% grid points set as input file
632                if ischar(par_civ2.Grid)%read the grid file if the input is a file name
633                    par_civ2.Grid=dlmread(par_civ2.Grid);
634                    par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
635                end
636            else% automatic grid
637                minix=floor(par_civ2.Dx/2)-0.5;
638                maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
639                miniy=floor(par_civ2.Dy/2)-0.5;
640                maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
641                [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
642                par_civ2.Grid(:,1)=reshape(GridX,[],1);
643                par_civ2.Grid(:,2)=reshape(GridY,[],1);
644            end
645        end
646       
647        % get the guess from patch1 or patch2 (case 'CheckCiv3')
648        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
649            if isfield (par_civ2,'CheckCiv3') && par_civ2.CheckCiv3 %get the guess from  patch2
650                SubRange= Data.Civ2_SubRange;
651                NbCentres=Data.Civ2_NbCentres;
652                Coord_tps=Data.Civ2_Coord_tps;
653                U_tps=Data.Civ2_U_tps;
654                V_tps=Data.Civ2_V_tps;
655                CivStage=Data.CivStage;%store the current CivStage
656                Civ1_Dt=Data.Civ2_Dt;
657                Data=[];%reinitialise the result structure Data
658                Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
659                Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
660                Data.Program='civ_series';
661                Data.CivStage=CivStage+1;%update the current civStage after reinitialisation of Data
662                Data.ListVarName={};
663                Data.VarDimName={};
664            else % get the guess from patch1
665                SubRange= Data.Civ1_SubRange;
666                NbCentres=Data.Civ1_NbCentres;
667                Coord_tps=Data.Civ1_Coord_tps;
668                U_tps=Data.Civ1_U_tps;
669                V_tps=Data.Civ1_V_tps;
670                Civ1_Dt=Data.Civ1_Dt;
671                Data.CivStage=4;
672            end
673        else
674            SubRange= par_civ2.Civ1_SubRange;
675            NbCentres=par_civ2.Civ1_NbCentres;
676            Coord_tps=par_civ2.Civ1_Coord_tps;
677            U_tps=par_civ2.Civ1_U_tps;
678            V_tps=par_civ2.Civ1_V_tps;
679            Civ1_Dt=par_civ2.Civ1_Dt;
680            Civ2_Dt=par_civ2.Civ1_Dt;
681            Data.ListVarName={};
682            Data.VarDimName={};
683        end
684        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
685        Shifty=zeros(size(par_civ2.Grid,1),1);
686        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
687        if par_civ2.CheckDeformation
688            DUDX=zeros(size(par_civ2.Grid,1),1);
689            DUDY=zeros(size(par_civ2.Grid,1),1);
690            DVDX=zeros(size(par_civ2.Grid,1),1);
691            DVDY=zeros(size(par_civ2.Grid,1),1);
692        end
693        NbSubDomain=size(SubRange,3);
694        for isub=1:NbSubDomain% for each sub-domain of Patch1
695            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
696            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
697                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
698            if ~isempty(ind_sel)
699                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
700                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
701                nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for each interpolation point (in case of subdomain overlap)
702                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
703                Shiftx(ind_sel)=Shiftx(ind_sel)+EM*U_tps(1:nbvec_sub+3,isub);%velocity shift estimated by tps from civ1
704                Shifty(ind_sel)=Shifty(ind_sel)+EM*V_tps(1:nbvec_sub+3,isub);
705                if par_civ2.CheckDeformation
706                    [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
707                    DUDX(ind_sel)=DUDX(ind_sel)+EMDX*U_tps(1:nbvec_sub+3,isub);
708                    DUDY(ind_sel)=DUDY(ind_sel)+EMDY*U_tps(1:nbvec_sub+3,isub);
709                    DVDX(ind_sel)=DVDX(ind_sel)+EMDX*V_tps(1:nbvec_sub+3,isub);
710                    DVDY(ind_sel)=DVDY(ind_sel)+EMDY*V_tps(1:nbvec_sub+3,isub);
711                end
712            end
713        end
714        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)       
715            if isfield(par_civ2,'NbSlice')
716                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
717                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
718                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
719            else
720                maskname=Param.ActionInput.Civ2.Mask;
721            end
722            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
723                par_civ2.Mask=mask; %use mask already opened
724            else
725                try
726                    par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
727                catch ME
728                    if ~isempty(ME.message)
729                        errormsg=['error reading input image: ' ME.message];
730                        disp_uvmat('ERROR',errormsg,checkrun)
731                        return
732                    end
733                end
734                mask=par_civ2.Mask;
735                maskoldname=maskname;
736            end
737        end
738
739        if CheckInputFile % else Dt given by par_civ2
740            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
741                Civ1_Dt=1;
742                Civ2_Dt=1;
743            else
744                Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
745            end
746        end
747        par_civ2.SearchBoxShift=(Civ2_Dt/Civ1_Dt)*[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
748        % shift the grid points by half the expected shift to provide the correlation box position in image A
749        par_civ2.Grid=[par_civ2.Grid(nbval>=1,1)-par_civ2.SearchBoxShift(:,1)/2 par_civ2.Grid(nbval>=1,2)-par_civ2.SearchBoxShift(:,2)/2];
750        if par_civ2.CheckDeformation
751            par_civ2.DUDX=DUDX(nbval>=1)./nbval(nbval>=1);
752            par_civ2.DUDY=DUDY(nbval>=1)./nbval(nbval>=1);
753            par_civ2.DVDX=DVDX(nbval>=1)./nbval(nbval>=1);
754            par_civ2.DVDY=DVDY(nbval>=1)./nbval(nbval>=1);
755        end
756       
757        % calculate velocity data (y and v in image indices, reverse to y component)
758        [xtable, ytable, utable, vtable, ctable, F,result_conv,errormsg] = civ (par_civ2);
759       
760        list_param=(fieldnames(Param.ActionInput.Civ2))';
761        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
762        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
763        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
764        %indicate the values of all the global attributes in the output data
765        if exist('ImageName_A','var')
766            Data.Civ2_ImageA=ImageName_A;
767            Data.Civ2_ImageB=ImageName_B;
768            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
769                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
770                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
771            else
772                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
773                Data.Civ2_Dt=Civ2_Dt;
774            end
775        end
776        for ilist=1:length(list_param)
777            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
778        end
779        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
780       
781        nbvar=numel(Data.ListVarName);
782        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
783        if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
784            Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_F','Civ2_C'}];%  cell array containing the names of the fields to record
785            Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
786            Data.VarAttribute{nbvar+1}.Role='coord_x';
787            Data.VarAttribute{nbvar+2}.Role='coord_y';
788            Data.VarAttribute{nbvar+3}.Role='vector_x';
789            Data.VarAttribute{nbvar+4}.Role='vector_y';
790            Data.VarAttribute{nbvar+5}.Role='warnflag';
791        end
792        Data.Civ2_X=reshape(xtable,[],1);
793        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
794        Data.Civ2_U=reshape(utable,[],1);
795        Data.Civ2_V=reshape(-vtable,[],1);
796        Data.Civ2_C=reshape(ctable,[],1);
797        Data.Civ2_F=reshape(F,[],1);
798        disp('civ2 performed')
799    elseif ~isfield(Data,'ListVarName') % we start there, using existing Civ2 data
800        if exist('ncfile','var')
801            CivFile=ncfile;
802            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
803            if ~isempty(errormsg)
804                disp_uvmat('ERROR',errormsg,checkrun)
805                return
806            end
807        elseif isfield(Param,'Civ2_X')% use Civ2 data as input in Param (test mode)
808            Data.ListGlobalAttribute={};
809            Data.ListVarName={};
810            Data.VarDimName={};
811            Data.Civ2_X=Param.Civ2_X;
812            Data.Civ2_Y=Param.Civ2_Y;
813            Data.Civ2_U=Param.Civ2_U;
814            Data.Civ2_V=Param.Civ2_V;
815            Data.Civ2_FF=Param.Civ2_FF;
816        end
817    end
818   
819    %% Fix2
820    if isfield (Param.ActionInput,'Fix2')
821        disp('fix2 started')
822        list_param=fieldnames(Param.ActionInput.Fix2)';
823        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
824        %indicate the values of all the global attributes in the output data
825        for ilist=1:length(list_param)
826            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
827        end
828        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
829        %
830        %         ListFixParam=fieldnames(Param.ActionInput.Fix2);
831        %         for ilist=1:length(ListFixParam)
832        %             ParamName=ListFixParam{ilist};
833        %             ListName=['Fix2_' ParamName];
834        %             eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
835        %             eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
836        %         end
837        if check_civx
838            if ~isfield(Data,'fix2')
839                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
840                Data.fix2=1;
841                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
842                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
843            end
844            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
845        else
846            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
847            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
848            nbvar=length(Data.ListVarName);
849            Data.VarAttribute{nbvar}.Role='errorflag';
850            Data.Civ2_FF=double(fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V));
851            Data.CivStage=Data.CivStage+1;
852        end
853    end
854   
855    %% Patch2
856    if isfield (Param.ActionInput,'Patch2')
857        disp('patch2 started')
858        list_param=fieldnames(Param.ActionInput.Patch2)';
859        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
860        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
861        %indicate the values of all the global attributes in the output data
862        for ilist=1:length(list_param)
863            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
864        end
865        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
866       
867        nbvar=length(Data.ListVarName);
868        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
869        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
870            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
871       
872        Data.VarAttribute{nbvar+1}.Role='vector_x';
873        Data.VarAttribute{nbvar+2}.Role='vector_y';
874        Data.VarAttribute{nbvar+5}.Role='coord_tps';
875        Data.VarAttribute{nbvar+6}.Role='vector_x';
876        Data.VarAttribute{nbvar+7}.Role='vector_y';
877        Data.Civ2_U_smooth=Data.Civ2_U;
878        Data.Civ2_V_smooth=Data.Civ2_V;
879        if isfield(Data,'Civ2_FF')
880            ind_good=find(Data.Civ2_FF==0);
881        else
882            ind_good=1:numel(Data.Civ2_X);
883        end
884        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures,Vres,tild,FFres]=...
885            filter_tps([Data.Civ2_X(ind_good) Data.Civ2_Y(ind_good)],Data.Civ2_U(ind_good),Data.Civ2_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
886        Data.Civ2_U_smooth(ind_good)=Ures;
887        Data.Civ2_V_smooth(ind_good)=Vres;
888        Data.Civ2_FF(ind_good)=FFres;
889        Data.CivStage=Data.CivStage+1;
890        disp('patch2 performed')
891    end
892   
893    %% write result in a netcdf file if requested
894    if CheckOutputFile
895        errormsg=struct2nc(ncfile_out,Data);
896        if isempty(errormsg)
897            disp([ncfile_out ' written'])
898            %[success,msg] = fileattrib(ncfile_out ,'+w','g');% done in struct2nc
899        else
900            disp(errormsg)
901        end
902        disp(['ellapsed time ' num2str(toc/60,2) ' minutes'])
903    end
904end
905
906
907% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
908%--------------------------------------------------------------------------
909% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
910%
911% OUTPUT:
912% xtable: set of x coordinates
913% ytable: set of y coordiantes
914% utable: set of u displacements (along x)
915% vtable: set of v displacements (along y)
916% ctable: max image correlation for each vector
917% typevector: set of flags, =1 for good, =0 for NaN vectors
918%
919%INPUT:
920% par_civ: structure of input parameters, with fields:
921%  .ImageA: first image for correlation (matrix)
922%  .ImageB: second image for correlation(matrix)
923%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
924%  .SearchBoxSize:  1,2 vector giving the size of the search box in x and y
925%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
926%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
927%  .ImageWidth: nb of pixels of the image in x
928%  .Dx, Dy: mesh for the PIV calculation
929%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
930%  .Mask: name of a mask file or mask image matrix itself
931%  .MinIma: thresholds for image luminosity
932%  .MaxIma
933%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
934%  .DUDX: matrix of deformation obtained from patch at each grid point
935%  .DUDY
936%  .DVDX:
937%  .DVDY
938
939function [xtable,ytable,utable,vtable,ctable,F,result_conv,errormsg] = civ (par_civ)
940
941%% prepare measurement grid
942if isfield(par_civ,'Grid')% grid points set as input, central positions of the sub-images in image A
943    if ischar(par_civ.Grid)%read the grid file if the input is a file name (grid in x, y image coordinates)
944        par_civ.Grid=dlmread(par_civ.Grid);
945        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
946    end
947    % else par_civ.Grid is already an array, no action here
948else% automatic grid in x, y image coordinates
949    minix=floor(par_civ.Dx/2)-0.5;
950    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
951    miniy=floor(par_civ.Dy/2)-0.5;% first automatic grid point at half the mesh Dy
952    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
953    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
954    par_civ.Grid(:,1)=reshape(GridX,[],1);
955    par_civ.Grid(:,2)=reshape(GridY,[],1);% increases with array index
956end
957nbvec=size(par_civ.Grid,1);
958
959%% prepare correlation and search boxes
960ibx2=floor(par_civ.CorrBoxSize(1)/2);
961iby2=floor(par_civ.CorrBoxSize(2)/2);
962isx2=floor(par_civ.SearchBoxSize(1)/2);
963isy2=floor(par_civ.SearchBoxSize(2)/2);
964shiftx=round(par_civ.SearchBoxShift(:,1));%use the input shift estimate, rounded to the next integer value
965shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
966if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
967    shiftx=shiftx*ones(nbvec,1);
968    shifty=shifty*ones(nbvec,1);
969end
970
971%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
972xtable=round(par_civ.Grid(:,1)+0.5)-0.5;
973ytable=round(par_civ.ImageHeight-par_civ.Grid(:,2)+0.5)-0.5;% y index corresponding to the position in image coordiantes
974utable=shiftx;%zeros(nbvec,1);
975vtable=shifty;%zeros(nbvec,1);
976ctable=zeros(nbvec,1);
977F=zeros(nbvec,1);
978result_conv=[];
979errormsg='';
980
981%% prepare mask
982if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
983    if strcmp(par_civ.Mask,'all')
984        return    % get the grid only, no civ calculation
985    elseif ischar(par_civ.Mask)
986        par_civ.Mask=imread(par_civ.Mask);% read the mask if not allready done
987    end
988end
989check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
990check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
991
992par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
993par_civ.ImageB=sum(double(par_civ.ImageB),3);
994[npy_ima npx_ima]=size(par_civ.ImageA);
995if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
996    errormsg='image pair with unequal size';
997    return
998end
999
1000%% Apply mask
1001% Convention for mask IDEAS TO IMPLEMENT ?
1002% mask >200 : velocity calculated
1003%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
1004% 150>=mask >100: velocity not calculated, nor interpolated
1005%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
1006%  20>=mask: velocity=0
1007checkmask=0;
1008MinA=min(min(par_civ.ImageA));
1009%MinB=min(min(par_civ.ImageB));
1010%check_undefined=false(size(par_civ.ImageA));
1011if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
1012    checkmask=1;
1013    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
1014        errormsg='mask must be an image with the same size as the images';
1015        return
1016    end
1017    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
1018    %     par_civ.ImageA(check_undefined)=0;% put image A to zero (i.e. the min image value) in the undefined  area
1019    %     par_civ.ImageB(check_undefined)=0;% put image B to zero (i.e. the min image value) in the undefined  area
1020end
1021
1022%% compute image correlations: MAINLOOP on velocity vectors
1023corrmax=0;
1024sum_square=1;% default
1025mesh=1;% default
1026CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
1027if CheckDeformation
1028    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
1029    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
1030end
1031
1032if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
1033    for ivec=1:nbvec
1034        iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
1035        jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);%  j index  for the middle of the correlation box in the image A
1036        F(ivec)=0;
1037        subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
1038        subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
1039        subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
1040        subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
1041        image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
1042        image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
1043        check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
1044        check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
1045        check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
1046        check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
1047        image1_crop(check1_y,check1_x)=par_civ.ImageA(subrange1_y(check1_y),subrange1_x(check1_x));%extract a subimage (correlation box) from image A
1048        image2_crop(check2_y,check2_x)=par_civ.ImageB(subrange2_y(check2_y),subrange2_x(check2_x));%extract a larger subimage (search box) from image B
1049        if checkmask
1050            mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
1051            mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
1052            mask1_crop(check1_y,check1_x)=check_undefined(subrange1_y(check1_y),subrange1_x(check1_x));%extract a mask subimage (correlation box) from image A
1053            mask2_crop(check2_y,check2_x)=check_undefined(subrange2_y(check2_y),subrange2_x(check2_x));%extract a mask subimage (search box) from image B
1054            sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
1055            if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
1056                F(ivec)=3; %
1057                utable(ivec)=0;
1058                vtable(ivec)=0;
1059            else
1060                image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
1061                image2_crop=image2_crop.*~mask2_crop;
1062                image1_mean=mean(mean(image1_crop))/(1-sizemask);
1063                image2_mean=mean(mean(image2_crop))/(1-sizemask);
1064            end
1065        else
1066            image1_mean=mean(mean(image1_crop));
1067            image2_mean=mean(mean(image2_crop));
1068        end
1069        %threshold on image minimum
1070        if F(ivec)~=3
1071            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
1072                F(ivec)=3;
1073                %threshold on image maximum
1074            elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
1075                F(ivec)=3;
1076            end
1077            if F(ivec)==3
1078                utable(ivec)=0;
1079                vtable(ivec)=0;
1080            else
1081                %mask
1082                if checkmask
1083                    image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
1084                    image2_crop=(image2_crop-image2_mean).*~mask2_crop;
1085                else
1086                    image1_crop=(image1_crop-image1_mean);
1087                    image2_crop=(image2_crop-image2_mean);
1088                end
1089                %deformation
1090                if CheckDeformation
1091                    xi=(1:mesh:size(image1_crop,2));
1092                    yi=(1:mesh:size(image1_crop,1))';
1093                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
1094                    XIant=XI-par_civ.DUDX(ivec)*XI+par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
1095                    YIant=YI+par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
1096                    image1_crop=interp2(image1_crop,XIant,YIant);
1097                    image1_crop(isnan(image1_crop))=0;
1098                    xi=(1:mesh:size(image2_crop,2));
1099                    yi=(1:mesh:size(image2_crop,1))';
1100                    image2_crop=interp2(image2_crop,xi,yi,'*spline');
1101                    image2_crop(isnan(image2_crop))=0;
1102                end
1103                sum_square=sum(sum(image1_crop.*image1_crop));
1104                %reference: Oliver Pust, PIV: Direct Cross-Correlation
1105                result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
1106                corrmax= max(max(result_conv));
1107                result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
1108                %Find the correlation max, at 255
1109                [y,x] = find(result_conv==255,1);
1110                subimage2_crop=image2_crop(y:y+2*iby2/mesh,x:x+2*ibx2/mesh);%subimage of image 2 corresponding to the optimum displacement of first image
1111                sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
1112                sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
1113                if ~isempty(y) && ~isempty(x)
1114                    try
1115                        if par_civ.CorrSmooth==1
1116                            [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
1117                        elseif par_civ.CorrSmooth==2
1118                            [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
1119                        else
1120                            [vector,F(ivec)] = quadr_fit(result_conv,x,y);
1121                        end
1122                        utable(ivec)=vector(1)*mesh+shiftx(ivec);
1123                        vtable(ivec)=vector(2)*mesh+shifty(ivec);
1124                        xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
1125                        ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
1126                        iref=round(xtable(ivec)+0.5);% nearest image index for the middle of the vector
1127                        jref=round(ytable(ivec)+0.5);
1128                        % eliminate vectors located in the mask
1129                        if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
1130                            utable(ivec)=0;
1131                            vtable(ivec)=0;
1132                            F(ivec)=3;
1133                        end
1134                        ctable(ivec)=corrmax/sum_square;% correlation value
1135                    catch ME
1136                        F(ivec)=3;
1137                        disp(ME.message)
1138                    end
1139                else
1140                    F(ivec)=3;
1141                end
1142            end
1143        end
1144    end
1145end
1146result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
1147
1148%------------------------------------------------------------------------
1149% --- Find the maximum of the correlation function after interpolation
1150% OUPUT:
1151% vector = optimum displacement vector with subpixel correction
1152% F =flag: =0 OK
1153%           =-2 , warning: max too close to the edge of the search box (1 pixel margin)
1154% INPUT:
1155% x,y: position of the maximum correlation at integer values
1156
1157function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
1158%------------------------------------------------------------------------
1159% vector=[0 0]; %default
1160F=0;
1161[npy,npx]=size(result_conv);
1162result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
1163%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ??? Israel Institute of Technology
1164%http://urapiv.wordpress.com
1165peaky = y;
1166if y < npy && y > 1
1167    f0 = log(result_conv(y,x));
1168    f1 = log(result_conv(y-1,x));
1169    f2 = log(result_conv(y+1,x));
1170    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
1171else
1172    F=-2; % warning flag for vector truncated by the limited search box
1173end
1174peakx=x;
1175if x < npx-1 && x > 1
1176    f0 = log(result_conv(y,x));
1177    f1 = log(result_conv(y,x-1));
1178    f2 = log(result_conv(y,x+1));
1179    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
1180else
1181    F=-2; % warning flag for vector truncated by the limited search box
1182end
1183vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1184
1185%------------------------------------------------------------------------
1186% --- Find the maximum of the correlation function after interpolation
1187function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1188%------------------------------------------------------------------------
1189% vector=[0 0]; %default
1190F=-2;
1191peaky=y;
1192peakx=x;
1193result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1194[npy,npx]=size(result_conv);
1195if (x < npx) && (y < npy) && (x > 1) && (y > 1)
1196    F=0;
1197    for i=-1:1
1198        for j=-1:1
1199            %following 15 lines based on
1200            %H. Nobach ??? M. Honkanen (2005)
1201            %Two-dimensional Gaussian regression for sub-pixel displacement
1202            %estimation in particle image velocimetry or particle position
1203            %estimation in particle tracking velocimetry
1204            %Experiments in Fluids (2005) 38: 511???515
1205            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1206            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1207            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1208            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1209            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1210        end
1211    end
1212    c10=(1/6)*sum(sum(c10));
1213    c01=(1/6)*sum(sum(c01));
1214    c11=(1/4)*sum(sum(c11));
1215    c20=(1/6)*sum(sum(c20));
1216    c02=(1/6)*sum(sum(c02));
1217    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1218    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1219    if abs(deltax)<1
1220        peakx=x+deltax;
1221    end
1222    if abs(deltay)<1
1223        peaky=y+deltay;
1224    end
1225end
1226vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1227
1228%------------------------------------------------------------------------
1229% --- Find the maximum of the correlation function after quadratic interpolation
1230function [vector,F] = quadr_fit(result_conv,x,y)
1231[npy,npx]=size(result_conv);
1232if x<4 || y<4 || npx-x<4 ||npy-y <4
1233    F=-2;
1234    vector=[x y];
1235else
1236    F=0;
1237    x_ind=x-4:x+4;
1238    y_ind=y-4:y+4;
1239    x_vec=0.25*(x_ind-x);
1240    y_vec=0.25*(y_ind-y);
1241    [X,Y]=meshgrid(x_vec,y_vec);
1242    coord=[reshape(X,[],1) reshape(Y,[],1)];
1243    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
1244   
1245   
1246    % n=numel(X);
1247    % x=[X Y];
1248    % X=X-0.5;
1249    % Y=Y+0.5;
1250    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
1251    p = polyfitn(coord,result_conv,2);
1252    A(1,1)=2*p.Coefficients(1);
1253    A(1,2)=p.Coefficients(2);
1254    A(2,1)=p.Coefficients(2);
1255    A(2,2)=2*p.Coefficients(4);
1256    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
1257    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
1258    % zg = polyvaln(p,coord);
1259    % figure
1260    % surf(x_vec,y_vec,reshape(zg,9,9))
1261    % hold on
1262    % plot3(X,Y,reshape(result_conv,9,9),'o')
1263    % hold off
1264end
1265
1266%'RUN_FIX': function for fixing velocity fields:
1267%-----------------------------------------------
1268% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
1269%
1270%filename: name of the netcdf file (used as input and output)
1271%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
1272%.vel_type='civ1' or 'civ2';
1273%.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
1274%.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
1275%flagindex: flag specifying which values of vec_f are removed:
1276% if flagindex(1)=1: vec_f=-2 vectors are removed
1277% if flagindex(2)=1: vec_f=3 vectors are removed
1278% if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
1279%iter=1 for civ1 fields and iter=2 for civ2 fields
1280%thresh_vecC: threshold in the image correlation vec_C
1281%flag_mask: =1 mask used to remove vectors (0 else)
1282%maskname: name of the mask image file for fix
1283%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
1284%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
1285%fileref: .nc file name for a reference velocity (='': refrence 0 used)
1286%fieldref: 'civ1','filter1'...feld used in fileref
1287
1288function FF=fix(Param,F,C,U,V,X,Y)
1289FF=zeros(size(F));%default
1290
1291%criterium on warn flags
1292FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
1293FlagVal=[-2 2 3 4];
1294for iflag=1:numel(FlagName)
1295    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
1296        FF=(FF==1| F==FlagVal(iflag));
1297    end
1298end
1299%criterium on correlation values
1300if isfield (Param,'MinCorr')
1301    FF=FF==1 | C<Param.MinCorr;
1302end
1303if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1304    Umod= U.*U+V.*V;
1305    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1306        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
1307    end
1308    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1309        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
1310    end
1311end
1312
1313
1314%------------------------------------------------------------------------
1315% --- determine the list of index pairs of processing file
1316function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1317    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1318%------------------------------------------------------------------------
1319i1_series=i_series;% set of first image indexes
1320i2_series=i_series;
1321j1_series=j_series;%ones(size(i_series));% set of first image numbers
1322j2_series=j_series;%ones(size(i_series));
1323r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1324if ~isempty(r)
1325    mode=['D' r.ind];
1326    ind1=str2num(r.num1);
1327    ind2=str2num(r.num2);
1328else
1329    mode='j1-j2';
1330    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1331    if ~isempty(r)
1332        NomTypeNc='_1ab';
1333    else
1334        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1335        if ~isempty(r)
1336            NomTypeNc='_1AB';
1337        else
1338            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1339            if ~isempty(r)
1340                NomTypeNc='_1_1-2';
1341            end
1342        end
1343    end
1344    if isempty(r)
1345        display('wrong pair mode input option')
1346    else
1347        ind1=stra2num(r.num1);
1348        ind2=stra2num(r.num2);
1349    end
1350end
1351switch mode
1352    case 'Di'
1353        i1_series=i_series-ind1;% set of first image numbers
1354        i2_series=i_series+ind2;
1355        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1356        if isempty(j_series)
1357            NomTypeNc='_1-2';
1358        else
1359            j1_series=j_series;
1360            j2_series=j_series;
1361            NomTypeNc='_1-2_1';
1362        end
1363    case 'Dj'
1364        j1_series=j_series-ind1;
1365        j2_series=j_series+ind2;
1366        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1367        NomTypeNc='_1_1-2';
1368    otherwise %bursts
1369        i1_series=i_series(1,:);% do not sweep the j index
1370        i2_series=i_series(1,:);
1371        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1372        j2_series=ind2*ones(1,size(i_series,2));
1373        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1374end
1375
1376
1377
1378
Note: See TracBrowser for help on using the repository browser.