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

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

update_xml simlified, bug on civ_series corrected

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        disp(['time image reading ' num2str(time_input,2) ' s'])
906        disp(['time civ1 ' num2str(time_civ1,2) ' s'])
907        disp(['time patch1 ' num2str(time_patch1,2) ' s'])
908        disp(['time civ2 ' num2str(time_civ2,2) ' s'])
909        disp(['time patch2 ' num2str(time_patch2,2) ' s'])
910        disp(['time other ' num2str((time_total-time_input-time_civ1-time_patch1-time_civ2-time_patch2),2) ' s'])
911    end
912end
913
914
915% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
916%--------------------------------------------------------------------------
917% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
918%
919% OUTPUT:
920% xtable: set of x coordinates
921% ytable: set of y coordiantes
922% utable: set of u displacements (along x)
923% vtable: set of v displacements (along y)
924% ctable: max image correlation for each vector
925% typevector: set of flags, =1 for good, =0 for NaN vectors
926%
927%INPUT:
928% par_civ: structure of input parameters, with fields:
929%  .ImageA: first image for correlation (matrix)
930%  .ImageB: second image for correlation(matrix)
931%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
932%  .SearchBoxSize:  1,2 vector giving the size of the search box in x and y
933%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
934%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
935%  .ImageWidth: nb of pixels of the image in x
936%  .Dx, Dy: mesh for the PIV calculation
937%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
938%  .Mask: name of a mask file or mask image matrix itself
939%  .MinIma: thresholds for image luminosity
940%  .MaxIma
941%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
942%  .DUDX: matrix of deformation obtained from patch at each grid point
943%  .DUDY
944%  .DVDX:
945%  .DVDY
946
947function [xtable,ytable,utable,vtable,ctable,F,result_conv,errormsg] = civ (par_civ)
948
949%% prepare measurement grid
950if isfield(par_civ,'Grid')% grid points set as input, central positions of the sub-images in image A
951    if ischar(par_civ.Grid)%read the grid file if the input is a file name (grid in x, y image coordinates)
952        par_civ.Grid=dlmread(par_civ.Grid);
953        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
954    end
955    % else par_civ.Grid is already an array, no action here
956else% automatic grid in x, y image coordinates
957    minix=floor(par_civ.Dx/2)-0.5;
958    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
959    miniy=floor(par_civ.Dy/2)-0.5;% first automatic grid point at half the mesh Dy
960    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
961    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
962    par_civ.Grid(:,1)=reshape(GridX,[],1);
963    par_civ.Grid(:,2)=reshape(GridY,[],1);% increases with array index
964end
965nbvec=size(par_civ.Grid,1);
966
967%% prepare correlation and search boxes
968ibx2=floor(par_civ.CorrBoxSize(1)/2);
969iby2=floor(par_civ.CorrBoxSize(2)/2);
970isx2=floor(par_civ.SearchBoxSize(1)/2);
971isy2=floor(par_civ.SearchBoxSize(2)/2);
972shiftx=round(par_civ.SearchBoxShift(:,1));%use the input shift estimate, rounded to the next integer value
973shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
974if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
975    shiftx=shiftx*ones(nbvec,1);
976    shifty=shifty*ones(nbvec,1);
977end
978
979%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
980xtable=round(par_civ.Grid(:,1)+0.5)-0.5;
981ytable=round(par_civ.ImageHeight-par_civ.Grid(:,2)+0.5)-0.5;% y index corresponding to the position in image coordiantes
982utable=shiftx;%zeros(nbvec,1);
983vtable=shifty;%zeros(nbvec,1);
984ctable=zeros(nbvec,1);
985F=zeros(nbvec,1);
986result_conv=[];
987errormsg='';
988
989%% prepare mask
990if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
991    if strcmp(par_civ.Mask,'all')
992        return    % get the grid only, no civ calculation
993    elseif ischar(par_civ.Mask)
994        par_civ.Mask=imread(par_civ.Mask);% read the mask if not allready done
995    end
996end
997check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
998check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
999
1000par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
1001par_civ.ImageB=sum(double(par_civ.ImageB),3);
1002[npy_ima npx_ima]=size(par_civ.ImageA);
1003if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
1004    errormsg='image pair with unequal size';
1005    return
1006end
1007
1008%% Apply mask
1009% Convention for mask, IDEAS NOT IMPLEMENTED
1010% mask >200 : velocity calculated
1011%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
1012% 150>=mask >100: velocity not calculated, nor interpolated
1013%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
1014%  20>=mask: velocity=0
1015checkmask=0;
1016MinA=min(min(par_civ.ImageA));
1017%MinB=min(min(par_civ.ImageB));
1018%check_undefined=false(size(par_civ.ImageA));
1019if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
1020    checkmask=1;
1021    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
1022        errormsg='mask must be an image with the same size as the images';
1023        return
1024    end
1025    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
1026end
1027
1028%% compute image correlations: MAINLOOP on velocity vectors
1029corrmax=0;
1030sum_square=1;% default
1031mesh=1;% default
1032CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
1033if CheckDeformation
1034    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
1035    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
1036end
1037
1038if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
1039    for ivec=1:nbvec
1040        iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
1041        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
1042        F(ivec)=0;
1043        subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
1044        subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
1045        subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
1046        subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
1047        image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
1048        image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
1049        check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
1050        check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
1051        check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
1052        check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
1053        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
1054        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
1055        if checkmask
1056            mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
1057            mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
1058            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
1059            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
1060            sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
1061            if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
1062                F(ivec)=1; %
1063                utable(ivec)=NaN;
1064                vtable(ivec)=NaN;
1065            else
1066                image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
1067                image2_crop=image2_crop.*~mask2_crop;
1068                image1_mean=mean(mean(image1_crop))/(1-sizemask);
1069                image2_mean=mean(mean(image2_crop))/(1-sizemask);
1070            end
1071        else
1072            image1_mean=mean(mean(image1_crop));
1073            image2_mean=mean(mean(image2_crop));
1074        end
1075        %threshold on image minimum
1076        if F(ivec)~=1
1077            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
1078                F(ivec)=1;
1079                %threshold on image maximum
1080            elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
1081                F(ivec)=1;
1082            end
1083            if F(ivec)==1
1084                utable(ivec)=NaN;
1085                vtable(ivec)=NaN;
1086            else
1087                %mask
1088                if checkmask
1089                    image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
1090                    image2_crop=(image2_crop-image2_mean).*~mask2_crop;
1091                else
1092                    image1_crop=(image1_crop-image1_mean);
1093                    image2_crop=(image2_crop-image2_mean);
1094                end
1095                %deformation
1096                if CheckDeformation
1097                    xi=(1:mesh:size(image1_crop,2));
1098                    yi=(1:mesh:size(image1_crop,1))';
1099                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
1100                    XIant=XI-par_civ.DUDX(ivec)*XI+par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
1101                    YIant=YI+par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
1102                    image1_crop=interp2(image1_crop,XIant,YIant);
1103                    image1_crop(isnan(image1_crop))=0;
1104                    xi=(1:mesh:size(image2_crop,2));
1105                    yi=(1:mesh:size(image2_crop,1))';
1106                    image2_crop=interp2(image2_crop,xi,yi,'*spline');
1107                    image2_crop(isnan(image2_crop))=0;
1108                end
1109                sum_square=sum(sum(image1_crop.*image1_crop));
1110                %reference: Oliver Pust, PIV: Direct Cross-Correlation
1111                result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
1112                corrmax= max(max(result_conv));
1113                result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
1114                %Find the correlation max, at 255
1115                [y,x] = find(result_conv==255,1);
1116                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
1117                sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
1118                sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
1119                if ~isempty(y) && ~isempty(x)
1120                    try
1121                        if par_civ.CorrSmooth==1
1122                            [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
1123                        elseif par_civ.CorrSmooth==2
1124                            [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
1125                        else
1126                            [vector,F(ivec)] = quadr_fit(result_conv,x,y);
1127                        end
1128                        utable(ivec)=vector(1)*mesh+shiftx(ivec);
1129                        vtable(ivec)=vector(2)*mesh+shifty(ivec);
1130                        xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
1131                        ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
1132                        iref=round(xtable(ivec)+0.5);% nearest image index for the middle of the vector
1133                        jref=round(ytable(ivec)+0.5);
1134                        % eliminate vectors located in the mask
1135                        if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
1136                            utable(ivec)=0;
1137                            vtable(ivec)=0;
1138                            F(ivec)=1;
1139                        end
1140                        ctable(ivec)=corrmax/sum_square;% correlation value
1141                    catch ME
1142                        F(ivec)=1;
1143                        disp(ME.message)
1144                    end
1145                else
1146                    F(ivec)=1;
1147                end
1148            end
1149        end
1150    end
1151end
1152result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
1153
1154%------------------------------------------------------------------------
1155% --- Find the maximum of the correlation function after interpolation
1156% OUPUT:
1157% vector = optimum displacement vector with subpixel correction
1158% F =flag: =0 OK
1159%           =-2 , warning: max too close to the edge of the search box (1 pixel margin)
1160% INPUT:
1161% x,y: position of the maximum correlation at integer values
1162
1163function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
1164%------------------------------------------------------------------------
1165% vector=[0 0]; %default
1166F=0;
1167[npy,npx]=size(result_conv);
1168result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
1169%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ??? Israel Institute of Technology
1170%http://urapiv.wordpress.com
1171peaky = y;
1172if y < npy && y > 1
1173    f0 = log(result_conv(y,x));
1174    f1 = log(result_conv(y-1,x));
1175    f2 = log(result_conv(y+1,x));
1176    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
1177else
1178    F=1; % warning flag for vector truncated by the limited search box
1179end
1180peakx=x;
1181if x < npx-1 && x > 1
1182    f0 = log(result_conv(y,x));
1183    f1 = log(result_conv(y,x-1));
1184    f2 = log(result_conv(y,x+1));
1185    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
1186else
1187    F=1; % warning flag for vector truncated by the limited search box
1188end
1189vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1190
1191%------------------------------------------------------------------------
1192% --- Find the maximum of the correlation function after interpolation
1193function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1194%------------------------------------------------------------------------
1195% vector=[0 0]; %default
1196F=1;
1197peaky=y;
1198peakx=x;
1199result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1200[npy,npx]=size(result_conv);
1201if (x < npx) && (y < npy) && (x > 1) && (y > 1)
1202    F=0;
1203    for i=-1:1
1204        for j=-1:1
1205            %following 15 lines based on
1206            %H. Nobach ??? M. Honkanen (2005)
1207            %Two-dimensional Gaussian regression for sub-pixel displacement
1208            %estimation in particle image velocimetry or particle position
1209            %estimation in particle tracking velocimetry
1210            %Experiments in Fluids (2005) 38: 511???515
1211            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1212            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1213            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1214            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1215            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1216        end
1217    end
1218    c10=(1/6)*sum(sum(c10));
1219    c01=(1/6)*sum(sum(c01));
1220    c11=(1/4)*sum(sum(c11));
1221    c20=(1/6)*sum(sum(c20));
1222    c02=(1/6)*sum(sum(c02));
1223    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1224    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1225    if abs(deltax)<1
1226        peakx=x+deltax;
1227    end
1228    if abs(deltay)<1
1229        peaky=y+deltay;
1230    end
1231end
1232vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1233
1234%------------------------------------------------------------------------
1235% --- Find the maximum of the correlation function after quadratic interpolation
1236function [vector,F] = quadr_fit(result_conv,x,y)
1237[npy,npx]=size(result_conv);
1238if x<4 || y<4 || npx-x<4 ||npy-y <4
1239    F=1;
1240    vector=[x y];
1241else
1242    F=0;
1243    x_ind=x-4:x+4;
1244    y_ind=y-4:y+4;
1245    x_vec=0.25*(x_ind-x);
1246    y_vec=0.25*(y_ind-y);
1247    [X,Y]=meshgrid(x_vec,y_vec);
1248    coord=[reshape(X,[],1) reshape(Y,[],1)];
1249    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
1250   
1251   
1252    % n=numel(X);
1253    % x=[X Y];
1254    % X=X-0.5;
1255    % Y=Y+0.5;
1256    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
1257    p = polyfitn(coord,result_conv,2);
1258    A(1,1)=2*p.Coefficients(1);
1259    A(1,2)=p.Coefficients(2);
1260    A(2,1)=p.Coefficients(2);
1261    A(2,2)=2*p.Coefficients(4);
1262    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
1263    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
1264    % zg = polyvaln(p,coord);
1265    % figure
1266    % surf(x_vec,y_vec,reshape(zg,9,9))
1267    % hold on
1268    % plot3(X,Y,reshape(result_conv,9,9),'o')
1269    % hold off
1270end
1271
1272
1273function FF=detect_false(Param,C,U,V,FFIn)
1274FF=FFIn;%default, good vectors
1275% FF=1, for correlation max at edge, not set in this function
1276% FF=2, for too small correlation
1277% FF=3, for velocity outside bounds
1278% FF=4 for exclusion by difference with the smoothed field, not set in this function
1279
1280if isfield (Param,'MinCorr')
1281     FF(C<Param.MinCorr & FFIn==0)=2;
1282end
1283if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1284    Umod= U.*U+V.*V;
1285    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1286        U2Min=Param.MinVel*Param.MinVel;
1287        FF(Umod<U2Min & FFIn==0)=3;
1288    end
1289    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1290         U2Max=Param.MaxVel*Param.MaxVel;
1291        FF(Umod>U2Max & FFIn==0)=3;
1292    end
1293end
1294
1295%------------------------------------------------------------------------
1296% --- determine the list of index pairs of processing file
1297function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1298    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1299%------------------------------------------------------------------------
1300i1_series=i_series;% set of first image indexes
1301i2_series=i_series;
1302j1_series=j_series;%ones(size(i_series));% set of first image numbers
1303j2_series=j_series;%ones(size(i_series));
1304r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1305if ~isempty(r)
1306    mode=['D' r.ind];
1307    ind1=str2num(r.num1);
1308    ind2=str2num(r.num2);
1309else
1310    mode='j1-j2';
1311    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1312    if ~isempty(r)
1313        NomTypeNc='_1ab';
1314    else
1315        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1316        if ~isempty(r)
1317            NomTypeNc='_1AB';
1318        else
1319            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1320            if ~isempty(r)
1321                NomTypeNc='_1_1-2';
1322            end
1323        end
1324    end
1325    if isempty(r)
1326        display('wrong pair mode input option')
1327    else
1328        ind1=stra2num(r.num1);
1329        ind2=stra2num(r.num2);
1330    end
1331end
1332switch mode
1333    case 'Di'
1334        i1_series=i_series-ind1;% set of first image numbers
1335        i2_series=i_series+ind2;
1336        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1337        if isempty(j_series)
1338            NomTypeNc='_1-2';
1339        else
1340            j1_series=j_series;
1341            j2_series=j_series;
1342            NomTypeNc='_1-2_1';
1343        end
1344    case 'Dj'
1345        j1_series=j_series-ind1;
1346        j2_series=j_series+ind2;
1347        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1348        NomTypeNc='_1_1-2';
1349    otherwise %bursts
1350        i1_series=i_series(1,:);% do not sweep the j index
1351        i2_series=i_series(1,:);
1352        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1353        j2_series=ind2*ones(1,size(i_series,2));
1354        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1355end
1356
1357
1358
1359
Note: See TracBrowser for help on using the repository browser.