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

Last change on this file since 1065 was 1065, checked in by sommeria, 5 years ago

extract rdvision made parallel

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