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

Last change on this file since 1137 was 1137, checked in by sommeria, 8 months ago

tps improved by a cosine window in each subdomain. Default size of subdomains reduced for faster computation in the civ interface

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