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

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

bugs repaired, still problems with geometry_calib

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