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

Last change on this file since 1090 was 1090, checked in by sommeria, 3 years ago

system of mirror output path introduced, and series/sliding_average added

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