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

Last change on this file since 1153 was 1153, checked in by sommeria, 3 months ago

civ3 improved

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