source: trunk/src/series/civ_3D.m @ 1115

Last change on this file since 1115 was 1107, checked in by g7moreau, 3 years ago

Update Copyright to 2022

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