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

Last change on this file since 980 was 977, checked in by g7moreau, 7 years ago
  • Update Copyright 2008-2017 notice
File size: 66.2 KB
Line 
1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   filter_tps: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_series(Param)
8%
9%OUTPUT
10% Data=structure containing the PIV results and information on the processing parameters
11% errormsg=error message char string, default=''
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-2017, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
32%   http://www.legi.grenoble-inp.fr
33%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
34%
35%     This file is part of the toolbox UVMAT.
36%
37%     UVMAT is free software; you can redistribute it and/or modify
38%     it under the terms of the GNU General Public License as published
39%     by the Free Software Foundation; either version 2 of the license,
40%     or (at your option) any later version.
41%
42%     UVMAT is distributed in the hope that it will be useful,
43%     but WITHOUT ANY WARRANTY; without even the implied warranty of
44%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45%     GNU General Public License (see LICENSE.txt) for more details.
46%=======================================================================
47
48function [Data,errormsg,result_conv]= civ_series(Param)
49errormsg='';
50
51%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
52if isstruct(Param) && isequal(Param.Action.RUN,0)% function activated from the GUI series but not RUN
53    path_series=fileparts(which('series'));
54    addpath(fullfile(path_series,'series'))
55    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
56    if isempty(Data)
57        Data=Param;% if  civ_input has been cancelled, keep previous parameters
58    end
59    Data.Program=mfilename;%gives the name of the current function
60    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
61    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
62    if isfield(Data,'ActionInput') && isfield(Data.ActionInput,'PairIndices')&& strcmp(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
63        Data.Desable_j_index='on';% hide the j index in series (set by the pair choice in civ_input)
64    end
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)
67    Data.FieldName='on';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
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
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)
73    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
74    Data.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
75    return
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
84
85%% test input
86if ~isfield(Param,'ActionInput')
87    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
88    return
89end
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)
95
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;
107    end
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
116        end
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
128            end
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
142                end
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
161                end
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;
174                NomTypeNc=Param.InputTable{1,4};
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)
188            FrameIndex_A_Civ2=FrameIndex_A_Civ1;
189            FrameIndex_B_Civ2=FrameIndex_B_Civ1;
190        else
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
200        end
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)
203            return
204        end
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);
257        else
258            NbField=numel(i1_series_Civ1);% no image used (only fix or patch) TO CHECK
259        end
260    catch ME
261        if ~isempty(ME.message)
262            disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
263            return
264        end
265    end
266   
267   
268    %% Output directory
269    OutputDir='';
270    if CheckOutputFile
271        OutputDir=[Param.OutputSubDir Param.OutputDirExt];
272    end
273end
274
275%% prepare output Data
276ListGlobalAttribute={'Conventions','Program','CivStage'};
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
282%% get timing from the ImaDoc file or input video
283if iview_A~=0
284    XmlFileName=find_imadoc(RootPath_A,SubDir_A,RootFile_A,FileExt_A);
285    Time=[];
286    if ~isempty(XmlFileName)
287        XmlData=imadoc2struct(XmlFileName);
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
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
320   
321    if length(FileInfo_A) >1 %case of image with multiple frames
322        nbfield=length(FileInfo_A);
323        nbfield_j=1;
324    end
325end
326
327%%%%% MAIN LOOP %%%%%%
328maskname='';% initiate the mask name
329tic;
330CheckOverwrite=1;%default
331if isfield(Param,'CheckOverwrite')
332    CheckOverwrite=Param.CheckOverwrite;
333end
334for ifield=1:NbField
335    if ~isempty(RUNHandle)% update the waitbar in interactive mode with GUI series  (checkrun=1)
336        update_waitbar(WaitbarHandle,ifield/NbField)
337        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
338            disp('program stopped by user')
339            break
340        end
341    end
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
359        end
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
380        end
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
385    end
386    %% Civ1
387    % if Civ1 computation is requested
388    if isfield (Param.ActionInput,'Civ1')
389        if CheckInputFile
390        disp('civ1 started')
391        end
392        par_civ1=Param.ActionInput.Civ1;
393        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
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
416            end
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);
430            end
431            j1=1;
432            if ~isempty(j1_series_Civ1)
433                j1=j1_series_Civ1(ifield);
434            end
435            j2=j1;
436            if ~isempty(j2_series_Civ1)
437                j2=j2_series_Civ1(ifield);
438            end
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
444            Data.Civ1_Dt=Time(i2+1,j2+1)-Time(i1+1,j1+1);
445            end
446            for ilist=1:length(list_param)
447                Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
448            end
449            Data.ListGlobalAttribute=[ListGlobalAttribute Civ1_param];
450            Data.CivStage=1;
451        end
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';
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
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
473                mask=par_civ1.Mask;
474                maskname=par_civ1.Mask;
475            end
476        end
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)
483                [xtable, ytable, utable, vtable, ctable, F, result_conv, errormsg] = civ (par_civ1);
484                if ~isempty(errormsg)
485                    disp_uvmat('ERROR',errormsg,checkrun)
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)
498            [xtable, ytable, utable, vtable, ctable, F, result_conv, errormsg] = civ (par_civ1);
499            if ~isempty(errormsg)
500                disp_uvmat('ERROR',errormsg,checkrun)
501                return
502            end
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);
509        end
510    else% we use existing Civ1 data
511        if exist('ncfile','var')
512            CivFile=ncfile;
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
518            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
519        elseif isfield(Param,'Civ1_X')
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;
527            Data.Civ1_FF=Param.Civ1_FF;
528        end
529    end
530   
531    %% Fix1
532    if isfield (Param.ActionInput,'Fix1')
533         disp('fix1 started')
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
540        end
541        list_param=fieldnames(Param.ActionInput.Fix1)';
542        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
543        %indicate the values of all the global attributes in the output data
544        for ilist=1:length(list_param)
545            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
546        end
547        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
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=int8(fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V));
553        Data.CivStage=2;
554    end
555    %% Patch1
556    if isfield (Param.ActionInput,'Patch1')
557        disp('patch1 started')
558        if check_civx
559            errormsg='Civ Matlab input needed for patch';
560            disp_uvmat('ERROR',errormsg,checkrun)
561            return
562        end
563       
564        % record the processing parameters of Patch1 as global attributes in the result nc file
565        list_param=fieldnames(Param.ActionInput.Patch1)';
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
568        for ilist=1:length(list_param)
569            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
570        end
571        Data.CivStage=3;% record the new state of processing
572        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
573       
574        % list the variables to record
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';
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));
586        if isfield(Data,'Civ1_FF')
587            ind_good=find(Data.Civ1_FF==0);
588        else
589            ind_good=1:numel(Data.Civ1_X);
590        end
591       
592        % perform Patch calculation using the UVMAT fct 'filter_tps'
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);
595        Data.Civ1_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
596        Data.Civ1_V_smooth(ind_good)=Vres;
597        Data.Civ1_FF(ind_good)=int8(FFres);
598        disp('patch1 performed')
599    end
600   
601    %% Civ2
602    if isfield (Param.ActionInput,'Civ2')
603        disp('civ2 started')
604        par_civ2=Param.ActionInput.Civ2;
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=[];
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);
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
628            ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
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
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
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
655        end
656       
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;
665                CivStage=Data.CivStage;%store the current CivStage
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';
671                Data.CivStage=CivStage+1;%update the current civStage after reinitialisation of Data
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;
681                Data.CivStage=4;
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;
690            Civ2_Dt=par_civ2.Civ1_Dt;
691            Data.ListVarName={};
692            Data.VarDimName={};
693        end
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)
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
703        NbSubDomain=size(SubRange,3);
704        for isub=1:NbSubDomain% for each sub-domain of Patch1
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) &...
707                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
708            if ~isempty(ind_sel)
709                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
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)
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
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
722            end
723        end
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
732        end
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
738                Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
739            end
740        end
741        par_civ2.SearchBoxShift=(Civ2_Dt/Civ1_Dt)*[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
742        % shift the grid points by half the expected shift to provide the correlation box position in image A
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];
744        if par_civ2.CheckDeformation
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);
749        end
750       
751        % calculate velocity data (y and v in image indices, reverse to y component)
752        [xtable, ytable, utable, vtable, ctable, F,result_conv,errormsg] = civ (par_civ2);
753       
754        list_param=(fieldnames(Param.ActionInput.Civ2))';
755        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
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
758        %indicate the values of all the global attributes in the output data
759        if exist('ImageName_A','var')
760            Data.Civ2_ImageA=ImageName_A;
761            Data.Civ2_ImageB=ImageName_B;
762             if strcmp(Param.ActionInput.ListCompareMode,'displacement')
763                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
764                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
765             else
766            Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
767            Data.Civ2_Dt=Civ2_Dt;
768             end
769        end
770        for ilist=1:length(list_param)
771            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
772        end
773        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
774       
775        nbvar=numel(Data.ListVarName);
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
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);
792        disp('civ2 performed')
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
811    end
812   
813    %% Fix2
814    if isfield (Param.ActionInput,'Fix2')
815        disp('fix2 started')
816        list_param=fieldnames(Param.ActionInput.Fix2)';
817        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
818        %indicate the values of all the global attributes in the output data
819        for ilist=1:length(list_param)
820            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
821        end
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
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);
839        else
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';
844            Data.Civ2_FF=double(fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V));
845            Data.CivStage=Data.CivStage+1;
846        end
847    end
848   
849    %% Patch2
850    if isfield (Param.ActionInput,'Patch2')
851        disp('patch2 started')
852        list_param=fieldnames(Param.ActionInput.Patch2)';
853        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
854        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
855        %indicate the values of all the global attributes in the output data
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       
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';
871        Data.Civ2_U_smooth=Data.Civ2_U;
872        Data.Civ2_V_smooth=Data.Civ2_V;
873        if isfield(Data,'Civ2_FF')
874            ind_good=find(Data.Civ2_FF==0);
875        else
876            ind_good=1:numel(Data.Civ2_X);
877        end
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;
884        disp('patch2 performed')
885    end
886   
887    %% write result in a netcdf file if requested
888    if CheckOutputFile
889        errormsg=struct2nc(ncfile_out,Data);
890        if isempty(errormsg)
891            disp([ncfile_out ' written'])
892            %[success,msg] = fileattrib(ncfile_out ,'+w','g');% done in struct2nc
893        else
894            disp(errormsg)
895        end
896        disp(['ellapsed time ' num2str(toc/60,2) ' minutes'])
897    end
898end
899
900
901% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
902%--------------------------------------------------------------------------
903% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
904%
905% OUTPUT:
906% xtable: set of x coordinates
907% ytable: set of y coordiantes
908% utable: set of u displacements (along x)
909% vtable: set of v displacements (along y)
910% ctable: max image correlation for each vector
911% typevector: set of flags, =1 for good, =0 for NaN vectors
912%
913%INPUT:
914% par_civ: structure of input parameters, with fields:
915%  .ImageA: first image for correlation (matrix)
916%  .ImageB: second image for correlation(matrix)
917%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
918%  .SearchBoxSize:  1,2 vector giving the size of the search box in x and y
919%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
920%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
921%  .ImageWidth: nb of pixels of the image in x
922%  .Dx, Dy: mesh for the PIV calculation
923%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
924%  .Mask: name of a mask file or mask image matrix itself
925%  .MinIma: thresholds for image luminosity
926%  .MaxIma
927%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
928%  .DUDX: matrix of deformation obtained from patch at each grid point
929%  .DUDY
930%  .DVDX:
931%  .DVDY
932
933function [xtable,ytable,utable,vtable,ctable,F,result_conv,errormsg] = civ (par_civ)
934
935%% prepare measurement grid
936if isfield(par_civ,'Grid')% grid points set as input, central positions of the sub-images in image A
937    if ischar(par_civ.Grid)%read the grid file if the input is a file name (grid in x, y image coordinates)
938        par_civ.Grid=dlmread(par_civ.Grid);
939        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
940    end
941    % else par_civ.Grid is already an array, no action here
942else% automatic grid in x, y image coordinates
943    minix=floor(par_civ.Dx/2)-0.5;
944    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
945    miniy=floor(par_civ.Dy/2)-0.5;% first automatic grid point at half the mesh Dy
946    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
947    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
948    par_civ.Grid(:,1)=reshape(GridX,[],1);
949    par_civ.Grid(:,2)=reshape(GridY,[],1);% increases with array index
950end
951nbvec=size(par_civ.Grid,1);
952
953%% prepare correlation and search boxes
954ibx2=floor(par_civ.CorrBoxSize(1)/2);
955iby2=floor(par_civ.CorrBoxSize(2)/2);
956isx2=floor(par_civ.SearchBoxSize(1)/2);
957isy2=floor(par_civ.SearchBoxSize(2)/2);
958shiftx=round(par_civ.SearchBoxShift(:,1));%use the input shift estimate, rounded to the next integer value
959shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
960if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
961    shiftx=shiftx*ones(nbvec,1);
962    shifty=shifty*ones(nbvec,1);
963end
964
965%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
966xtable=round(par_civ.Grid(:,1)+0.5)-0.5;
967ytable=round(par_civ.ImageHeight-par_civ.Grid(:,2)+0.5)-0.5;% y index corresponding to the position in image coordiantes
968utable=shiftx;%zeros(nbvec,1);
969vtable=shifty;%zeros(nbvec,1);
970ctable=zeros(nbvec,1);
971F=zeros(nbvec,1);
972result_conv=[];
973errormsg='';
974
975%% prepare mask
976if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
977    if strcmp(par_civ.Mask,'all')
978        return    % get the grid only, no civ calculation
979    elseif ischar(par_civ.Mask)
980        par_civ.Mask=imread(par_civ.Mask);% read the mask if not allready done
981    end
982end
983check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
984check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
985
986par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
987par_civ.ImageB=sum(double(par_civ.ImageB),3);
988[npy_ima npx_ima]=size(par_civ.ImageA);
989if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
990    errormsg='image pair with unequal size';
991    return
992end
993
994%% Apply mask
995% Convention for mask IDEAS TO IMPLEMENT ?
996% mask >200 : velocity calculated
997%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
998% 150>=mask >100: velocity not calculated, nor interpolated
999%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
1000%  20>=mask: velocity=0
1001checkmask=0;
1002MinA=min(min(par_civ.ImageA));
1003%MinB=min(min(par_civ.ImageB));
1004%check_undefined=false(size(par_civ.ImageA));
1005if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
1006    checkmask=1;
1007    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
1008        errormsg='mask must be an image with the same size as the images';
1009        return
1010    end
1011    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
1012%     par_civ.ImageA(check_undefined)=0;% put image A to zero (i.e. the min image value) in the undefined  area
1013%     par_civ.ImageB(check_undefined)=0;% put image B to zero (i.e. the min image value) in the undefined  area
1014end
1015
1016%% compute image correlations: MAINLOOP on velocity vectors
1017corrmax=0;
1018sum_square=1;% default
1019mesh=1;% default
1020CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
1021if CheckDeformation
1022    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
1023    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
1024end
1025
1026if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
1027    for ivec=1:nbvec
1028        iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
1029        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
1030        F(ivec)=0;
1031        subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
1032        subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
1033        subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
1034        subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
1035        image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
1036        image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
1037        check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
1038        check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
1039        check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
1040        check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
1041        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
1042        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
1043        if checkmask
1044            mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
1045            mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
1046            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
1047            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
1048            sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
1049            if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
1050                F(ivec)=3; %
1051                utable(ivec)=0;
1052                vtable(ivec)=0;
1053            else
1054                image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
1055                image2_crop=image2_crop.*~mask2_crop;
1056                image1_mean=mean(mean(image1_crop))/(1-sizemask);
1057                image2_mean=mean(mean(image2_crop))/(1-sizemask);
1058            end
1059        else
1060            image1_mean=mean(mean(image1_crop));
1061            image2_mean=mean(mean(image2_crop));
1062        end
1063        %threshold on image minimum
1064        if F(ivec)~=3
1065            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
1066                F(ivec)=3;
1067                %threshold on image maximum
1068            elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
1069                F(ivec)=3;
1070            end
1071            if F(ivec)==3
1072                utable(ivec)=0;
1073                vtable(ivec)=0;
1074            else
1075                %mask
1076                if checkmask
1077                    image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
1078                    image2_crop=(image2_crop-image2_mean).*~mask2_crop;
1079                else
1080                    image1_crop=(image1_crop-image1_mean);
1081                    image2_crop=(image2_crop-image2_mean);
1082                end
1083                %deformation
1084                if CheckDeformation
1085                    xi=(1:mesh:size(image1_crop,2));
1086                    yi=(1:mesh:size(image1_crop,1))';
1087                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
1088                    XIant=XI-par_civ.DUDX(ivec)*XI+par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
1089                    YIant=YI+par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
1090                    image1_crop=interp2(image1_crop,XIant,YIant);
1091                    image1_crop(isnan(image1_crop))=0;
1092                    xi=(1:mesh:size(image2_crop,2));
1093                    yi=(1:mesh:size(image2_crop,1))';
1094                    image2_crop=interp2(image2_crop,xi,yi,'*spline');
1095                    image2_crop(isnan(image2_crop))=0;
1096                end
1097                sum_square=sum(sum(image1_crop.*image1_crop));
1098                %reference: Oliver Pust, PIV: Direct Cross-Correlation
1099                result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
1100                corrmax= max(max(result_conv));
1101                result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
1102                %Find the correlation max, at 255
1103                [y,x] = find(result_conv==255,1);
1104                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
1105                sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
1106                sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
1107                if ~isempty(y) && ~isempty(x)
1108                    try
1109                        if par_civ.CorrSmooth==1
1110                            [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
1111                        elseif par_civ.CorrSmooth==2
1112                            [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
1113                        else
1114                            [vector,F(ivec)] = quadr_fit(result_conv,x,y);
1115                        end
1116                        utable(ivec)=vector(1)*mesh+shiftx(ivec);
1117                        vtable(ivec)=vector(2)*mesh+shifty(ivec);
1118                        xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
1119                        ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
1120                        iref=round(xtable(ivec)+0.5);% nearest image index for the middle of the vector
1121                        jref=round(ytable(ivec)+0.5);
1122                        % eliminate vectors located in the mask
1123                        if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
1124                            utable(ivec)=0;
1125                            vtable(ivec)=0;
1126                            F(ivec)=3;
1127                        end
1128                        ctable(ivec)=corrmax/sum_square;% correlation value
1129                    catch ME
1130                        F(ivec)=3;
1131                        disp(ME.message)
1132                    end
1133                else
1134                    F(ivec)=3;
1135                end
1136            end
1137        end
1138    end
1139end
1140result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
1141
1142%------------------------------------------------------------------------
1143% --- Find the maximum of the correlation function after interpolation
1144% OUPUT:
1145% vector = optimum displacement vector with subpixel correction
1146% F =flag: =0 OK
1147%           =-2 , warning: max too close to the edge of the search box (1 pixel margin)
1148% INPUT:
1149% x,y: position of the maximum correlation at integer values
1150
1151function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
1152%------------------------------------------------------------------------
1153% vector=[0 0]; %default
1154F=0;
1155[npy,npx]=size(result_conv);
1156result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
1157%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ᅵ Israel Institute of Technology
1158%http://urapiv.wordpress.com
1159peaky = y;
1160if y < npy && y > 1
1161    f0 = log(result_conv(y,x));
1162    f1 = log(result_conv(y-1,x));
1163    f2 = log(result_conv(y+1,x));
1164    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
1165else
1166    F=-2; % warning flag for vector truncated by the limited search box
1167end
1168peakx=x;
1169if x < npx-1 && x > 1
1170    f0 = log(result_conv(y,x));
1171    f1 = log(result_conv(y,x-1));
1172    f2 = log(result_conv(y,x+1));
1173    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
1174else
1175    F=-2; % warning flag for vector truncated by the limited search box
1176end
1177vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1178
1179%------------------------------------------------------------------------
1180% --- Find the maximum of the correlation function after interpolation
1181function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1182%------------------------------------------------------------------------
1183% vector=[0 0]; %default
1184F=-2;
1185peaky=y;
1186peakx=x;
1187result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1188[npy,npx]=size(result_conv);
1189if (x < npx) && (y < npy) && (x > 1) && (y > 1)
1190    F=0;
1191    for i=-1:1
1192        for j=-1:1
1193            %following 15 lines based on
1194            %H. Nobach ï¿œ M. Honkanen (2005)
1195            %Two-dimensional Gaussian regression for sub-pixel displacement
1196            %estimation in particle image velocimetry or particle position
1197            %estimation in particle tracking velocimetry
1198            %Experiments in Fluids (2005) 38: 511ï¿œ515
1199            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1200            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1201            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1202            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1203            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1204        end
1205    end
1206    c10=(1/6)*sum(sum(c10));
1207    c01=(1/6)*sum(sum(c01));
1208    c11=(1/4)*sum(sum(c11));
1209    c20=(1/6)*sum(sum(c20));
1210    c02=(1/6)*sum(sum(c02));
1211    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1212    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1213    if abs(deltax)<1
1214        peakx=x+deltax;
1215    end
1216    if abs(deltay)<1
1217        peaky=y+deltay;
1218    end
1219end
1220vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1221
1222%------------------------------------------------------------------------
1223% --- Find the maximum of the correlation function after quadratic interpolation
1224function [vector,F] = quadr_fit(result_conv,x,y)
1225[npy,npx]=size(result_conv);
1226if x<4 || y<4 || npx-x<4 ||npy-y <4
1227    F=-2;
1228    vector=[x y];
1229else
1230    F=0;
1231    x_ind=x-4:x+4;
1232    y_ind=y-4:y+4;
1233    x_vec=0.25*(x_ind-x);
1234    y_vec=0.25*(y_ind-y);
1235    [X,Y]=meshgrid(x_vec,y_vec);
1236    coord=[reshape(X,[],1) reshape(Y,[],1)];
1237    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
1238   
1239   
1240    % n=numel(X);
1241    % x=[X Y];
1242    % X=X-0.5;
1243    % Y=Y+0.5;
1244    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
1245    p = polyfitn(coord,result_conv,2);
1246    A(1,1)=2*p.Coefficients(1);
1247    A(1,2)=p.Coefficients(2);
1248    A(2,1)=p.Coefficients(2);
1249    A(2,2)=2*p.Coefficients(4);
1250    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
1251    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
1252    % zg = polyvaln(p,coord);
1253    % figure
1254    % surf(x_vec,y_vec,reshape(zg,9,9))
1255    % hold on
1256    % plot3(X,Y,reshape(result_conv,9,9),'o')
1257    % hold off
1258end
1259
1260%'RUN_FIX': function for fixing velocity fields:
1261%-----------------------------------------------
1262% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
1263%
1264%filename: name of the netcdf file (used as input and output)
1265%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
1266%.vel_type='civ1' or 'civ2';
1267%.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
1268%.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
1269%flagindex: flag specifying which values of vec_f are removed:
1270% if flagindex(1)=1: vec_f=-2 vectors are removed
1271% if flagindex(2)=1: vec_f=3 vectors are removed
1272% if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
1273%iter=1 for civ1 fields and iter=2 for civ2 fields
1274%thresh_vecC: threshold in the image correlation vec_C
1275%flag_mask: =1 mask used to remove vectors (0 else)
1276%maskname: name of the mask image file for fix
1277%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
1278%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
1279%fileref: .nc file name for a reference velocity (='': refrence 0 used)
1280%fieldref: 'civ1','filter1'...feld used in fileref
1281
1282function FF=fix(Param,F,C,U,V,X,Y)
1283FF=zeros(size(F));%default
1284
1285%criterium on warn flags
1286FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
1287FlagVal=[-2 2 3 4];
1288for iflag=1:numel(FlagName)
1289    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
1290        FF=(FF==1| F==FlagVal(iflag));
1291    end
1292end
1293%criterium on correlation values
1294if isfield (Param,'MinCorr')
1295    FF=FF==1 | C<Param.MinCorr;
1296end
1297if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1298    Umod= U.*U+V.*V;
1299    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1300        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
1301    end
1302    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1303        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
1304    end
1305end
1306
1307
1308%------------------------------------------------------------------------
1309% --- determine the list of index pairs of processing file
1310function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1311    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1312%------------------------------------------------------------------------
1313i1_series=i_series;% set of first image indexes
1314i2_series=i_series;
1315j1_series=j_series;%ones(size(i_series));% set of first image numbers
1316j2_series=j_series;%ones(size(i_series));
1317r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1318if ~isempty(r)
1319    mode=['D' r.ind];
1320    ind1=str2num(r.num1);
1321    ind2=str2num(r.num2);
1322else
1323    mode='j1-j2';
1324    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1325    if ~isempty(r)
1326        NomTypeNc='_1ab';
1327    else
1328        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1329        if ~isempty(r)
1330            NomTypeNc='_1AB';
1331        else
1332            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1333            if ~isempty(r)
1334                NomTypeNc='_1_1-2';
1335            end
1336        end
1337    end
1338    if isempty(r)
1339        display('wrong pair mode input option')
1340    else
1341        ind1=stra2num(r.num1);
1342        ind2=stra2num(r.num2);
1343    end
1344end
1345switch mode
1346    case 'Di'
1347        i1_series=i_series-ind1;% set of first image numbers
1348        i2_series=i_series+ind2;
1349        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1350        if isempty(j_series)
1351            NomTypeNc='_1-2';
1352        else
1353            j1_series=j_series;
1354            j2_series=j_series;
1355            NomTypeNc='_1-2_1';
1356        end
1357    case 'Dj'
1358        j1_series=j_series-ind1;
1359        j2_series=j_series+ind2;
1360        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1361        NomTypeNc='_1_1-2';
1362    otherwise %bursts
1363        i1_series=i_series(1,:);% do not sweep the j index
1364        i2_series=i_series(1,:);
1365        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1366        j2_series=ind2*ones(1,size(i_series,2));
1367        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1368end
1369
1370
1371
1372
Note: See TracBrowser for help on using the repository browser.