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

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

interp range introduced in set_object

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