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

Last change on this file since 1195 was 1195, checked in by sommeria, 5 days ago

format of PIV data made more compact/4

File size: 56.0 KB
Line 
1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   detect_false: put a flag to 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 civ1cc
24%                      .Fix1: parameters for detect_false1
25%                      .Patch1:
26%                      .Civ2: for civ2
27%                      .Fix2:
28%                      .Patch2:
29
30%=======================================================================
31% Copyright 2008-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
32%   http://www.legi.grenoble-inp.fr
33%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.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    if 0==1 %never satisfied but trigger compilation with the appropriate transform functions ('eval' inactive for compilation)
54        ima_rescale
55    end
56    path_series=fileparts(which('series'));
57    addpath(fullfile(path_series,'series'))
58    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
59    % TODO: change from guide to App: modify the input procedure, adapt read_GUI function
60    %App=civ_input_App
61    %Data=civ_input_App(Param);% introduce the civ parameters using the GUI civ_input
62    % if isempty(App)
63    %     Data=Param;% if  civ_input has been cancelled, keep previous parameters
64    % end
65    Data.Program=mfilename;%gives the name of the current function
66    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
67    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
68    Data.NbSlice='off'; %nbre of slices ('off' by default)
69    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
70    Data.FieldName='on';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
71    Data.FieldTransform = 'off';%can use a transform function
72    Data.ProjObject='off';%can use projection object(option 'off'/'on',
73    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
74    Data.OutputDirExt='.civ';%set the output dir extension
75    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)
76    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
77    Data.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
78    if isfield(Data,'ActionInput') && isfield(Data.ActionInput,'PairIndices') && isequal(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
79        Data.IndexRange_j='off';%no j index display in series
80    else
81        Data.IndexRange_j='on';% j index display in series if relevant
82    end
83    return
84end
85
86%% read input parameters from an xml file if input is a file name (batch mode)
87checkrun=1;
88if ischar(Param)
89    Param=xml2struct(Param);% read Param as input file (batch case)
90    checkrun=0;
91end
92
93%% test input
94if ~isfield(Param,'ActionInput')
95    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
96    return
97end
98
99inv_scale_factor=100; % scale factor of displacements for uin16 records in netcdf files (dx expressed in pixels)
100%inv_scale_factor=[];% no scale factor, displacements written as single precision real
101
102%% input files and indexing
103hseries=findobj(allchild(0),'Tag','series');
104RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
105WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
106MaxIndex_i=Param.IndexRange.MaxIndex_i;
107MinIndex_i=Param.IndexRange.MinIndex_i;
108MaxIndex_j=ones(size(MaxIndex_i));MinIndex_j=ones(size(MinIndex_i));
109if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
110    MaxIndex_j=Param.IndexRange.MaxIndex_j;
111    MinIndex_j=Param.IndexRange.MinIndex_j;
112end
113if isfield(Param,'InputTable')
114    [filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
115    iview_B=0;% series index (iview) for the second image series (only non zero for option 'shift' comparing two image series )
116    if Param.ActionInput.CheckCiv1
117        iview_A=1;% usual PIV, the image series is on the first line of the table
118    else % Civ1 has been already stored in a netcdf file input
119        iview_A=2;% the second line is used for the input images
120    end
121    RootPath_A=Param.InputTable{iview_A,1};
122    RootFile_A=Param.InputTable{iview_A,3};
123    SubDir_A=Param.InputTable{iview_A,2};
124    NomType_A=Param.InputTable{iview_A,4};
125    FileExt_A=Param.InputTable{iview_A,5};
126    if iview_B==0
127        iview_B=iview_A;% the second image series is the same as the first
128    end
129    RootPath_B=Param.InputTable{iview_B,1};
130    RootFile_B=Param.InputTable{iview_B,3};
131    SubDir_B=Param.InputTable{iview_B,2};
132    NomType_B=Param.InputTable{iview_B,4};
133    FileExt_B=Param.InputTable{iview_B,5};
134    PairCiv2='';
135   
136    switch Param.ActionInput.ListCompareMode
137        case 'PIV'
138            PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
139            if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
140                PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;%string which determines the civ2 pair
141            end
142            if iview_A==1% if Civ1 is performed
143                [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
144                    find_pair_indices(PairCiv1,i1_series{1},j1_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
145                if ~isempty(PairCiv2)
146                    [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
147                        find_pair_indices(PairCiv2,i1_series{1},j1_series{1},MinIndex_i(1),MaxIndex_i(1),MinIndex_j(1),MaxIndex_j(1));
148                    check_bounds=check_bounds | check_bounds_Civ2;
149                end
150            else% we start from an existing Civ1 file
151                i1_series_Civ1=i1_series{1};
152                i2_series_Civ1=i2_series{1};
153                j1_series_Civ1=j1_series{1};
154                j2_series_Civ1=j2_series{1};
155                NomTypeNc=Param.InputTable{1,4};
156                if ~isempty(PairCiv2)
157                    [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds,NomTypeNc]=...
158                        find_pair_indices(PairCiv2,i1_series{2},j1_series{2},MinIndex_i(2),MaxIndex_i(2),MinIndex_j(2),MaxIndex_j(2));
159                end
160            end
161        case 'displacement'
162            if isfield(Param.ActionInput,'OriginIndex')
163                i1_series_Civ1=Param.ActionInput.OriginIndex*ones(size(i1_series{1}));
164            else
165                i1_series_Civ1=ones(size(i1_series{1}));
166            end
167            i1_series_Civ2=i1_series_Civ1;
168            i2_series_Civ1=i1_series{1};
169            i2_series_Civ2=i1_series{1};
170            j1_series_Civ1=[];% no j index variation for the ref image
171            j1_series_Civ2=[];
172            if isempty(j1_series{1})
173                j2_series_Civ1=ones(size(i1_series_Civ1));
174            else
175                j2_series_Civ1=j1_series{1};% if j index exist
176            end
177            j2_series_Civ2=j2_series_Civ1;
178            NomTypeNc='_1';
179    end
180    %determine frame indices for input with movie or other multiframe input file
181    if isempty(j1_series_Civ1)% simple movie with index i
182        FrameIndex_A_Civ1=i1_series_Civ1;
183        FrameIndex_B_Civ1=i2_series_Civ1;
184        j1_series_Civ1=ones(size(i1_series_Civ1));
185        if strcmp(Param.ActionInput.ListCompareMode,'PIV')
186            j2_series_Civ1=ones(size(i1_series_Civ1));
187        end
188        Check_j_Civ1=false;
189    else % movie for each burst or volume (index j)
190        FrameIndex_A_Civ1=j1_series_Civ1;
191        FrameIndex_B_Civ1=j2_series_Civ1;
192        Check_j_Civ1=true;
193    end
194    if isempty(PairCiv2)
195        FrameIndex_A_Civ2=FrameIndex_A_Civ1;
196        FrameIndex_B_Civ2=FrameIndex_B_Civ1;
197    else
198        if isempty(j1_series_Civ2)
199            FrameIndex_A_Civ2=i1_series_Civ2;
200            FrameIndex_B_Civ2=i2_series_Civ2;
201            j1_series_Civ2=ones(size(i1_series_Civ2));
202            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
203                j2_series_Civ2=ones(size(i1_series_Civ2));
204            end
205            Check_j_Civ2=false;
206        else
207            FrameIndex_A_Civ2=j1_series_Civ2;
208            FrameIndex_B_Civ2=j2_series_Civ2;
209            Check_j_Civ2=true;
210        end
211    end
212    if isempty(i1_series_Civ1)||(~isempty(PairCiv2) && isempty(i1_series_Civ2))
213        disp_uvmat('ERROR','no image pair for civ in the input file index range',checkrun)
214        return
215    end
216end
217
218%% check the first image pair
219if Param.ActionInput.CheckCiv1% Civ1 is performed
220    NbField=numel(i1_series_Civ1);
221elseif Param.ActionInput.CheckCiv2 % Civ2 is performed without Civ1
222    NbField=numel(i1_series_Civ2);
223else
224    NbField=numel(i1_series_Civ1);% no image used (only detect_false or patch) TO CHECK
225end
226
227%% prepare output Data
228OutputDir=[Param.OutputSubDir Param.OutputDirExt];
229ListGlobalAttribute={'Conventions','Program','CivStage'};
230Data.Conventions='uvmat/civdata/compress';% states the conventions used for the description of field variables and attributes
231Data.Program='civ_series';
232if isfield(Param,'UvmatRevision')
233    Data.Program=[Data.Program ', uvmat r' Param.UvmatRevision];
234end
235Data.CivStage=0;%default
236
237%% get timing from the ImaDoc file or input video
238% if iview_A~=0
239XmlFileName=find_imadoc(RootPath_A,SubDir_A);
240Time=[];
241if ~isempty(XmlFileName)
242    XmlData=imadoc2struct(XmlFileName);%read the time from XmlFileName
243    if isfield(XmlData,'Time')
244        Time=XmlData.Time;
245    end
246    if isfield(XmlData,'Camera')
247        if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
248            NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
249            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
250                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
251            end
252        end
253        if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
254            TimeUnit=XmlData.Camera.TimeUnit;
255        end
256    end
257end
258
259%% File relabeling documented by the xml file (e.g. PCO)
260CheckRelabel=isfield(Param.IndexRange,'Relabel' )&& Param.IndexRange.Relabel;%=true for index relabeling (PCO)
261
262%%%%% MAIN LOOP %%%%%%
263maskoldname='';% initiate the mask name
264backgroundoldname='';
265FileType_A='';
266FileType_B='';
267CheckOverwrite=1;%default
268if isfield(Param,'CheckOverwrite')
269    CheckOverwrite=Param.CheckOverwrite;
270end
271for ifield=1:NbField
272    tstart=tic;
273    time_civ1=0;
274    time_patch1=0;
275    time_civ2=0;
276    time_patch2=0;
277    if ~isempty(RUNHandle)% update the waitbar in interactive mode with GUI series  (checkrun=1)
278        update_waitbar(WaitbarHandle,ifield/NbField)
279        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
280            disp('program stopped by user')
281            break
282        end
283    end
284    OutputPath=fullfile(Param.OutputPath,Param.Experiment,Param.Device);
285    if CheckRelabel
286        RootFileOut=index2filename(XmlData.FileSeries,1,1,MaxIndex_j);
287    else
288        RootFileOut=RootFile_A;
289    end
290    if strcmp(Param.ActionInput.ListCompareMode,'PIV')
291        ncfile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
292            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
293    else
294        ncfile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
295            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
296    end
297    ncfile_out=ncfile;% by default
298   
299    if isfield (Param.ActionInput,'Civ2')
300        i1_civ2=i1_series_Civ2(ifield);
301        i2_civ2=i1_civ2;
302        if ~isempty(i2_series_Civ2)
303            i2_civ2=i2_series_Civ2(ifield);
304        end
305        j1_civ2=1;
306        if ~isempty(j1_series_Civ2)
307            j1_civ2=j1_series_Civ2(ifield);
308        end
309        j2_civ2=i1_civ2;
310        if ~isempty(j2_series_Civ2)
311            j2_civ2=j2_series_Civ2(ifield);
312        end
313        if strcmp(Param.ActionInput.ListCompareMode,'PIV')
314            ncfile_out=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i1_civ2,i2_civ2,j1_civ2,j2_civ2);
315        else % displacement
316            ncfile_out=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i2_civ2,[],j2_civ2);
317        end
318    end
319    if ~CheckOverwrite && exist(ncfile_out,'file')
320        disp(['existing output file ' ncfile_out ' already exists, skip to next field'])
321        continue% skip iteration if the mode overwrite is desactivated and the result file already exists
322    end
323    %     end
324    ImageName_A='';ImageName_B='';%default
325    VideoObject_A=[];VideoObject_B=[];
326    Civ_FF=[];%default
327   
328    %% Civ1
329    % if Civ1 computation is requested
330    if Param.ActionInput.CheckCiv1
331        disp('civ1 started')
332        par_civ1=Param.ActionInput.Civ1;% parameters for civ1
333        %if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
334        try
335            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
336                ImageName_A=Param.ActionInput.RefFile;
337                FrameIndex_A=1;
338            elseif CheckRelabel
339                [RootFile,FrameIndex_A]=index2filename(XmlData.FileSeries,i1_series_Civ1(ifield),j1_series_Civ1(ifield),MaxIndex_j);
340                ImageName_A=fullfile(RootPath_A,SubDir_A,RootFile);
341            else
342                ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
343                FrameIndex_A=FrameIndex_A_Civ1(ifield);
344            end
345            if strcmp(FileExt_A,'.nc')% case of input images in format netcdf
346                FieldName_A=Param.InputFields.FieldName;
347                [DataIn,~,~,errormsg]=nc2struct(ImageName_A,{FieldName_A});
348                par_civ1.ImageA=DataIn.(FieldName_A);
349            else % usual image formats for image A
350                if isempty(FileType_A)% open the image object if not already done in case of movie input
351                    [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A);
352                    FileType_A=FileInfo_A.FileType;
353                    if isempty(Time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video','cine_phantom','telopsIR'}), 1))% case of video inputFrameIndex_A
354                        Time=zeros(FileInfo_A.NumberOfFrames+1,2);
355                        Time(:,2)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate)';
356                        if ~isempty(j1_series_Civ1) && j1_series_Civ1~=1
357                            Time=Time';
358                        end
359                    end
360                    if ~isempty(FileType_A) && isempty(Time)% Time = index i +0.001 index j by default
361                        MaxIndex_i=max(i2_series_Civ1);
362                        MaxIndex_j=max(j2_series_Civ1);
363                        Time=(1:MaxIndex_i)'*ones(1,MaxIndex_j);
364                        Time=Time+0.001*ones(MaxIndex_i,1)*(1:MaxIndex_j);
365                        Time=[zeros(1,MaxIndex_j);Time];% insert a first line of zeros
366                        Time=[zeros(MaxIndex_i+1,1) Time];% insert a first column of zeros
367                    end
368                end
369                if isempty(regexp(ImageName_A,'(^http://)|(^https://)', 'once')) && ~exist(ImageName_A,'file')
370                    disp([ImageName_A ' missing'])
371                    continue
372                end
373                tsart_input=tic;
374                [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A);
375                time_input=toc(tsart_input);
376            end
377            if CheckRelabel
378                [RootFile,FrameIndex_B]=index2filename(XmlData.FileSeries,i2_series_Civ1(ifield),j2_series_Civ1(ifield),MaxIndex_j);
379                ImageName_B=fullfile(RootPath_B,SubDir_B,RootFile);
380            else
381                ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
382                FrameIndex_B=FrameIndex_B_Civ1(ifield);
383            end
384            if isempty(FileType_B)% determine the image type for the first field
385                [FileInfo_B,VideoObject_B]=get_file_info(ImageName_B);
386                FileType_B=FileInfo_B.FileType;
387            end
388            if isempty(regexp(ImageName_B,'(^http://)|(^https://)', 'once')) && ~exist(ImageName_B,'file')
389                disp([ImageName_B ' missing'])
390                continue
391            end
392            [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B);
393           
394        catch ME % display errors in reading input images
395            if ~isempty(ME.message)
396                disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
397                continue
398            end
399        end
400       
401        % case of background image to subtract
402        if par_civ1.CheckBackground &&~isempty(par_civ1.Background)
403            [RootPath_background,SubDir_background,RootFile_background,~,~,~,~,Ext_background]=fileparts_uvmat(Param.ActionInput.Civ1.Background);
404            if ~isempty(i2_series_Civ1)% case of volume,backgrounds act on different j levels
405                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',j1_series_Civ1(ifield));
406            elseif isfield(par_civ1,'NbSlice')
407                i1_background=mod(i1-1,par_civ1.NbSlice)+1;
408                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',i1_background);
409                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, background index refers to j index
410                    par_civ1.NbSlice_j=par_civ1.NbSlice;
411                end
412            else
413                backgroundname=Param.ActionInput.Civ1.Background;
414            end
415            if strcmp(backgroundoldname,backgroundname)% background exist, not already read in civ1
416                par_civ1.Background=background; %use background already opened
417            else
418                if ~isempty(regexp(backgroundname,'(^http://)|(^https://)', 'once'))|| exist(backgroundname,'file')
419                    try
420                        par_civ1.Background=imread(backgroundname);%update the background, an store it for future use
421                    catch ME
422                        if ~isempty(ME.message)
423                            errormsg=['error reading input image: ' ME.message];
424                            disp_uvmat('ERROR',errormsg,checkrun)
425                            return
426                        end
427                    end
428                else
429                    par_civ1.Background=[];
430                end
431                background=par_civ1.Background;
432                backgroundoldname=backgroundname;
433            end
434            par_civ1.ImageA=par_civ1.ImageA-par_civ1.Background;
435            par_civ1.ImageB=par_civ1.ImageB-par_civ1.Background;
436        end
437       
438        % case of image luminosity rescaling
439        if par_civ1.CheckRescale &&~isempty(par_civ1.Maxtanh)
440            par_civ1.ImageA =par_civ1.Maxtanh*tanh(double(par_civ1.ImageA)/par_civ1.Maxtanh);
441            par_civ1.ImageB=par_civ1.Maxtanh*tanh(double(par_civ1.ImageB)/par_civ1.Maxtanh);
442        end
443       
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       
459        j1=j1_series_Civ1(ifield);
460       
461        j2=j1;
462        if Check_j_Civ1
463            j2=j2_series_Civ1(ifield);
464        end
465        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
466            Data.Civ1_Time=Time(i2+1,j2+1);% the Time is the Time of the second image
467            Data.Civ1_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
468        else
469            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
470            Data.Civ1_Dt=Time(i2+1,j2+1)-Time(i1+1,j1+1);
471        end
472        for ilist=1:length(list_param)
473            Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
474        end
475        Data.ListGlobalAttribute=[ListGlobalAttribute Civ1_param];
476        Data.CivStage=1;
477       
478        % set the list of variables
479        %         Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_FF'};%  cell array containing the names of the fields to record
480        %         Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
481        %         Data.VarAttribute{1}.Role='coord_x';
482        %         Data.VarAttribute{2}.Role='coord_y';
483        %         Data.VarAttribute{3}.Role='vector_x';
484        %         Data.VarAttribute{4}.Role='vector_y';
485        %         Data.VarAttribute{5}.Role='ancillary';
486        %         Data.VarAttribute{6}.Role='errorflag';
487       
488        % case of mask
489        if par_civ1.CheckMask&&~isempty(par_civ1.Mask)
490            [RootPath_mask,SubDir_mask,RootFile_mask,~,~,~,~,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ1.Mask);
491            if Check_j_Civ1
492                j1=j1_series_Civ1(ifield);
493            else
494                j1=[];
495            end
496            if ~isempty(i2_series_Civ1)&& ~isequal(i1_series_Civ1,i2_series_Civ1)% case of volume,masks act on different j levels
497                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',j1);
498            elseif isfield(par_civ1,'NbSlice')
499                i1_mask=mod(i1-1,par_civ1.NbSlice)+1;
500                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
501                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, mask index refers to j index
502                    par_civ1.NbSlice_j=par_civ1.NbSlice;
503                end
504            else
505                maskname=Param.ActionInput.Civ1.Mask;
506            end
507            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
508                par_civ1.Mask=mask; %use mask already opened
509            else
510                if ~isempty(regexp(maskname,'(^http://)|(^https://)', 'once'))|| exist(maskname,'file')
511                    try
512                        par_civ1.Mask=imread(maskname);%update the mask, an store it for future use
513                    catch ME
514                        if ~isempty(ME.message)
515                            errormsg=['error reading input image: ' ME.message];
516                            disp_uvmat('ERROR',errormsg,checkrun)
517                            return
518                        end
519                    end
520                else
521                    par_civ1.Mask=[];
522                    disp_uvmat('ERROR',[maskname ' does not exist'],checkrun);
523                    return
524                end
525                mask=par_civ1.Mask;
526                maskoldname=maskname;
527            end
528        end
529       
530        % case of input grid
531        if par_civ1.CheckGrid &&~isempty(par_civ1.Grid)
532            GridData=nc2struct(Param.ActionInput.Civ1.Grid);
533            par_civ1.Grid=GridData.Grid;
534            par_civ1.CorrBoxSize=GridData.CorrBox;
535        end
536       
537        % caluclate velocity data
538        %   [Data.Civ1_X,Data.Civ1_Y,Data.Civ1_U,Data.Civ1_V,Data.Civ1_C,Data.Civ1_FF, result_conv, errormsg] = civ (par_civ1);
539        [Civ_X,Civ_Y,Civ_U,Civ_V,Civ_C,Civ_FF, result_conv, errormsg] = civ (par_civ1);
540        Civ_X_shifted=Civ_X-0.5+Civ_U/2;% get the exact positions
541        Civ_Y_shifted=Civ_Y-0.5+Civ_V/2;
542        if ~isempty(errormsg)
543            disp_uvmat('ERROR',errormsg,checkrun)
544            return
545        end
546    end
547   
548   
549    %% Fix1
550    if isfield (Param.ActionInput,'Fix1')
551        disp('detect_false1 started')
552        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
553            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
554            Data.ListGlobalAttribute(Fix1_attr)=[];
555            for ilist=1:numel(Fix1_attr)
556                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
557            end
558        end
559        list_param=fieldnames(Param.ActionInput.Fix1)';
560        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
561        %indicate the values of all the global attributes in the output data
562        for ilist=1:length(list_param)
563            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
564        end
565        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
566        % Data.Civ1_FF=uint8(detect_false(Param.ActionInput.Fix1,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V,Data.Civ1_FF));
567        Civ_FF=uint8(detect_false(Param.ActionInput.Fix1,Civ_C,Civ_U,Civ_V,Civ_FF));
568        Data.CivStage=2;
569    end
570    %% Patch1
571    if Param.ActionInput.CheckPatch1 && isfield (Param.ActionInput,'Patch1')
572        disp('patch1 started')
573        tstart_patch1=tic;
574       
575        % record the processing parameters of Patch1 as global attributes in the result nc file
576        list_param=fieldnames(Param.ActionInput.Patch1)';
577        list_param(strcmp('TestPatch1',list_param))=[];% remove 'TestPatch1' from the list of parameters
578        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Patch1_' before  each parameter name
579        for ilist=1:length(list_param)
580            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
581        end
582        Data.CivStage=3;% record the new state of processing
583        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
584       
585        % list the variables to record
586        %         nbvar=length(Data.ListVarName);
587        %         Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
588        %         Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
589        %             {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
590        %         Data.VarAttribute{nbvar+1}.Role='vector_x';
591        %         Data.VarAttribute{nbvar+2}.Role='vector_y';
592        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
593        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
594        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
595        %Data.Civ1_U_smooth=Data.Civ1_U; % zeros(size(Data.Civ1_X));
596        %Data.Civ1_V_smooth=Data.Civ1_V; %zeros(size(Data.Civ1_X));
597        %         if isfield(Data,'Civ1_FF')
598        if isempty(Civ_FF)
599            ind_good=1:numel(Civ_X);
600        else
601            ind_good=find(Civ_FF==0);
602        end
603        if isempty(ind_good)
604            disp_uvmat('ERROR','all vectors of civ1 are bad, check input parameters' ,checkrun)
605            return
606        end
607       
608        % perform Patch calculation using the UVMAT fct 'filter_tps'
609        [SubRange,NbCentres,Coord_tps,U_tps,V_tps,~,Ures, Vres,~,FFres]=...
610            filter_tps([Civ_X_shifted(ind_good),Civ_Y_shifted(ind_good)],Civ_U(ind_good),Civ_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
611        Civ_U_smooth=Civ_U;% false vectors kept unchanged
612        Civ_V_smooth=Civ_V;
613        Civ_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
614        Civ_V_smooth(ind_good)=Vres;
615        Civ_FF(ind_good)=uint8(4*FFres);%set FF to value =4 for vectors eliminated by filter_tps
616        time_patch1=toc(tstart_patch1);
617        disp('patch1 performed')
618    end
619   
620    %% Civ2
621    if isfield (Param.ActionInput,'Civ2')
622        disp('civ2 started')
623        tstart_civ2=tic;
624        par_civ2=Param.ActionInput.Civ2;
625        %         if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
626        par_civ2.ImageA=[];
627        par_civ2.ImageB=[];
628        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
629            ImageName_A_Civ2=Param.ActionInput.RefFile;
630        elseif CheckRelabel
631            [RootFile,FrameIndex_A_2]=index2filename(XmlData.FileSeries,i1_series_Civ2(ifield),j1_series_Civ2(ifield),MaxIndex_j);
632            ImageName_A_Civ2=fullfile(RootPath_A,SubDir_A,RootFile);
633        else
634            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
635            FrameIndex_A_2=FrameIndex_A_Civ2(ifield);
636        end
637        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A,FrameIndex_A_2)
638            par_civ2.ImageA=par_civ1.ImageA;
639        else
640            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_2);
641        end
642        if CheckRelabel
643            [RootFile,FrameIndex_B_2]=index2filename(XmlData.FileSeries,i2_civ2,j2_civ2,MaxIndex_j);
644            ImageName_B_Civ2=fullfile(RootPath_B,SubDir_B,RootFile);
645        else
646            ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
647            FrameIndex_B_2=FrameIndex_B_Civ2(ifield);
648        end
649        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_2,FrameIndex_B)
650            par_civ2.ImageB=par_civ1.ImageB;
651        else
652            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_2);
653        end
654        %  [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A_Civ2);
655        npy_ima=size(par_civ2.ImageA,1);
656        npx_ima=size(par_civ2.ImageA,2);
657        if par_civ2.CheckGrid &&~isempty(par_civ2.Grid) % case of input grid
658            GridData=nc2struct(Param.ActionInput.Civ2.Grid);
659            par_civ2.Grid=GridData.Grid;
660            par_civ2.CorrBoxSize=GridData.CorrBox;
661        else% automatic grid
662            nbinterv_x=floor((npx_ima-1)/par_civ2.Dx);
663            gridlength_x=nbinterv_x*par_civ2.Dx;
664            minix=ceil((npx_ima-gridlength_x)/2);
665            nbinterv_y=floor((npy_ima-1)/par_civ2.Dy);
666            gridlength_y=nbinterv_y*par_civ2.Dy;
667            miniy=ceil((npy_ima-gridlength_y)/2);
668            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:npx_ima-1,miniy:par_civ2.Dy:npy_ima-1);
669            par_civ2.Grid=zeros(numel(GridX),2);
670            par_civ2.Grid(:,1)=reshape(GridX,[],1);
671            par_civ2.Grid(:,2)=reshape(GridY,[],1);% increases with array index
672        end
673       
674        %                 %% user defined image transform
675        %         if ~isempty(transform_fct)
676        %                par_civ2 =transform_fct(par_civ2,Param);
677        %         end
678        %% case of image luminosity rescaling
679        if par_civ2.CheckRescale &&~isempty(par_civ2.Maxtanh)
680            par_civ2.ImageA =par_civ2.Maxtanh*tanh(double(par_civ2.ImageA)/par_civ2.Maxtanh);
681            par_civ2.ImageB=par_civ2.Maxtanh*tanh(double(par_civ2.ImageB)/par_civ2.Maxtanh);
682        end
683       
684        % get the guess from patch1 or patch2 (case 'CheckCiv3')
685        if iview_A==2 && isfield (par_civ2,'CheckCiv3') && strcmp(par_civ2.CheckCiv3,'iterate(civ3)') %get the guess from  patch2% Civ1 data read in a netcdf file
686            [DataIn,~,~,errormsg]=nc2struct(filecell{1,ifield});
687            if ~isempty(errormsg)
688                disp(errormsg)
689                return
690            end
691            SubRange= DataIn.Civ2_SubRange;
692            NbCentres=DataIn.Civ2_NbCentres;
693            Coord_tps=DataIn.Civ2_Coord_tps;
694            U_tps=DataIn.Civ2_U_tps;
695            V_tps=DataIn.Civ2_V_tps;
696            Civ1_Dt=DataIn.Civ2_Dt;
697            Data=[];%reinitialise the result structure Data
698            Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
699            Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
700            Data.Program='civ_series';
701            Data.ListVarName={};
702            Data.VarDimName={};
703        else % get the guess from patch1
704            %             SubRange= Data.Civ_SubRange;
705            %             NbCentres=Data.Civ_NbCentres;
706            %             Coord_tps=Data.Civ_Coord_tps;
707            %             U_tps=Data.Civ_U_tps;
708            %             V_tps=Data.Civ_V_tps;
709            Civ1_Dt=Data.Civ1_Dt;
710        end
711        Data.CivStage=4;
712        Shiftx=zeros(size(par_civ2.Grid,1),1);% initialise the shift expected from civ1 data
713        Shifty=zeros(size(par_civ2.Grid,1),1);
714        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
715        if par_civ2.CheckDeformation
716            DUDX=zeros(size(par_civ2.Grid,1),1);
717            DUDY=zeros(size(par_civ2.Grid,1),1);
718            DVDX=zeros(size(par_civ2.Grid,1),1);
719            DVDY=zeros(size(par_civ2.Grid,1),1);
720        end
721        NbSubDomain=size(SubRange,3);
722        for isub=1:NbSubDomain% for each sub-domain of Patch1
723            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
724            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
725                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
726            if ~isempty(ind_sel)
727                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
728                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
729                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
730                CentreX=(SubRange(1,1,isub)+SubRange(1,2,isub))/2; %x posiion of the subdomain center
731                CentreY=(SubRange(2,1,isub)+SubRange(2,2,isub))/2; %y posiion of the subdomain center
732                xwidth=(SubRange(1,2,isub)-SubRange(1,1,isub))/pi;
733                ywidth=(SubRange(2,2,isub)-SubRange(2,1,isub))/pi;
734                x_dist=(epoints(:,1)-CentreX)/xwidth;
735                y_dist=(epoints(:,2)-CentreY)/ywidth;
736                weight=cos(x_dist).*cos(y_dist);%weighting fct =1 at the rectangle center and 0 at edge
737                nbval(ind_sel)=nbval(ind_sel)+weight;% records the number of values for each interpolation point (in case of subdomain overlap)
738                Shiftx(ind_sel)=Shiftx(ind_sel)+weight.*(EM*U_tps(1:nbvec_sub+3,isub));%velocity shift estimated by tps from civ1
739                Shifty(ind_sel)=Shifty(ind_sel)+weight.*(EM*V_tps(1:nbvec_sub+3,isub));
740                if par_civ2.CheckDeformation
741                    [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
742                    DUDX(ind_sel)=DUDX(ind_sel)+weight.*(EMDX*U_tps(1:nbvec_sub+3,isub));
743                    DUDY(ind_sel)=DUDY(ind_sel)+weight.*(EMDY*U_tps(1:nbvec_sub+3,isub));
744                    DVDX(ind_sel)=DVDX(ind_sel)+weight.*(EMDX*V_tps(1:nbvec_sub+3,isub));
745                    DVDY(ind_sel)=DVDY(ind_sel)+weight.*(EMDY*V_tps(1:nbvec_sub+3,isub));
746                end
747            end
748        end
749        Shiftx(nbval>0)=Shiftx(nbval>0)./nbval(nbval>0);
750        Shifty(nbval>0)=Shifty(nbval>0)./nbval(nbval>0);
751       
752        % introduce mask
753        if par_civ2.CheckMask && ~isempty(par_civ2.Mask)
754            [RootPath_mask,SubDir_mask,RootFile_mask,~,~,~,~,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
755            if ~isempty(i2_series_Civ2) && ~isequal(i1_series_Civ2,i2_series_Civ2) % we do PIV among indices i,  at given indices j (volume scan), mask depends on position j
756                if Check_j_Civ2
757                    j1=j1_series_Civ2(ifield);
758                else
759                    j1=[];
760                end
761                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',j1);
762            elseif isfield(par_civ2,'NbSlice')
763                i1=i1_series_Civ2(ifield);
764                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
765                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
766                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, mask index refers to j index
767                    par_civ2.NbSlice_j=par_civ2.NbSlice;
768                end
769            else
770                maskname=Param.ActionInput.Civ2.Mask;
771            end
772            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
773                par_civ2.Mask=mask; %use mask already opened
774            else
775                if exist(maskname,'file')|| ~isempty(regexp(maskname,'(^http://)|(^https://)', 'once'))
776                    try
777                        par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
778                    catch ME
779                        if ~isempty(ME.message)
780                            errormsg=['error reading input image: ' ME.message];
781                            disp_uvmat('ERROR',errormsg,checkrun)
782                            return
783                        end
784                    end
785                else
786                    par_civ2.Mask=[];
787                    disp_uvmat('ERROR',[maskname ' does not exist'],checkrun);
788                    return
789                end
790                mask=par_civ2.Mask;
791                maskoldname=maskname;
792            end
793        end
794       
795        % case of background image to subtract
796        if par_civ2.CheckBackground &&~isempty(par_civ2.Background)
797            [RootPath_background,SubDir_background,RootFile_background,~,~,~,~,Ext_background]=fileparts_uvmat(Param.ActionInput.Civ1.Background);
798            j1=1;
799            if ~isempty(j1_series_Civ1)
800                j1=j1_series_Civ1(ifield);
801            end
802            if ~isempty(i2_series_Civ1)% case of volume,backgrounds act on different j levels
803                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',j1);
804            elseif isfield(par_civ2,'NbSlice')
805                i1_background=mod(i1-1,par_civ2.NbSlice)+1;
806                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',i1_background);
807                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, background index refers to j index
808                    par_civ2.NbSlice_j=par_civ2.NbSlice;
809                end
810            else
811                backgroundname=Param.ActionInput.Civ1.Background;
812            end
813            if strcmp(backgroundoldname,backgroundname)% background exist, not already read in civ2
814                par_civ2.Background=background; %use background already opened
815            else
816                if ~isempty(regexp(backgroundname,'(^http://)|(^https://)', 'once'))|| exist(backgroundname,'file')
817                    try
818                        par_civ2.Background=imread(backgroundname);%update the background, an store it for future use
819                    catch ME
820                        if ~isempty(ME.message)
821                            errormsg=['error reading input image: ' ME.message];
822                            disp_uvmat('ERROR',errormsg,checkrun)
823                            return
824                        end
825                    end
826                else
827                    par_civ2.Background=[];
828                end
829                background=par_civ2.Background;
830                backgroundoldname=backgroundname;
831            end
832            par_civ2.ImageA=par_civ2.ImageA-par_civ2.Background;
833            par_civ2.ImageB=par_civ2.ImageB-par_civ2.Background;
834        end
835       
836        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
837            Civ1_Dt=1;
838            Civ2_Dt=1;
839        else
840            Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
841        end
842        par_civ2.SearchBoxShift=zeros(size(par_civ2.Grid));
843        par_civ2.SearchBoxShift(:,1)=(Civ2_Dt/Civ1_Dt)*Shiftx;%rescale the shift in case of Dt different for Civ1 and Civ2
844        par_civ2.SearchBoxShift(:,2)=(Civ2_Dt/Civ1_Dt)*Shifty;
845       
846        if par_civ2.CheckDeformation
847            par_civ2.DUDX(nbval>0)=DUDX(nbval>0)./nbval(nbval>0);
848            par_civ2.DUDY(nbval>0)=DUDY(nbval>0)./nbval(nbval>0);
849            par_civ2.DVDX(nbval>0)=DVDX(nbval>0)./nbval(nbval>0);
850            par_civ2.DVDY(nbval>0)=DVDY(nbval>0)./nbval(nbval>0);
851        end
852       
853        % calculate velocity data (y and v in image indices, reverse to y component)
854       
855        [Civ_X,Civ_Y,Civ_U,Civ_V,Civ_C,Civ_FF,~, errormsg] = civ (par_civ2);
856        Civ_X_shifted=Civ_X-0.5+Civ_U/2;% get the exact positions
857        Civ_Y_shifted=Civ_Y-0.5+Civ_V/2;
858        list_param=(fieldnames(Param.ActionInput.Civ2))';
859        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
860        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
861        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
862        %indicate the values of all the global attributes in the output data
863        if exist('ImageName_A','var')
864            Data.Civ2_ImageA=ImageName_A;
865            Data.Civ2_ImageB=ImageName_B;
866            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
867                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
868                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
869            else
870                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
871                Data.Civ2_Dt=Civ2_Dt;
872            end
873        end
874        for ilist=1:length(list_param)
875            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
876        end
877        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
878       
879        %        nbvar=numel(Data.ListVarName);
880        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
881        %         if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
882        %             Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_C','Civ2_FF'}];%  cell array containing the names of the fields to record
883        %             Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
884        %             Data.VarAttribute{nbvar+1}.Role='coord_x';
885        %             Data.VarAttribute{nbvar+2}.Role='coord_y';
886        %             Data.VarAttribute{nbvar+3}.Role='vector_x';
887        %             Data.VarAttribute{nbvar+4}.Role='vector_y';
888        %             Data.VarAttribute{nbvar+5}.Role='ancillary';
889        %             Data.VarAttribute{nbvar+6}.Role='errorflag';
890        %         end
891        disp('civ2 performed')
892        time_civ2=toc(tstart_civ2);
893    elseif Param.ActionInput.CheckFix2 && isfield (Param.ActionInput,'Fix2') % we start there, using existing Civ2 data
894        if exist('ncfile','var')
895            CivFile=ncfile;
896            [Data,~,~,errormsg]=nc2struct(CivFile);%read civ1 and detect_false1 data in the existing netcdf file
897            if ~isempty(errormsg)
898                disp_uvmat('ERROR',errormsg,checkrun)
899                return
900            end
901        end
902    end
903   
904    %% Fix2
905    if (Param.ActionInput.CheckFix2 && isfield (Param.ActionInput,'Fix2'))||(Param.ActionInput.CheckPatch2 && isfield (Param.ActionInput,'Patch2'))%% if Fix2 computation is requested
906        disp('detect_false2 started')
907        list_param=fieldnames(Param.ActionInput.Fix2)';
908        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
909        %indicate the values of all the global attributes in the output data
910        for ilist=1:length(list_param)
911            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
912        end
913        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
914        Civ_FF=uint8(detect_false(Param.ActionInput.Fix2,Civ_C,Civ_U,Civ_V,Civ_FF));
915        Data.CivStage=Data.CivStage+1;
916    end
917   
918    %% Patch2
919    if Param.ActionInput.CheckPatch2 && isfield (Param.ActionInput,'Patch2')% if Patch2 computation is requested
920       
921        disp('patch2 started')
922        tstart_patch2=tic;
923        list_param=fieldnames(Param.ActionInput.Patch2)';
924        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
925        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
926        %indicate the values of all the global attributes in the output data
927        for ilist=1:length(list_param)
928            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
929        end
930        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
931       
932        %  nbvar=length(Data.ListVarName);
933        %         Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
934        %         Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
935        %             {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
936       
937        %         Data.VarAttribute{nbvar+1}.Role='vector_x';
938        %         Data.VarAttribute{nbvar+2}.Role='vector_y';
939        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
940        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
941        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
942       
943        if isempty(Civ_FF)
944            ind_good=1:numel(Civ_X);
945        else
946            ind_good=find(Civ_FF==0);
947        end
948        if isempty(ind_good)
949            disp_uvmat('ERROR','all vectors of civ2 are bad, check input parameters' ,checkrun)
950            return
951        end
952       
953        [Civ_SubRange,Civ_NbCentres,Civ_Coord_tps,Civ_U_tps,Civ_V_tps,~,Ures,Vres,~,FFres]=...
954            filter_tps([Civ_X_shifted(ind_good) Civ_Y_shifted(ind_good)],Civ_U(ind_good),Civ_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
955        Civ_U_smooth=Civ_U;% keep the false vectors unchanged
956        Civ_V_smooth=Civ_V;
957        Civ_U_smooth(ind_good)=Ures;
958        Civ_V_smooth(ind_good)=Vres;
959        Civ_FF(ind_good)=uint8(4*FFres);
960        Data.CivStage=Data.CivStage+1;
961        time_patch2=toc(tstart_patch2);
962        disp('patch2 performed')
963    end
964   
965    %% write result in a netcdf file
966   
967    Data.ListVarName={'X','Y','U','V','C','FF'};%  cell array containing the names of the fields to record
968    Data.VarDimName={'nb_vec','nb_vec','nb_vec','nb_vec','nb_vec','nb_vec'};
969    Data.VarAttribute{1}.Role='coord_x';
970    Data.VarAttribute{2}.Role='coord_y';
971    Data.VarAttribute{3}.Role='vector_x';
972    Data.VarAttribute{3}.scale_factor=1/inv_scale_factor;
973    Data.VarAttribute{4}.Role='vector_y';
974    Data.VarAttribute{4}.scale_factor=1/inv_scale_factor;
975    Data.VarAttribute{5}.Role='ancillary';
976    Data.VarAttribute{5}.scale_factor=1/inv_scale_factor;
977    Data.VarAttribute{6}.Role='errorflag';
978    Data.X=uint16(Civ_X);
979    Data.Y=uint16(Civ_Y);
980    Data.U=int16(inv_scale_factor*Civ_U);
981    Data.V=int16(inv_scale_factor*Civ_V);
982    Data.C=uint8(inv_scale_factor*Civ_C);
983    Data.FF=uint8(Civ_FF);
984    if (Param.ActionInput.CheckPatch1 && ~Param.ActionInput.CheckCiv2) ||Param.ActionInput.CheckPatch2
985        nbvar=6;
986        %     Data.ListVarName=[Data.ListVarName {'U_smooth','V_smooth','SubRange','NbCentres','Coord_tps','U_tps','V_tps'}];
987        %         Data.VarDimName=[Data.VarDimName {'nb_vec','nb_vec',{'nb_coord','nb_bounds','nb_subdomain'},{'nb_subdomain'},...
988        %             {'nb_tps','nb_coord','nb_subdomain'},{'nb_tps','nb_subdomain'},{'nb_tps','nb_subdomain'}}];
989        Data.ListVarName=[Data.ListVarName {'U_smooth','V_smooth'}];
990        Data.VarDimName=[Data.VarDimName {'nb_vec','nb_vec'}];
991        Data.VarAttribute{nbvar+1}.Role='vector_x';
992        Data.VarAttribute{nbvar+1}.scale_factor=1/inv_scale_factor;
993        Data.VarAttribute{nbvar+2}.Role='vector_y';
994        Data.VarAttribute{nbvar+2}.scale_factor=1/inv_scale_factor;
995        Data.U_smooth=int16(inv_scale_factor*Civ_U_smooth);
996        Data.V_smooth=int16(inv_scale_factor*Civ_V_smooth);
997        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
998        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
999        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
1000        %         Data.U_smooth=int16(inv_scale_factor*U_smooth);
1001        %         Data.V_smooth=int16(inv_scale_factor*V_smooth);
1002        %         Data.SubRange=SubRange;
1003        %         Data.NbCentres=NbCentres;
1004        %         Data.Coord_tps=Coord_tps;
1005        %         Data.U_tps=U_tps;
1006        %         Data.V_tps=V_tps;
1007    end
1008    %
1009    %      if ~isempty(inv_scale_factor)
1010    %              Data=compress_data(Data,inv_scale_factor);% compress the data using integers instead of (single precision)floating reals
1011    %      end
1012    errormsg=struct2nc(ncfile_out,Data);
1013    if isempty(errormsg)
1014        disp([ncfile_out ' written'])
1015    else
1016        disp(errormsg)
1017    end
1018    time_total=toc(tstart);
1019    disp(['ellapsed time ' num2str(time_total/60,2) ' minutes'])
1020    disp(['time civ1 ' num2str(time_civ1,2) ' s'])
1021    disp(['time patch1 ' num2str(time_patch1,2) ' s'])
1022    disp(['time civ2 ' num2str(time_civ2,2) ' s'])
1023    disp(['time patch2 ' num2str(time_patch2,2) ' s'])
1024    if exist('time_input','var')
1025        disp(['time image reading ' num2str(time_input,2) ' s'])
1026        disp(['time other ' num2str((time_total-time_input-time_civ1-time_patch1-time_civ2-time_patch2),2) ' s'])
1027    end
1028end
1029
1030
1031
1032%------------------------------------------------------------------------
1033% --- determine the list of index pairs of processing file
1034function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1035    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1036%------------------------------------------------------------------------
1037i1_series=i_series;% set of first image indexes
1038i2_series=i_series;
1039j1_series=j_series;%ones(size(i_series));% set of first image numbers
1040j2_series=j_series;%ones(size(i_series));
1041r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1042if ~isempty(r)
1043    mode=['D' r.ind];
1044    ind1=str2num(r.num1);
1045    ind2=str2num(r.num2);
1046else
1047    mode='j1-j2';
1048    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1049    if ~isempty(r)
1050        NomTypeNc='_1ab';
1051    else
1052        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1053        if ~isempty(r)
1054            NomTypeNc='_1AB';
1055        else
1056            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1057            if ~isempty(r)
1058                NomTypeNc='_1_1-2';
1059            end
1060        end
1061    end
1062    if isempty(r)
1063        display('wrong pair mode input option')
1064    else
1065        ind1=stra2num(r.num1);
1066        ind2=stra2num(r.num2);
1067    end
1068end
1069switch mode
1070    case 'Di'
1071        i1_series=i_series-ind1;% set of first image numbers
1072        i2_series=i_series+ind2;
1073        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1074        if isempty(j_series)
1075            NomTypeNc='_1-2';
1076        else
1077            j1_series=j_series;
1078            j2_series=j_series;
1079            NomTypeNc='_1-2_1';
1080        end
1081    case 'Dj'
1082        j1_series=j_series-ind1;
1083        j2_series=j_series+ind2;
1084        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1085        NomTypeNc='_1_1-2';
1086    otherwise %bursts
1087        i1_series=i_series(1,:);% do not sweep the j index
1088        i2_series=i_series(1,:);
1089        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1090        j2_series=ind2*ones(1,size(i_series,2));
1091        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1092end
1093
1094%------------------------------------------------------------------------
1095% --- set the flag for false vectors
1096function FF=detect_false(Param,C,U,V,FFIn)
1097FF=FFIn;%default, good vectors
1098% FF=1, for correlation max at edge, not set in this function
1099% FF=2, for too small correlation
1100% FF=3, for velocity outside bounds
1101% FF=4 for exclusion by difference with the smoothed field, set by call to function filter_tps
1102
1103if isfield (Param,'MinCorr')
1104     FF(C<Param.MinCorr & FFIn==0)=2;
1105end
1106if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1107    Umod= U.*U+V.*V;
1108    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1109        U2Min=Param.MinVel*Param.MinVel;
1110        FF(Umod<U2Min & FFIn==0)=3;
1111    end
1112    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1113         U2Max=Param.MaxVel*Param.MaxVel;
1114        FF(Umod>U2Max & FFIn==0)=3;
1115    end
1116end
1117
1118% % --- compress the data using integers instead of (single precision)floating reals
1119% function DataOut=compress_data(DataIn,inv_scale_factor)
1120% DataOut=DataIn; %default
1121% DataOut.Conventions= 'uvmat/civdata/compress';
1122% ListVarName=DataIn.ListVarName;
1123% for ilist=1:numel(ListVarName)
1124%     switch ListVarName{ilist}
1125%         case {'Civ1_C','Civ2_C'}
1126%             DataOut.(ListVarName{ilist})=uint8(inv_scale_factor*DataIn.(ListVarName{ilist}));
1127%             DataOut.VarAttribute{ilist}.scale_factor=1/inv_scale_factor;
1128%         case {'Civ1_U','Civ1_V','Civ2_U','Civ2_V','Civ1_U_smooth','Civ1_V_smooth','Civ2_U_smooth','Civ2_V_smooth'}
1129%             DataOut.(ListVarName{ilist})=int16(inv_scale_factor*DataIn.(ListVarName{ilist}));
1130%             DataOut.VarAttribute{ilist}.scale_factor=1/inv_scale_factor;
1131%         case 'Civ1_X'
1132%             DataOut.Civ1_X=uint16(DataIn.Civ1_X);
1133%         case 'Civ1_Y'
1134%             DataOut.Civ1_Y=uint16(DataIn.Civ1_Y);
1135%        case 'Civ2_X'
1136%             DataOut.Civ2_X=uint16(DataIn.Civ2_X);
1137%         case 'Civ2_Y'
1138%             DataOut.Civ2_Y=uint16(DataIn.Civ2_Y);
1139%     end
1140% end
Note: See TracBrowser for help on using the repository browser.