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

Last change on this file since 1022 was 1020, checked in by sommeria, 6 years ago

mode displacement repaired

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