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

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

file relabeling implemented for civ_series

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