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

Last change on this file since 1198 was 1198, checked in by sommeria, 3 days ago

parfor introduced in civ.m

File size: 55.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        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
279            disp('program stopped by user')
280            break
281        end
282    end
283    OutputPath=fullfile(Param.OutputPath,Param.Experiment,Param.Device);
284    if CheckRelabel
285        RootFileOut=index2filename(XmlData.FileSeries,1,1,MaxIndex_j);
286    else
287        RootFileOut=RootFile_A;
288    end
289    if strcmp(Param.ActionInput.ListCompareMode,'PIV')
290        ncfile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
291            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
292    else
293        ncfile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
294            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
295    end
296    ncfile_out=ncfile;% by default
297   
298    if isfield (Param.ActionInput,'Civ2')
299        i1_civ2=i1_series_Civ2(ifield);
300        i2_civ2=i1_civ2;
301        if ~isempty(i2_series_Civ2)
302            i2_civ2=i2_series_Civ2(ifield);
303        end
304        j1_civ2=1;
305        if ~isempty(j1_series_Civ2)
306            j1_civ2=j1_series_Civ2(ifield);
307        end
308        j2_civ2=i1_civ2;
309        if ~isempty(j2_series_Civ2)
310            j2_civ2=j2_series_Civ2(ifield);
311        end
312        if strcmp(Param.ActionInput.ListCompareMode,'PIV')
313            ncfile_out=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i1_civ2,i2_civ2,j1_civ2,j2_civ2);
314        else % displacement
315            ncfile_out=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i2_civ2,[],j2_civ2);
316        end
317    end
318    if ~CheckOverwrite && exist(ncfile_out,'file')
319        disp(['existing output file ' ncfile_out ' already exists, skip to next field'])
320        continue% skip iteration if the mode overwrite is desactivated and the result file already exists
321    end
322    %     end
323    ImageName_A='';ImageName_B='';%default
324    VideoObject_A=[];VideoObject_B=[];
325    Civ_FF=[];%default
326   
327    %% Civ1
328    % if Civ1 computation is requested
329    if Param.ActionInput.CheckCiv1
330        tstart_civ1=tic;
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        time_civ1=toc(tstart_civ1);
547    end
548   
549   
550    %% Fix1
551    if isfield (Param.ActionInput,'Fix1')
552        disp('detect_false1 started')
553        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
554            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
555            Data.ListGlobalAttribute(Fix1_attr)=[];
556            for ilist=1:numel(Fix1_attr)
557                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
558            end
559        end
560        list_param=fieldnames(Param.ActionInput.Fix1)';
561        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
562        %indicate the values of all the global attributes in the output data
563        for ilist=1:length(list_param)
564            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
565        end
566        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
567        % Data.Civ1_FF=uint8(detect_false(Param.ActionInput.Fix1,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V,Data.Civ1_FF));
568        Civ_FF=uint8(detect_false(Param.ActionInput.Fix1,Civ_C,Civ_U,Civ_V,Civ_FF));
569        Data.CivStage=2;
570    end
571    %% Patch1
572    if Param.ActionInput.CheckPatch1 && isfield (Param.ActionInput,'Patch1')
573        disp('patch1 started')
574        tstart_patch1=tic;
575       
576        % record the processing parameters of Patch1 as global attributes in the result nc file
577        list_param=fieldnames(Param.ActionInput.Patch1)';
578        list_param(strcmp('TestPatch1',list_param))=[];% remove 'TestPatch1' from the list of parameters
579        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Patch1_' before  each parameter name
580        for ilist=1:length(list_param)
581            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
582        end
583        Data.CivStage=3;% record the new state of processing
584        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
585       
586        % list the variables to record
587        %         nbvar=length(Data.ListVarName);
588        %         Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
589        %         Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
590        %             {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
591        %         Data.VarAttribute{nbvar+1}.Role='vector_x';
592        %         Data.VarAttribute{nbvar+2}.Role='vector_y';
593        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
594        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
595        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
596        %Data.Civ1_U_smooth=Data.Civ1_U; % zeros(size(Data.Civ1_X));
597        %Data.Civ1_V_smooth=Data.Civ1_V; %zeros(size(Data.Civ1_X));
598        %         if isfield(Data,'Civ1_FF')
599        if isempty(Civ_FF)
600            ind_good=1:numel(Civ_X);
601        else
602            ind_good=find(Civ_FF==0);
603        end
604        if isempty(ind_good)
605            disp_uvmat('ERROR','all vectors of civ1 are bad, check input parameters' ,checkrun)
606            return
607        end
608       
609        % perform Patch calculation using the UVMAT fct 'filter_tps'
610        [SubRange,NbCentres,Coord_tps,U_tps,V_tps,~,Ures, Vres,~,FFres]=...
611            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);
612        Civ_U_smooth=Civ_U;% false vectors kept unchanged
613        Civ_V_smooth=Civ_V;
614        Civ_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
615        Civ_V_smooth(ind_good)=Vres;
616        Civ_FF(ind_good)=uint8(4*FFres);%set FF to value =4 for vectors eliminated by filter_tps
617        time_patch1=toc(tstart_patch1);
618        disp('patch1 performed')
619    end
620   
621    %% Civ2
622    if isfield (Param.ActionInput,'Civ2')
623        disp('civ2 started')
624        tstart_civ2=tic;
625        par_civ2=Param.ActionInput.Civ2;
626        %         if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
627        par_civ2.ImageA=[];
628        par_civ2.ImageB=[];
629        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
630            ImageName_A_Civ2=Param.ActionInput.RefFile;
631        elseif CheckRelabel
632            [RootFile,FrameIndex_A_2]=index2filename(XmlData.FileSeries,i1_series_Civ2(ifield),j1_series_Civ2(ifield),MaxIndex_j);
633            ImageName_A_Civ2=fullfile(RootPath_A,SubDir_A,RootFile);
634        else
635            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
636            FrameIndex_A_2=FrameIndex_A_Civ2(ifield);
637        end
638        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A,FrameIndex_A_2)
639            par_civ2.ImageA=par_civ1.ImageA;
640        else
641            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_2);
642        end
643        if CheckRelabel
644            [RootFile,FrameIndex_B_2]=index2filename(XmlData.FileSeries,i2_civ2,j2_civ2,MaxIndex_j);
645            ImageName_B_Civ2=fullfile(RootPath_B,SubDir_B,RootFile);
646        else
647            ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
648            FrameIndex_B_2=FrameIndex_B_Civ2(ifield);
649        end
650        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_2,FrameIndex_B)
651            par_civ2.ImageB=par_civ1.ImageB;
652        else
653            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_2);
654        end
655        %  [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A_Civ2);
656        npy_ima=size(par_civ2.ImageA,1);
657        npx_ima=size(par_civ2.ImageA,2);
658        if par_civ2.CheckGrid &&~isempty(par_civ2.Grid) % case of input grid
659            GridData=nc2struct(Param.ActionInput.Civ2.Grid);
660            par_civ2.Grid=GridData.Grid;
661            par_civ2.CorrBoxSize=GridData.CorrBox;
662        else% automatic grid
663            nbinterv_x=floor((npx_ima-1)/par_civ2.Dx);
664            gridlength_x=nbinterv_x*par_civ2.Dx;
665            minix=ceil((npx_ima-gridlength_x)/2);
666            nbinterv_y=floor((npy_ima-1)/par_civ2.Dy);
667            gridlength_y=nbinterv_y*par_civ2.Dy;
668            miniy=ceil((npy_ima-gridlength_y)/2);
669            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:npx_ima-1,miniy:par_civ2.Dy:npy_ima-1);
670            par_civ2.Grid=zeros(numel(GridX),2);
671            par_civ2.Grid(:,1)=reshape(GridX,[],1);
672            par_civ2.Grid(:,2)=reshape(GridY,[],1);% increases with array index
673        end
674       
675        %                 %% user defined image transform
676        %         if ~isempty(transform_fct)
677        %                par_civ2 =transform_fct(par_civ2,Param);
678        %         end
679        %% case of image luminosity rescaling
680        if par_civ2.CheckRescale &&~isempty(par_civ2.Maxtanh)
681            par_civ2.ImageA =par_civ2.Maxtanh*tanh(double(par_civ2.ImageA)/par_civ2.Maxtanh);
682            par_civ2.ImageB=par_civ2.Maxtanh*tanh(double(par_civ2.ImageB)/par_civ2.Maxtanh);
683        end
684       
685        % get the guess from patch1 or patch2 (case 'CheckCiv3')
686        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
687            [DataIn,~,~,errormsg]=nc2struct(filecell{1,ifield});
688            if ~isempty(errormsg)
689                disp(errormsg)
690                return
691            end
692            SubRange= DataIn.Civ2_SubRange;
693            NbCentres=DataIn.Civ2_NbCentres;
694            Coord_tps=DataIn.Civ2_Coord_tps;
695            U_tps=DataIn.Civ2_U_tps;
696            V_tps=DataIn.Civ2_V_tps;
697            Civ1_Dt=DataIn.Civ2_Dt;
698            Data=[];%reinitialise the result structure Data
699            Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
700            Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
701            Data.Program='civ_series';
702            Data.ListVarName={};
703            Data.VarDimName={};
704        else % get the guess from patch1
705            %             SubRange= Data.Civ_SubRange;
706            %             NbCentres=Data.Civ_NbCentres;
707            %             Coord_tps=Data.Civ_Coord_tps;
708            %             U_tps=Data.Civ_U_tps;
709            %             V_tps=Data.Civ_V_tps;
710            Civ1_Dt=Data.Civ1_Dt;
711        end
712        Data.CivStage=4;
713        Shiftx=zeros(size(par_civ2.Grid,1),1);% initialise the shift expected from civ1 data
714        Shifty=zeros(size(par_civ2.Grid,1),1);
715        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
716        if par_civ2.CheckDeformation
717            DUDX=zeros(size(par_civ2.Grid,1),1);
718            DUDY=zeros(size(par_civ2.Grid,1),1);
719            DVDX=zeros(size(par_civ2.Grid,1),1);
720            DVDY=zeros(size(par_civ2.Grid,1),1);
721        end
722        NbSubDomain=size(SubRange,3);
723        for isub=1:NbSubDomain% for each sub-domain of Patch1
724            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
725            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
726                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
727            if ~isempty(ind_sel)
728                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
729                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
730                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
731                CentreX=(SubRange(1,1,isub)+SubRange(1,2,isub))/2; %x posiion of the subdomain center
732                CentreY=(SubRange(2,1,isub)+SubRange(2,2,isub))/2; %y posiion of the subdomain center
733                xwidth=(SubRange(1,2,isub)-SubRange(1,1,isub))/pi;
734                ywidth=(SubRange(2,2,isub)-SubRange(2,1,isub))/pi;
735                x_dist=(epoints(:,1)-CentreX)/xwidth;
736                y_dist=(epoints(:,2)-CentreY)/ywidth;
737                weight=cos(x_dist).*cos(y_dist);%weighting fct =1 at the rectangle center and 0 at edge
738                nbval(ind_sel)=nbval(ind_sel)+weight;% records the number of values for each interpolation point (in case of subdomain overlap)
739                Shiftx(ind_sel)=Shiftx(ind_sel)+weight.*(EM*U_tps(1:nbvec_sub+3,isub));%velocity shift estimated by tps from civ1
740                Shifty(ind_sel)=Shifty(ind_sel)+weight.*(EM*V_tps(1:nbvec_sub+3,isub));
741                if par_civ2.CheckDeformation
742                    [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
743                    DUDX(ind_sel)=DUDX(ind_sel)+weight.*(EMDX*U_tps(1:nbvec_sub+3,isub));
744                    DUDY(ind_sel)=DUDY(ind_sel)+weight.*(EMDY*U_tps(1:nbvec_sub+3,isub));
745                    DVDX(ind_sel)=DVDX(ind_sel)+weight.*(EMDX*V_tps(1:nbvec_sub+3,isub));
746                    DVDY(ind_sel)=DVDY(ind_sel)+weight.*(EMDY*V_tps(1:nbvec_sub+3,isub));
747                end
748            end
749        end
750        Shiftx(nbval>0)=Shiftx(nbval>0)./nbval(nbval>0);
751        Shifty(nbval>0)=Shifty(nbval>0)./nbval(nbval>0);
752       
753        % introduce mask
754        if par_civ2.CheckMask && ~isempty(par_civ2.Mask)
755            [RootPath_mask,SubDir_mask,RootFile_mask,~,~,~,~,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
756            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
757                if Check_j_Civ2
758                    j1=j1_series_Civ2(ifield);
759                else
760                    j1=[];
761                end
762                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',j1);
763            elseif isfield(par_civ2,'NbSlice')
764                i1=i1_series_Civ2(ifield);
765                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
766                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
767                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, mask index refers to j index
768                    par_civ2.NbSlice_j=par_civ2.NbSlice;
769                end
770            else
771                maskname=Param.ActionInput.Civ2.Mask;
772            end
773            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
774                par_civ2.Mask=mask; %use mask already opened
775            else
776                if exist(maskname,'file')|| ~isempty(regexp(maskname,'(^http://)|(^https://)', 'once'))
777                    try
778                        par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
779                    catch ME
780                        if ~isempty(ME.message)
781                            errormsg=['error reading input image: ' ME.message];
782                            disp_uvmat('ERROR',errormsg,checkrun)
783                            return
784                        end
785                    end
786                else
787                    par_civ2.Mask=[];
788                    disp_uvmat('ERROR',[maskname ' does not exist'],checkrun);
789                    return
790                end
791                mask=par_civ2.Mask;
792                maskoldname=maskname;
793            end
794        end
795       
796        % case of background image to subtract
797        if par_civ2.CheckBackground &&~isempty(par_civ2.Background)
798            [RootPath_background,SubDir_background,RootFile_background,~,~,~,~,Ext_background]=fileparts_uvmat(Param.ActionInput.Civ1.Background);
799            j1=1;
800            if ~isempty(j1_series_Civ1)
801                j1=j1_series_Civ1(ifield);
802            end
803            if ~isempty(i2_series_Civ1)% case of volume,backgrounds act on different j levels
804                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',j1);
805            elseif isfield(par_civ2,'NbSlice')
806                i1_background=mod(i1-1,par_civ2.NbSlice)+1;
807                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',i1_background);
808                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, background index refers to j index
809                    par_civ2.NbSlice_j=par_civ2.NbSlice;
810                end
811            else
812                backgroundname=Param.ActionInput.Civ1.Background;
813            end
814            if strcmp(backgroundoldname,backgroundname)% background exist, not already read in civ2
815                par_civ2.Background=background; %use background already opened
816            else
817                if ~isempty(regexp(backgroundname,'(^http://)|(^https://)', 'once'))|| exist(backgroundname,'file')
818                    try
819                        par_civ2.Background=imread(backgroundname);%update the background, an store it for future use
820                    catch ME
821                        if ~isempty(ME.message)
822                            errormsg=['error reading input image: ' ME.message];
823                            disp_uvmat('ERROR',errormsg,checkrun)
824                            return
825                        end
826                    end
827                else
828                    par_civ2.Background=[];
829                end
830                background=par_civ2.Background;
831                backgroundoldname=backgroundname;
832            end
833            par_civ2.ImageA=par_civ2.ImageA-par_civ2.Background;
834            par_civ2.ImageB=par_civ2.ImageB-par_civ2.Background;
835        end
836       
837        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
838            Civ1_Dt=1;
839            Civ2_Dt=1;
840        else
841            Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
842        end
843        par_civ2.SearchBoxShift=zeros(size(par_civ2.Grid));
844        par_civ2.SearchBoxShift(:,1)=(Civ2_Dt/Civ1_Dt)*Shiftx;%rescale the shift in case of Dt different for Civ1 and Civ2
845        par_civ2.SearchBoxShift(:,2)=(Civ2_Dt/Civ1_Dt)*Shifty;
846       
847        if par_civ2.CheckDeformation
848            par_civ2.DUDX(nbval>0)=DUDX(nbval>0)./nbval(nbval>0);
849            par_civ2.DUDY(nbval>0)=DUDY(nbval>0)./nbval(nbval>0);
850            par_civ2.DVDX(nbval>0)=DVDX(nbval>0)./nbval(nbval>0);
851            par_civ2.DVDY(nbval>0)=DVDY(nbval>0)./nbval(nbval>0);
852        end
853       
854        % calculate velocity data (y and v in image indices, reverse to y component)
855       
856        [Civ_X,Civ_Y,Civ_U,Civ_V,Civ_C,Civ_FF,~, errormsg] = civ (par_civ2);
857        Civ_X_shifted=Civ_X-0.5+Civ_U/2;% get the exact positions
858        Civ_Y_shifted=Civ_Y-0.5+Civ_V/2;
859        list_param=(fieldnames(Param.ActionInput.Civ2))';
860        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
861        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
862        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
863        %indicate the values of all the global attributes in the output data
864        if exist('ImageName_A','var')
865            Data.Civ2_ImageA=ImageName_A;
866            Data.Civ2_ImageB=ImageName_B;
867            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
868                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
869                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
870            else
871                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
872                Data.Civ2_Dt=Civ2_Dt;
873            end
874        end
875        for ilist=1:length(list_param)
876            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
877        end
878        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
879       
880        %        nbvar=numel(Data.ListVarName);
881        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
882        %         if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
883        %             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
884        %             Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
885        %             Data.VarAttribute{nbvar+1}.Role='coord_x';
886        %             Data.VarAttribute{nbvar+2}.Role='coord_y';
887        %             Data.VarAttribute{nbvar+3}.Role='vector_x';
888        %             Data.VarAttribute{nbvar+4}.Role='vector_y';
889        %             Data.VarAttribute{nbvar+5}.Role='ancillary';
890        %             Data.VarAttribute{nbvar+6}.Role='errorflag';
891        %         end
892        disp('civ2 performed')
893        time_civ2=toc(tstart_civ2);
894    elseif Param.ActionInput.CheckFix2 && isfield (Param.ActionInput,'Fix2') % we start there, using existing Civ2 data
895        if exist('ncfile','var')
896            CivFile=ncfile;
897            [Data,~,~,errormsg]=nc2struct(CivFile);%read civ1 and detect_false1 data in the existing netcdf file
898            if ~isempty(errormsg)
899                disp_uvmat('ERROR',errormsg,checkrun)
900                return
901            end
902        end
903    end
904   
905    %% Fix2
906    if (Param.ActionInput.CheckFix2 && isfield (Param.ActionInput,'Fix2'))||(Param.ActionInput.CheckPatch2 && isfield (Param.ActionInput,'Patch2'))%% if Fix2 computation is requested
907        disp('detect_false2 started')
908        list_param=fieldnames(Param.ActionInput.Fix2)';
909        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
910        %indicate the values of all the global attributes in the output data
911        for ilist=1:length(list_param)
912            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
913        end
914        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
915        Civ_FF=uint8(detect_false(Param.ActionInput.Fix2,Civ_C,Civ_U,Civ_V,Civ_FF));
916        Data.CivStage=Data.CivStage+1;
917    end
918   
919    %% Patch2
920    if Param.ActionInput.CheckPatch2 && isfield (Param.ActionInput,'Patch2')% if Patch2 computation is requested
921       
922        disp('patch2 started')
923        tstart_patch2=tic;
924        list_param=fieldnames(Param.ActionInput.Patch2)';
925        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
926        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
927        %indicate the values of all the global attributes in the output data
928        for ilist=1:length(list_param)
929            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
930        end
931        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
932       
933        %  nbvar=length(Data.ListVarName);
934        %         Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
935        %         Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
936        %             {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
937       
938        %         Data.VarAttribute{nbvar+1}.Role='vector_x';
939        %         Data.VarAttribute{nbvar+2}.Role='vector_y';
940        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
941        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
942        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
943       
944        if isempty(Civ_FF)
945            ind_good=1:numel(Civ_X);
946        else
947            ind_good=find(Civ_FF==0);
948        end
949        if isempty(ind_good)
950            disp_uvmat('ERROR','all vectors of civ2 are bad, check input parameters' ,checkrun)
951            return
952        end
953       
954        [Civ_SubRange,Civ_NbCentres,Civ_Coord_tps,Civ_U_tps,Civ_V_tps,~,Ures,Vres,~,FFres]=...
955            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);
956        Civ_U_smooth=Civ_U;% keep the false vectors unchanged
957        Civ_V_smooth=Civ_V;
958        Civ_U_smooth(ind_good)=Ures;
959        Civ_V_smooth(ind_good)=Vres;
960        Civ_FF(ind_good)=uint8(4*FFres);
961        Data.CivStage=Data.CivStage+1;
962        time_patch2=toc(tstart_patch2);
963        disp('patch2 performed')
964    end
965   
966    %% write result in a netcdf file
967   
968    Data.ListVarName={'X','Y','U','V','C','FF'};%  cell array containing the names of the fields to record
969    Data.VarDimName={'nb_vec','nb_vec','nb_vec','nb_vec','nb_vec','nb_vec'};
970    Data.VarAttribute{1}.Role='coord_x';
971    Data.VarAttribute{2}.Role='coord_y';
972    Data.VarAttribute{3}.Role='vector_x';
973    Data.VarAttribute{3}.scale_factor=1/inv_scale_factor;
974    Data.VarAttribute{4}.Role='vector_y';
975    Data.VarAttribute{4}.scale_factor=1/inv_scale_factor;
976    Data.VarAttribute{5}.Role='ancillary';
977    Data.VarAttribute{5}.scale_factor=1/100;%scla factor for correlation
978    Data.VarAttribute{6}.Role='errorflag';
979    Data.X=uint16(Civ_X);
980    Data.Y=uint16(Civ_Y);
981    Data.U=int16(inv_scale_factor*Civ_U);
982    Data.V=int16(inv_scale_factor*Civ_V);
983    Data.C=uint8(100*Civ_C);
984    Data.FF=uint8(Civ_FF);
985    % add smoothed field if ptch is done
986    if (Param.ActionInput.CheckPatch1 && ~Param.ActionInput.CheckCiv2) ||Param.ActionInput.CheckPatch2
987        nbvar=6;
988        Data.ListVarName=[Data.ListVarName {'U_smooth','V_smooth'}];
989        Data.VarDimName=[Data.VarDimName {'nb_vec','nb_vec'}];
990        Data.VarAttribute{nbvar+1}.Role='vector_x';
991        Data.VarAttribute{nbvar+1}.scale_factor=1/inv_scale_factor;
992        Data.VarAttribute{nbvar+2}.Role='vector_y';
993        Data.VarAttribute{nbvar+2}.scale_factor=1/inv_scale_factor;
994        Data.U_smooth=int16(inv_scale_factor*Civ_U_smooth);
995        Data.V_smooth=int16(inv_scale_factor*Civ_V_smooth);
996    end
997    errormsg=struct2nc(ncfile_out,Data);
998    if isempty(errormsg)
999        disp([ncfile_out ' written'])
1000    else
1001        disp(errormsg)
1002    end
1003    time_total=toc(tstart);
1004    disp(['ellapsed time ' num2str(time_total/60,2) ' minutes'])
1005    disp(['time civ1 ' num2str(time_civ1,2) ' s'])
1006    disp(['time patch1 ' num2str(time_patch1,2) ' s'])
1007    disp(['time civ2 ' num2str(time_civ2,2) ' s'])
1008    disp(['time patch2 ' num2str(time_patch2,2) ' s'])
1009    if exist('time_input','var')
1010        disp(['time image reading ' num2str(time_input,2) ' s'])
1011        disp(['time other ' num2str((time_total-time_input-time_civ1-time_patch1-time_civ2-time_patch2),2) ' s'])
1012    end
1013end
1014
1015
1016
1017%------------------------------------------------------------------------
1018% --- determine the list of index pairs of processing file
1019function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1020    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1021%------------------------------------------------------------------------
1022i1_series=i_series;% set of first image indexes
1023i2_series=i_series;
1024j1_series=j_series;%ones(size(i_series));% set of first image numbers
1025j2_series=j_series;%ones(size(i_series));
1026r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1027if ~isempty(r)
1028    mode=['D' r.ind];
1029    ind1=str2num(r.num1);
1030    ind2=str2num(r.num2);
1031else
1032    mode='j1-j2';
1033    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1034    if ~isempty(r)
1035        NomTypeNc='_1ab';
1036    else
1037        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1038        if ~isempty(r)
1039            NomTypeNc='_1AB';
1040        else
1041            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1042            if ~isempty(r)
1043                NomTypeNc='_1_1-2';
1044            end
1045        end
1046    end
1047    if isempty(r)
1048        display('wrong pair mode input option')
1049    else
1050        ind1=stra2num(r.num1);
1051        ind2=stra2num(r.num2);
1052    end
1053end
1054switch mode
1055    case 'Di'
1056        i1_series=i_series-ind1;% set of first image numbers
1057        i2_series=i_series+ind2;
1058        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1059        if isempty(j_series)
1060            NomTypeNc='_1-2';
1061        else
1062            j1_series=j_series;
1063            j2_series=j_series;
1064            NomTypeNc='_1-2_1';
1065        end
1066    case 'Dj'
1067        j1_series=j_series-ind1;
1068        j2_series=j_series+ind2;
1069        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1070        NomTypeNc='_1_1-2';
1071    otherwise %bursts
1072        i1_series=i_series(1,:);% do not sweep the j index
1073        i2_series=i_series(1,:);
1074        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1075        j2_series=ind2*ones(1,size(i_series,2));
1076        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1077end
1078
1079%------------------------------------------------------------------------
1080% --- set the flag for false vectors
1081function FF=detect_false(Param,C,U,V,FFIn)
1082FF=FFIn;%default, good vectors
1083% FF=1, for correlation max at edge, not set in this function
1084% FF=2, for too small correlation
1085% FF=3, for velocity outside bounds
1086% FF=4 for exclusion by difference with the smoothed field, set by call to function filter_tps
1087
1088if isfield (Param,'MinCorr')
1089     FF(C<Param.MinCorr & FFIn==0)=2;
1090end
1091if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1092    Umod= U.*U+V.*V;
1093    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1094        U2Min=Param.MinVel*Param.MinVel;
1095        FF(Umod<U2Min & FFIn==0)=3;
1096    end
1097    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1098         U2Max=Param.MaxVel*Param.MaxVel;
1099        FF(Umod>U2Max & FFIn==0)=3;
1100    end
1101end
1102
1103% % --- compress the data using integers instead of (single precision)floating reals
1104% function DataOut=compress_data(DataIn,inv_scale_factor)
1105% DataOut=DataIn; %default
1106% DataOut.Conventions= 'uvmat/civdata/compress';
1107% ListVarName=DataIn.ListVarName;
1108% for ilist=1:numel(ListVarName)
1109%     switch ListVarName{ilist}
1110%         case {'Civ1_C','Civ2_C'}
1111%             DataOut.(ListVarName{ilist})=uint8(inv_scale_factor*DataIn.(ListVarName{ilist}));
1112%             DataOut.VarAttribute{ilist}.scale_factor=1/inv_scale_factor;
1113%         case {'Civ1_U','Civ1_V','Civ2_U','Civ2_V','Civ1_U_smooth','Civ1_V_smooth','Civ2_U_smooth','Civ2_V_smooth'}
1114%             DataOut.(ListVarName{ilist})=int16(inv_scale_factor*DataIn.(ListVarName{ilist}));
1115%             DataOut.VarAttribute{ilist}.scale_factor=1/inv_scale_factor;
1116%         case 'Civ1_X'
1117%             DataOut.Civ1_X=uint16(DataIn.Civ1_X);
1118%         case 'Civ1_Y'
1119%             DataOut.Civ1_Y=uint16(DataIn.Civ1_Y);
1120%        case 'Civ2_X'
1121%             DataOut.Civ2_X=uint16(DataIn.Civ2_X);
1122%         case 'Civ2_Y'
1123%             DataOut.Civ2_Y=uint16(DataIn.Civ2_Y);
1124%     end
1125% end
Note: See TracBrowser for help on using the repository browser.