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

Last change on this file since 1143 was 1143, checked in by sommeria, 22 months ago

new display of false vectors

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