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

Last change on this file since 1203 was 1203, checked in by sommeria, 2 days ago

civ repaired

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