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

Last change on this file since 997 was 997, checked in by sommeria, 7 years ago

ActionInput? button introduced in series, use of parameter file series.xml

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