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

Last change on this file since 1147 was 1147, checked in by sommeria, 5 months ago

merge_proj repaired with multimask possibility

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