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

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