source: trunk/src/civ.m @ 313

Last change on this file since 313 was 313, checked in by sommeria, 9 years ago

bug reapirs in view of vector colors and grid in civ

File size: 182.6 KB
Line 
1%'civ': function associated with the interface 'civ.fig' for PIV, spline interpolation and stereo PIV (patch)
2%------------------------------------------------------------------------
3%  provides an interface for the software menucivx
4% function varargout = civ(varargin)
5% provides an interface for the software menucivx
6%
7%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
8%  Copyright Joel Sommeria, 2011, LEGI / CNRS-UJF-INPG, sommeria@legi.grenoble-inp.fr
9%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
10%     This file is part of the toolbox UVMAT.
11%
12%     UVMAT is free software; you can redistribute it and/or modify
13%     it under the terms of the GNU General Public License as published by
14%     the Free Software Foundation; either version 2 of the License, or
15%     (at your option) any later version.
16%
17%     UVMAT is distributed in the hope that it will be useful,
18%     but WITHOUT ANY WARRANTY; without even the implied warranty of
19%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
21%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
22function varargout = civ(varargin)
23%TODO: search range
24
25% Last Modified by GUIDE v2.5 30-Nov-2011 21:52:52
26% Begin initialization code - DO NOT EDIT
27gui_Singleton = 1;
28gui_State = struct('gui_Name',       mfilename, ...
29    'gui_Singleton',  gui_Singleton, ...
30    'gui_OpeningFcn', @civ_OpeningFcn, ...
31    'gui_OutputFcn',  @civ_OutputFcn, ...
32    'gui_LayoutFcn',  [] , ...
33    'gui_Callback',   []);
34if nargin && ischar(varargin{1})
35    gui_State.gui_Callback = str2func(varargin{1});
36end
37
38if nargout
39    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
40else
41    gui_mainfcn(gui_State, varargin{:});
42end
43% End initialization code - DO NOT EDIT
44
45%------------------------------------------------------------------------
46% --- Executes just before civ is made visible.
47function civ_OpeningFcn(hObject, eventdata, handles, fileinput)
48%------------------------------------------------------------------------
49% This function has no output args, see OutputFcn.
50
51%% General settings
52handles.output = hObject;
53guidata(hObject, handles); % Update handles structure
54set(hObject,'WindowButtonDownFcn',{'mouse_down'}) % allows mouse action with right button (zoom for uicontrol display)
55
56%% Adjust the GUI according to the binaries available in PARAM.xml
57path_civ=fileparts(which('civ')); %path to civ
58addpath (path_civ) ; %add the path to civ, (useful in case of change of working directory after civ has been s opened in the working directory)
59errormsg=[];%default error message
60xmlfile='PARAM.xml';
61if exist(xmlfile,'file')
62    try
63        t=xmltree(xmlfile);
64        sparam=convert(t);
65    catch
66        errormsg={' Unable to read the file PARAM.xml defining the civx binaries:'; lasterr};
67    end
68else
69    errormsg=[xmlfile ' not found: path to civx binaries undefined'];
70end
71if ~isempty(errormsg)
72    msgbox_uvmat('WARNING',errormsg);
73end
74test_batch=0;%default: ,no batch mode available
75if isfield(sparam,'BatchParam') && isfield(sparam.BatchParam,'BatchMode')
76    test_batch=strcmp(sparam.BatchParam.BatchMode,'sge'); %sge is currently the only implemented batch mod
77end
78if test_batch==0
79    set(handles.BATCH,'Enable','off')% put the BATCH button in grey (unactivated)
80    set(handles.BATCH,'BackgroundColor',[0.831 0.816 0.784])% put the BATCH button in grey (unactivated)
81end
82if isfield(sparam.RunParam,'CivBin')
83    if ~exist(sparam.RunParam.CivBin,'file')
84        sparam.RunParam.CivBin=fullfile(path_civ,sparam.RunParam.CivBin);
85    end
86else
87    sparam.RunParam.CivBin='';
88end
89
90%% load the list of previously browsed files in the upper bar menu Open/
91dir_perso=prefdir; % path to the directory .matlab for personal data
92profil_perso=fullfile(dir_perso,'uvmat_perso.mat');% personal data file uvmauvmat_perso.mat' in .matlab
93if exist(profil_perso,'file')
94    h=load (profil_perso);
95    if isfield(h,'MenuFile')
96        for ifile=1:min(length(h.MenuFile),5)
97            eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',h.MenuFile{ifile});'])
98        end
99    end
100end
101
102%% prepare the GUI with parameters from the input file if opened from uvmat
103if exist('fileinput','var')% && isfield(param,'RootName') && ~isempty(param.RootName)
104    errormsg=display_file_name(handles,fileinput);
105    if ~isempty(errormsg)
106        msgbox_uvmat('ERROR',errormsg)
107    end
108end
109
110%------------------------------------------------------------------------
111% --- Outputs from this function are returned to the command line.
112function varargout = civ_OutputFcn(hObject, eventdata, handles)
113%------------------------------------------------------------------------
114% Get default command line output from handles structure
115varargout{1} = handles.output;
116
117%------------------------------------------------------------------------
118% --- Function activated by the Open/Browse... option in the upper menu bar.
119function MenuBrowse_Callback(hObject, eventdata, handles)
120%------------------------------------------------------------------------
121%get the current input root file name to initiate the browser
122filebase=get(handles.RootName,'String');
123oldfile=''; %default
124if isempty(filebase)|| isequal(filebase,'')%loads the previously stored root file name
125    dir_perso=prefdir;
126    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
127    if exist(profil_perso,'file')
128        h=load (profil_perso);
129        if isfield(h,'filebase')&& ischar(h.filebase)
130            oldfile=h.filebase;
131        end
132        if isfield(h,'RootPath') && ischar(h.RootPath)
133            oldfile=h.RootPath;
134        end
135    end
136else
137    oldfile=filebase;
138end
139ind_opening=1;%default
140browse.incr_pair=[0 0]; %default
141menu={'*.xml;*.civ;*.png;*.jpg;*.tif;*.avi;*.AVI;*.nc;', ' (*.xml,*.civ,*.png,*.jpg ,.tif, *.avi,*.nc)';
142    '*.xml',  '.xml files '; ...
143    '*.civ',  '.civ files '; ...
144    '*.png','.png image files'; ...
145    '*.jpg',' jpeg image files'; ...
146    '*.tif','.tif image files'; ...
147    '*.avi;*.AVI','.avi movie files'; ...
148    '*.nc','.netcdf files'; ...
149    '*.*',  'All Files (*.*)'};
150[FileName, PathName, filtindex] = uigetfile( menu, 'Pick a file',oldfile);
151fileinput=[PathName FileName];%complete file name
152sizf=size(fileinput);
153if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
154
155%% prepare the GUI with parameters from the input file if opened from uvmat
156errormsg=display_file_name(handles,fileinput);
157if ~isempty(errormsg)
158    msgbox_uvmat('ERROR',erromsg)
159end
160
161[path,name,ext]=fileparts(fileinput);
162testeditxml=0;
163if isequal(ext,'.xml')
164    testeditxml=1;
165    t_browse=xmltree(fileinput);
166    head_element=get(t_browse,1);
167    if isfield(head_element,'name')&& isequal(head_element.name,'ImaDoc')
168        testeditxml=0;
169    end
170end
171if testeditxml==1 || isequal(ext,'.xls')
172    heditxml=editxml({fileinput});
173    set(heditxml,'Tag','browser')
174    waitfor(heditxml,'Tag','idle')
175    if ~ishandle(heditxml)
176        return
177    end
178    attr=findobj(get(heditxml,'children'),'Tag','CurrentAttributes');
179    set(handles.browse,'UserData',fileinput)% store for future opening with browser
180    fileinput=get(attr,'UserData');
181    if ~exist(fileinput,'file')
182        return
183    end
184end
185[RootPath,RootFile,str1,str2,str_a,str_b,ext,nom_type,subdir]=name2display(fileinput);
186% filebase=fullfile(RootPath,RootFile);
187num_i1=str2double(str1);
188if isnan(num_i1),num_i1=1;end
189num_i2=str2double(str2);
190if isnan(num_i2),num_i2=num_i1;end
191num_j1=stra2num(str_a);
192if isnan(num_j1),num_j1=1;end
193num_j2=stra2num(str_b);
194if isnan(num_j2),num_j2=num_j1;end
195if isequal(get(handles.ListCompareMode,'Value'),1)
196    browse=[];%initialisation
197else
198    browse=get(handlesRootName,'UserData');
199end
200browse.num_i1=num_i1;
201browse.num_i2=num_i2;
202browse.num_j1=num_j1;
203browse.num_j2=num_j2;
204if length(ext)>1 && (~isempty(imformats(ext(2:end)))||strcmpi(ext,'.avi'));%if an image file has been opened by uvmat
205    browse.nom_type_ima=nom_type;
206    browse.ext_ima=ext;
207    set(handles.ImaExt,'String',ext)
208end
209set(handles.ImaDoc,'String',ext);
210
211set(handles.RootName,'UserData',browse);% store information from browser
212
213%------------------------------------------------------------------------
214% --- Open again the file whose name has been recorded in MenuFile_1
215function MenuFile_1_Callback(hObject, eventdata, handles)
216%------------------------------------------------------------------------
217fileinput=get(handles.MenuFile_1,'Label');
218errormsg=display_file_name(handles,fileinput);
219if ~isempty(errormsg)
220    msgbox_uvmat('ERROR',erromsg)
221end
222
223% -----------------------------------------------------------------------
224% --- Open again the file whose name has been recorded in MenuFile_2
225function MenuFile_2_Callback(hObject, eventdata, handles)
226%------------------------------------------------------------------------
227fileinput=get(handles.MenuFile_2,'Label');
228errormsg=display_file_name(handles,fileinput);
229if ~isempty(errormsg)
230    msgbox_uvmat('ERROR',erromsg)
231end
232
233% -----------------------------------------------------------------------
234% --- Open again the file whose name has been recorded in MenuFile_3
235function MenuFile_3_Callback(hObject, eventdata, handles)
236%------------------------------------------------------------------------
237fileinput=get(handles.MenuFile_3,'Label');
238errormsg=display_file_name(handles,fileinput);
239if ~isempty(errormsg)
240    msgbox_uvmat('ERROR',erromsg)
241end
242
243% -----------------------------------------------------------------------
244% --- Open again the file whose name has been recorded in MenuFile_4
245function MenuFile_4_Callback(hObject, eventdata, handles)
246%------------------------------------------------------------------------
247fileinput=get(handles.MenuFile_4,'Label');
248errormsg=display_file_name(handles,fileinput);
249if ~isempty(errormsg)
250    msgbox_uvmat('ERROR',erromsg)
251end
252
253% -----------------------------------------------------------------------
254% --- Open again the file whose name has been recorded in MenuFile_5
255function MenuFile_5_Callback(hObject, eventdata, handles)
256%------------------------------------------------------------------------
257fileinput=get(handles.MenuFile_5,'Label');
258errormsg=display_file_name(handles,fileinput);
259if ~isempty(errormsg)
260    msgbox_uvmat('ERROR',erromsg)
261end
262
263% -----------------------------------------------------------------------
264% --- Prepare the GUI for the compiled CivX program
265function MenuCivX_Callback(hObject, eventdata, handles)
266set(handles.MenuMatlab,'checked','off')
267set(handles.MenuCivX,'checked','on')
268%set(handles.thresh_patch1,'Visible','off')
269% set(handles.thresh_text1,'Visible','off')
270% set(handles.num_MaxDiff,'Visible','off')
271% set(handles.thresh_text2,'Visible','off')
272set(handles.num_Rho,'Style','edit')
273set(handles.num_Rho,'String','1')
274set(handles.BATCH,'Enable','on')
275% -----------------------------------------------------------------------
276
277% -----------------------------------------------------------------------
278% --- Prepare the GUI for the Matlab PIV program
279function MenuMatlab_Callback(hObject, eventdata, handles)
280% -----------------------------------------------------------------------
281set(handles.MenuMatlab,'checked','on')
282set(handles.MenuCivX,'checked','off')
283if get(handles.CheckPatch1,'Value')
284    set(handles.thresh_patch1,'Visible','on')
285    set(handles.thresh_text1,'Visible','on')
286end
287if get(handles.CheckPatch2,'Value')
288    set(handles.num_MaxDiff,'Visible','on')
289    set(handles.thresh_text2,'Visible','on')
290end
291set(handles.num_Rho,'Style','popupmenu')
292set(handles.num_Rho,'Value',1)
293set(handles.num_Rho,'String',{'1';'2'})
294set(handles.BATCH,'Enable','off')
295
296% -----------------------------------------------------------------------
297% --- Open the help html file
298function MenuHelp_Callback(hObject, eventdata, handles)
299% -----------------------------------------------------------------------
300path_civ=fileparts(which ('civ'));
301helpfile=fullfile(path_civ,'uvmat_doc','uvmat_doc.html');
302if isempty(dir(helpfile))
303    msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
304else
305    addpath (fullfile(path_civ,'uvmat_doc'))
306    web([helpfile '#civ'])
307end
308
309%------------------------------------------------------------------------
310% --- Function activated when a new filebase (image series) is introduced
311function RootName_Callback(hObject, eventdata, handles)
312%------------------------------------------------------------------------
313filebase=get(handles.RootName,'String');
314errormsg=display_file_name(handles,filebase);
315if ~isempty(errormsg)
316    msgbox_uvmat('ERROR',erromsg)
317end
318
319%------------------------------------------------------------------------
320% --- general function activated for an input file series
321function errormsg=display_file_name(handles,fileinput)
322%------------------------------------------------------------------------
323set(handles.ListCompareMode,'Visible','on')
324errormsg='';%default empty error message
325
326%% enable RUN, BATCH button and 'status' display
327set(handles.RUN, 'Enable','On')
328set(handles.RUN,'BackgroundColor',[1 0 0])%set RUN button to red color
329set(handles.BATCH,'Enable','On')
330set(handles.BATCH,'BackgroundColor',[1 0 0])%set BATCH button to red color
331if isfield(handles,'status')
332    set(handles.status,'Value',0);       %suppress the 'status' display
333    status_Callback([], [], handles)
334end
335
336%% determine nomenclature types and extension of the input files
337ext_ima='';%default
338nom_type_ima='';%default
339nom_type_nc='';
340[RootPath,FileName,i1_str,i2_str,j1_str,j2_str,ext_input,nom_type_input,subdir]=name2display(fileinput);
341RootName=fullfile(RootPath,FileName);
342set(handles.RootName,'String',RootName)
343set(handles.RootName,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
344i1=str2double(i1_str);
345i2=str2double(i2_str);
346j1=str2double(j1_str);
347j2=str2double(j2_str);
348num_ref_i=i1;%efaulmt ref index
349num_ref_j=j1;
350browse.incr_pair=[0 0];%default
351
352% form=imformats(ext_input(2:end));
353if ~isempty(ext_input)&&(~isempty(imformats(ext_input(2:end)))||strcmpi(ext_input,'.avi'))% if the extension corresponds to an image or movie format recognized by Matlab
354    ext_ima=ext_input;
355    nom_type_ima=nom_type_input;
356else %case of netcdf input file, look for corresponding images
357    nom_type_nc=nom_type_input;
358    if ~isnan(i2)
359        num_ref_i=floor((num_ref_i+i2)/2);% reference image number corresponding to the file
360        browse.incr_pair(1)=i2-i1;
361        browse.incr_pair(2)=0;
362    end
363    %TODO: read the image name in the netcdf file (if documented)
364    %look for double image series '_i_j'
365    dirima=dir([RootName '_' i1_str '_' j1_str '.*']);
366    if isempty(dirima)
367        % look for images series  with sub marker '_'
368        dirima=dir([RootName '_*' i1_str  '.*']);
369        if isempty(dirima)
370            % look for other images series
371            dirima=dir([RootName '*' i1_str '.*']);
372            if isempty(dirima)
373                % look for other images series witth letter appendix
374                appendix=char(96+j1_str);
375                dirima=dir([RootName '*' i1_str appendix '.*']);
376            end
377        end
378    end
379    for ilist=1:numel(dirima)
380        [pp,ff,i1_str,i2_str,j1_str,j2_str,ext_list,nom_type_list]=name2display(dirima(ilist).name);
381        form=imformats(ext_list(2:end));
382        if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
383            ext_ima=ext_list;
384            nom_type_ima=nom_type_list;
385            i1=str2double(i1_str);
386            j1=str2double(j1_str);
387            i2=str2double(i2_str);
388            j2=str2double(j2_str);         
389            % set the range of fields (1:1 by default) and selected pair
390            if isequal(i2,i1)||isnan(i2)
391                num_ref_i=i1;
392            else
393                num_ref_i=floor((i1+i2)/2);
394                browse.incr_pair(1)=i2-i1;
395                browse.incr_pair(2)=0;
396            end
397            if isequal(j1,j2)||isnan(j2)
398                if isnan(j1)
399                    num_ref_j=1;
400                else
401                    num_ref_j=j1;
402                end
403            else
404                num_ref_j=floor((j1+j2)/2);
405                browse.incr_pair(2)=j2-j1;
406            end
407            break
408        end
409    end
410end
411
412%% look for an image documentation file
413ext_imadoc='';%default
414if exist([RootName '.xml'],'file')
415    ext_imadoc='.xml';
416elseif exist([RootName '.civxml'],'file')
417    ext_imadoc='.civxml';
418elseif exist([RootName '.civ'],'file')
419    ext_imadoc='.civ';
420elseif exist([RootName '.avi'],'file')
421    ext_imadoc='.avi';
422elseif exist([RootName '.AVI'],'file')
423    ext_imadoc='.AVI';
424end
425set(handles.ImaDoc,'String',ext_imadoc)% display the extension name for the image documentation file used
426set(handles.ImaDoc,'BackgroundColor',[1 1 0])
427drawnow
428%%%%%%%%   read image documentation file  %%%%%%%%%%%%%%%%%%%%%%%%%%%
429mode=''; %default
430time=[];
431TimeUnit='frame'; %default
432CoordUnit='px';%default
433pxcmx_search=[];%default
434pxcmy_search=[];%default
435if isequal(ext_imadoc,'.civxml')%TO ABANDON
436    [nbfield,nbfield2,time]=read_civxml([RootName '.civxml']);
437    mode='pair j1-j2';
438    if isempty(nom_type_ima)% dtermine types by default if not already selected by browser or uvmat
439        nom_type_ima='_i_j';
440    end
441elseif isequal(ext_imadoc,'.xml')
442    [XmlData,warntext]=imadoc2struct([RootName '.xml']);
443    ext_ima_read=[];
444    nom_type_read=[];
445    if isfield(XmlData,'Heading')&&isfield(XmlData.Heading','ImageName')&&ischar(XmlData.Heading.ImageName)% get image nom type and extension from the xml file
446        [PP,FF,fc,str2,str_a,str_b,ext_ima_read,nom_type_read]=name2display(XmlData.Heading.ImageName);
447        fullname=fullfile(fileparts(RootName),XmlData.Heading.ImageName); %full name (including path) of the first image defined by the xmle file,
448        if ~exist(fullname,'file')
449            msgbox_uvmat('WARNING',['FirstImage ' fullname ' defined in the xml file does not exist'])
450        end
451    end
452    if isfield(XmlData,'Time')
453        time=XmlData.Time;
454        nbfield=size(time,1);
455        nbfield2=size(time,2);
456        %transform .Time to a column vector if it is a line vector thenomenclature uses a single index: correct possible bug in xml
457        if isequal(nbfield,1) && ~isequal(nbfield2,1)% .Time is a line vector
458            if numel(nom_type_read)>=2 && isempty(regexp(nom_type_read(2:end),'\D','once'))
459                time=time';
460                nbfield=nbfield2;
461                nbfield2=1;
462            end
463        end
464    end
465    if isfield(XmlData,'TimeUnit')
466        TimeUnit=XmlData.TimeUnit;
467    end
468    pxcmx_search=1;
469    pxcmy_search=1;
470    if isfield(XmlData,'GeometryCalib')
471        tsai=XmlData.GeometryCalib;
472        if isfield(tsai,'f') && isfield(tsai,'Tz') && isfield(tsai,'dpx') && isfield(tsai,'dpy')&& isfield(tsai,'R')
473            rot2D=tsai.R(1:2,[1,2]);
474            pxcmx_search=tsai.f * sqrt(det(rot2D))/(tsai.Tz*tsai.dpx);
475            pxcmy_search=tsai.f * sqrt(det(rot2D))/(tsai.Tz*tsai.dpy);
476        end
477        if isfield(tsai,'CoordUnit')
478            CoordUnit=tsai.CoordUnit;
479        end
480    end
481elseif strcmp(ext_imadoc,'.civ')% case of .civ image documentation file
482    [error,time,TimeUnit,mode,npx,npy]=read_imatext([RootName '.civ']);
483    if error==2, msgbox_uvmat('WARNING',['no file ' RootName '.civ']);
484    elseif error==1, msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
485    end
486    nom_type_ima='001a';
487elseif strcmpi(ext_imadoc,'.avi')
488    nom_type_ima='*';
489    ext_ima=ext_imadoc;
490    set(handles.ListPairMode,'Value',1);
491    set(handles.ListPairMode,'String',{'series(Di)'})
492    dt=0.04;%default
493    if exist([RootName ext_imadoc],'file')==2
494        info=aviinfo([RootName ext_imadoc]);%read infos on the avi movie
495        dt=1/info.FramesPerSecond;%time interval between successive frames
496        nbfield=info.NumFrames;%number of frames
497    end
498    time=(dt*(0:nbfield-1))';%list of image times
499end
500if isempty(time)
501    set(handles.ImaDoc,'String',''); %xml file not used for timing
502end
503set(handles.ImaDoc,'BackgroundColor',[1 1 1])% set display box to yellow color
504
505
506%% timing display
507%show the reference image edit box if relevant (not needed for movies or in the absence of time information
508if ~isempty(time)
509    if size(time,1)+size(time,2)>=3 % if there are at least two time values to define dt
510        nbfield=size(time,1);
511        nbfield2=size(time,2);
512        set(handles.ImaDoc,'UserData',time); %store the set of times
513        set(handles.dt_unit,'String',['dt in m' TimeUnit]);
514        set(handles.TimeUnit,'String',TimeUnit);
515        set(handles.nb_field,'String',num2str(nbfield));
516        set(handles.nb_field2,'String',num2str(nbfield2));
517    end
518end
519set(handles.CoordUnit,'String',CoordUnit)
520set(handles.SearchRange,'UserData',[pxcmx_search pxcmy_search]);
521set(handles.ImaExt,'String',ext_ima)
522set(handles.ref_i,'String',num2str(num_ref_i))
523set(handles.first_i,'String',num2str(num_ref_i));
524set(handles.last_i,'String',num2str(num_ref_i));%
525set(handles.ref_j,'String',num2str(num_ref_j))
526set(handles.first_j,'String',num2str(num_ref_j));
527set(handles.last_j,'String',num2str(num_ref_j));%
528
529%% set the civ options depending on the input file content
530ind_opening=0;%default
531if isequal(ext_input,'.nc')
532    browse.nom_type_nc=nom_type_input;
533    ind_opening=2;% propose 'fix' as the default option
534    Data=nc2struct(fileinput,'ListGlobalAttribute','CivStage','absolut_time_T0','fix','patch','civ2','fix2');
535    if ~isempty(Data.CivStage)%test for civ files
536        ind_opening=Data.CivStage;
537        set(handles.ListPairMode,'Value',3)
538    end
539end
540ListOptions={'CheckCiv1', 'CheckFix1' 'CheckPatch1', 'CheckCiv2', 'CheckFix2', 'CheckPatch2'};
541for index = 1:ind_opening
542    set(handles.(ListOptions{index}),'value',0)
543end
544for index = ind_opening+1
545    set(handles.(ListOptions{index}),'value',1)
546end
547update_CivOptions(handles)
548
549
550%%  set the menus of image pairs and default selection for civ   %%%%%%%%%%%%%%%%%%%
551test_ima_i=numel(nom_type_ima)>1 && isempty(regexp(nom_type_ima(2:end),'\D','once'));%images with single indexing
552if test_ima_i || isequal(nom_type_nc,'_i1-i2')||~(exist('nbfield2','var')&&(nbfield2~=1))
553    set(handles.ListPairMode,'Value',1)
554    set(handles.ListPairMode,'String',{'series(Di)'})   
555elseif (nbfield==1)% simple series in j
556    set(handles.ListPairMode,'Value',1)
557    set(handles.ListPairMode,'String',{'series(Dj)'})
558else
559    set(handles.ListPairMode,'String',{'pair j1-j2';'series(Dj)';'series(Di)'})%multiple choice
560    if nbfield2 <= 10
561        set(handles.ListPairMode,'Value',1)% advice 'pair j1-j2' for small burst
562    end
563end
564
565%% update the subdirectory display
566listot=dir(RootPath);%directory of RootPath
567idir=0;
568listdir={''};%default
569% get the list of existing civ subdirectories in the path of theinput root  file
570for ilist=1:length(listot)
571    if listot(ilist).isdir
572        name=listot(ilist).name;
573        if ~isequal(name,'.') && ~isequal(name,'..')
574            idir=idir+1;
575            listdir{idir,1}=listot(ilist).name;
576        end
577    end
578end
579Value=find(strcmp(subdir,listdir));%search the index of subdir in the cell listdir
580if isempty(Value)% if the input subdir is not found
581    ValueCiv1=get(handles.ListSubdirCiv1,'Value');%read the currrently selected dir name
582    if ValueCiv1>numel(listdir)
583        ValueCiv1=1;
584    end
585    set(handles.txt_SubdirCiv1,'String',listdir{ValueCiv1})
586    ValueCiv2=get(handles.ListSubdirCiv2,'Value');
587    if ValueCiv2>numel(listdir)
588        ValueCiv2=1;
589    end
590    set(handles.txt_SubdirCiv2,'String',listdir{ValueCiv2})
591else
592    ValueCiv1=Value;
593    ValueCiv2=Value;
594     set(handles.txt_SubdirCiv1,'String',listdir{Value})
595     set(handles.txt_SubdirCiv2,'String',listdir{Value})
596end
597set(handles.ListSubdirCiv1,'Value',ValueCiv1)
598set(handles.ListSubdirCiv2,'Value',ValueCiv2)
599set(handles.ListSubdirCiv1,'String',[listdir;'new...'])
600set(handles.ListSubdirCiv2,'String',[listdir;'new...'])
601if isempty(listdir)
602    set(handles.txt_SubdirCiv1,'String','CIV')
603    set(handles.txt_SubdirCiv2,'String','CIV')
604end
605
606%% store info
607browse.nom_type_ima=nom_type_ima;
608set(handles.RootName,'UserData',browse)% store the nomenclature type
609
610%% list the possible index pairs, depending on the option set in ListPairMode
611ListPairMode_Callback([], [], handles)
612
613%% store the root input filename for future opening
614profil_perso=fullfile(prefdir,'uvmat_perso.mat');
615% RootPath=fileparts(RootName);
616if exist(profil_perso,'file')
617    save (profil_perso,'RootPath','-append'); %store the root name for future opening of uvmat
618else
619    txt=ver('MATLAB');
620    Release=txt.Release;
621    relnumb=str2double(Release(3:4));
622    if relnumb >= 14
623        save (profil_perso,'RootPath','-V6'); %store the root name for future opening of uvmat
624    else
625        save (profil_perso,'RootPath'); %store the root name for future opening of uvmat
626    end
627end
628set(handles.RootName,'BackgroundColor',[1 1 1])
629
630%------------------------------------------------------------------------
631% --- Executes on carriage return on the subdir checkciv1 edit window
632function txt_SubdirCiv1_Callback(hObject, eventdata, handles)
633%------------------------------------------------------------------------
634subdir=get(handles.txt_SubdirCiv1,'String');
635menu_str=get(handles.ListSubdirCiv1,'String');% read the list of subdirectories for update
636ichoice=find(strcmp(subdir,menu_str),1);
637if isempty(ichoice)
638    ilist=numel(menu_str); %select 'new...' in the menu
639else
640    ilist=ichoice;
641end
642set(handles.ListSubdirCiv1,'Value',ilist)% select the selected subdir in the menu
643if get(handles.CheckCiv1,'Value')% if Civ1 is performed
644    set(handles.txt_SubdirCiv2,'String',subdir);% set by default civ2 directory the same as civ1
645    set(handles.ListSubdirCiv2,'Value',ilist)
646else % if Civ1 data already exist
647    find_netcpair_civ1(handles); %update the list of available pairs from netcdf files in the new directory
648end
649
650%------------------------------------------------------------------------
651% --- Executes on carriage return on the subdir checkciv1 edit window
652function txt_SubdirCiv2_Callback(hObject, eventdata, handles)
653%------------------------------------------------------------------------
654subdir=get(handles.txt_SubdirCiv1,'String');
655menu_str=get(handles.ListSubdirCiv2,'String');% read the list of subdirectories for update
656ichoice=find(strcmp(subdir,menu_str),1);
657if isempty(ichoice)
658    ilist=numel(menu_str); %select 'new...' in the menu
659else
660    ilist=ichoice;
661end
662set(handles.ListSubdirCiv2,'Value',ilist)% select the selected subdir in the menu
663%update the list of available pairs from netcdf files in the new directory
664if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
665    find_netcpair_civ2(handles);
666end
667
668%------------------------------------------------------------------------
669% --- Executes on button press in CheckCiv1.
670function CheckCiv1_Callback(hObject, eventdata, handles)
671%------------------------------------------------------------------------
672update_CivOptions(handles)
673
674%------------------------------------------------------------------------
675% --- Executes on button press in CheckFix1.
676function CheckFix1_Callback(hObject, eventdata, handles)
677%------------------------------------------------------------------------
678update_CivOptions(handles)
679
680%------------------------------------------------------------------------
681% --- Executes on button press in CheckPatch1.
682function CheckPatch1_Callback(hObject, eventdata, handles)
683%------------------------------------------------------------------------
684update_CivOptions(handles)
685
686%------------------------------------------------------------------------
687% --- Executes on button press in CheckCiv2.
688function CheckCiv2_Callback(hObject, eventdata, handles)
689%------------------------------------------------------------------------
690update_CivOptions(handles)
691
692%------------------------------------------------------------------------
693% --- Executes on button press in CheckFix2.
694function CheckFix2_Callback(hObject, eventdata, handles)
695%------------------------------------------------------------------------
696update_CivOptions(handles)
697
698%------------------------------------------------------------------------
699% --- Executes on button press in CheckPatch2.
700function CheckPatch2_Callback(hObject, eventdata, handles)
701%------------------------------------------------------------------------
702update_CivOptions(handles)
703
704%------------------------------------------------------------------------
705% --- activated by any checkbox controling the selection of Civ1,Fix1,Patch1,Civ2,Fix2,Patch2
706function update_CivOptions(handles)
707%------------------------------------------------------------------------
708checkbox=zeros(1,6);
709checkbox(1)=get(handles.CheckCiv1,'Value');
710checkbox(2)=get(handles.CheckFix1,'Value');
711checkbox(3)=get(handles.CheckPatch1,'Value');
712checkbox(4)=get(handles.CheckCiv2,'Value');
713checkbox(5)=get(handles.CheckFix2,'Value');
714checkbox(6)=get(handles.CheckPatch2,'Value');
715ind_selected=find(checkbox,1);
716if ~isempty(ind_selected)
717  RootName=get(handles.RootName,'String');
718    if isempty(RootName)
719         msgbox_uvmat('ERROR','Please open an image or PIV .nc file with the upper bar menu Open/Browse...')
720        return
721    end
722end
723set(handles.PairIndices,'Visible','on')
724set(handles.txt_SubdirCiv1,'Visible','on')
725set(handles.ListSubdirCiv1,'Visible','on')
726find_netcpair_civ1(handles) % select the available netcdf files
727if max(checkbox(4:6))% case of civ2 pair choice needed
728    set(handles.TitlePairCiv2,'Visible','on')
729    set(handles.TitleSubdirCiv2,'Visible','on')
730    set(handles.txt_SubdirCiv2,'Visible','on')
731    set(handles.ListSubdirCiv2,'Visible','on')
732    set(handles.ListPairCiv2,'Visible','on')
733    find_netcpair_civ2(handles) % select the available netcdf files
734else
735    set(handles.TitleSubdirCiv2,'Visible','off')
736    set(handles.txt_SubdirCiv2,'Visible','off')
737    set(handles.ListSubdirCiv2,'Visible','off')
738    set(handles.ListPairCiv2,'Visible','off')
739end
740options={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
741for ilist=1:length(options)
742    if checkbox(ilist)
743        set(handles.(options{ilist}),'Visible','on')
744    else
745        set(handles.(options{ilist}),'Visible','off')
746    end
747end
748
749%------------------------------------------------------------------------
750% --- Executes on button press in RUN: processing on local computer
751function RUN_Callback(hObject, eventdata, handles)
752%------------------------------------------------------------------------
753set(handles.RUN, 'Enable','Off')
754set(handles.RUN,'BackgroundColor',[0.831 0.816 0.784])
755batch=0;
756errormsg=launch_jobs(hObject, eventdata, handles,batch);
757set(handles.RUN, 'Enable','On')
758set(handles.RUN,'BackgroundColor',[1 0 0])
759
760% start status callback to visualise results
761if ~isempty(errormsg)
762    display(errormsg)
763    msgbox_uvmat('ERROR',errormsg)
764elseif  isfield(handles,'status') %&& ~isequal(get(handles.ListPairMode,'Value'),3)
765    set(handles.status,'Value',1);%suppress status display
766    status_Callback(hObject, eventdata, handles)
767end
768
769%------------------------------------------------------------------------
770% --- Executes on button press in BATCH: remote processing
771function BATCH_Callback(hObject, eventdata, handles)
772% -----------------------------------------------------------------------
773set(handles.BATCH, 'Enable','Off')
774set(handles.BATCH,'BackgroundColor',[0.831 0.816 0.784])
775batch=1;
776errormsg=launch_jobs(hObject, eventdata, handles, batch);
777set(handles.BATCH, 'Enable','On')
778set(handles.BATCH,'BackgroundColor',[1 0 0])
779
780% start status callback to visualise results
781if ~isempty(errormsg)
782    display(errormsg)
783    msgbox_uvmat('ERROR',errormsg)
784elseif isfield(handles,'status')
785    set(handles.status,'Value',1);%suppress status display
786    status_Callback(hObject, eventdata, handles)
787end
788
789%-------------------------------------------------------------------
790% --- Executes on button press in status.
791function status_Callback(hObject, eventdata, handles)
792%-------------------------------------------------------------------
793val=get(handles.status,'Value');
794if val==0
795    set(handles.status,'BackgroundColor',[0 1 0])
796    hfig=findobj(allchild(0),'name','civ_status');
797    if ~isempty(hfig)
798        delete(hfig)
799    end
800    return
801end
802set(handles.status,'BackgroundColor',[1 1 0])
803drawnow
804listtype={'civ1','fix1','patch1','civ2','fix2','patch2'};
805Param.CheckCiv1=get(handles.CheckCiv1,'Value');
806Param.CheckFix1=get(handles.CheckFix1,'Value');
807Param.CheckPatch1=get(handles.CheckPatch1,'Value');
808Param.CheckCiv2=get(handles.CheckCiv2,'Value');
809Param.CheckFix2=get(handles.CheckFix2,'Value');
810Param.CheckPatch2=get(handles.CheckPatch2,'Value');
811box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
812
813option_civ=find(box_test,1,'last');%last selected option (non-zero index of box_test)
814filecell=get(handles.civ,'UserData');%retrieve the list of output files expected for PIV
815test_new=0;
816if ~isfield(filecell,'nc')
817    test_new=1;
818    [ref_i,ref_j,errormsg]=find_ref_indices(handles);
819    if ~isempty(errormsg)
820        msgbox_uvmat('ERROR',errormsg)
821        return
822    end
823    filecell=set_civ_filenames(handles,ref_i,ref_j,box_test);%determine the output file expected from the GUI status
824end
825if ~isequal(box_test(4:6),[0 0 0])
826    civ_files=filecell.nc.civ2;%case of civ2 operations
827else
828    civ_files=filecell.nc.civ1;
829end
830[root,filename,ext]=fileparts(civ_files{1});
831[rootroot,subdir,extdir]=fileparts(root);
832hfig=findobj(allchild(0),'name','civ_status');
833if isempty(hfig)
834    hfig=figure('DeleteFcn',@stop_status);
835    set(hfig,'name','civ_status')
836    hlist=uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', @open_view_field,'tag','list');
837    uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','msgbox','Max',2,'String','checking files...');
838    uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
839    uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','OK','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@close_GUI);
840    BarPosition=[0.05 0.81 0.01 0.05];
841    hwaitbar=uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
842    drawnow
843end
844% datnum=[];
845Tabchar={};
846nbfiles=numel(civ_files);
847count=0;
848testrecent=0;
849while count<nbfiles
850    count=0;
851    datnum=zeros(1,nbfiles);
852    for ifile=1:nbfiles
853        detect=exist(civ_files{ifile},'file'); % check the existence of the file
854        option=0;
855        if detect==0
856            option_str='not created';
857        else
858            datfile=dir(civ_files{ifile});
859            if isfield(datfile,'datenum')
860                datnum(ifile)=datfile.datenum;%only available in recent matlab versions
861                testrecent=1;
862            end
863            filefound(ifile)={datfile.name};
864            lastfield='';
865            % check the content  netcdf file
866            Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','patch2','fix2','civ2','patch','fix');
867            if ~isempty(Data.patch2) && isequal(Data.patch2,1)
868                option=6;
869                option_str='patch2';
870            elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
871                option=5;
872                option_str='fix2';
873            elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
874                option=4;
875                option_str='civ2';
876            elseif ~isempty(Data.patch) && isequal(Data.patch,1);
877                option=3;
878                option_str='patch1';
879            elseif ~isempty(Data.fix) && isequal(Data.fix,1);
880                option=2;
881                option_str='fix1';
882            else
883                option=1;
884                option_str='civ1';
885            end
886        end
887        if option >= option_civ
888            count=count+1;
889        end
890        [rr,filename,ext]=fileparts(civ_files{ifile});
891        Tabchar{ifile,1}=[fullfile([subdir extdir],filename) ext  '...' option_str];
892    end
893    datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
894    if isempty(datnum)
895        if testrecent
896            message='no civ result created yet';
897        else
898            message='';
899        end
900    else
901        datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
902        [first,ind]=min(datnum);
903        [last,indlast]=max(datnum);
904        if test_new
905            message='existing file status, no processing launched yet';
906        else
907        message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
908            ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
909        end
910    end
911    hfig=findobj(allchild(0),'name','civ_status');
912    if isempty(hfig)% the status list has been deleted
913        return
914    else
915        hlist=findobj(hfig,'tag','list');
916        hmsgbox=findobj(hfig,'tag','msgbox');
917        hwaitbar=findobj(hfig,'tag','waitbar');
918        set(hlist,'String',Tabchar)
919        set(hmsgbox,'String', message)
920        if count>0 && ~test_new
921            BarPosition(3)=0.9*count/nbfiles;
922            set(hwaitbar,'Position',BarPosition)
923        end
924    end
925    set(hlist,'UserData',rootroot)
926    if count<10
927    pause(.5)% wait 0.5 seconds for next check
928    else
929        pause(10)% wait 10 seconds for next check
930    end
931end
932
933%------------------------------------------------------------------------
934% --- Main lauch command, called by RUN and BATCH
935function errormsg=launch_jobs(hObject, eventdata, handles, batch)
936%-----------------------------------------------------------------------
937errormsg='';%default
938
939%% read the input parameters from the  GUI civ
940Param=read_GUI(handles.civ);
941
942%% check the selected list of operations:
943operations={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
944box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
945index_first=find(box_test==1,1);
946if isempty(index_first)
947    errormsg='no selected operation';
948    return
949end
950index_last=find(box_test==1,1,'last');
951box_used=box_test(index_first : index_last);
952[box_missing,ind_missing]=min(box_used);
953if isequal(box_missing,0); %there is a missing step in the sequence of operations
954    errormsg=['missing' cell2mat(operations(ind_missing))];
955    return
956end
957
958%% check mask if selecetd
959%could be included in get_mask callback ?
960if isequal(get(handles.CheckMask,'Value'),1)
961    maskname=get(handles.txt_MaskName,'String');
962    if ~exist(maskname,'file')
963        get_mask_civ1_Callback(hObject, eventdata, handles);
964    end
965end
966if isequal(get(handles.CheckMask,'Value'),1)
967    maskname=get(handles.txt_MaskName,'String');
968    if ~exist(maskname,'file')
969        get_mask_fix1_Callback(hObject, eventdata, handles);
970    end
971end
972if isequal(get(handles.CheckMask,'Value'),1)
973    maskname=get(handles.txt_Mask,'String');
974    if ~exist(maskname,'file')
975        get_mask_civ2_Callback(hObject, eventdata, handles);
976    end
977end
978if isequal(get(handles.CheckMask,'Value'),1)
979    maskname=get(handles.txt_MaskName,'String');
980    if ~exist(maskname,'file')
981        get_mask_fix2_Callback(hObject, eventdata, handles);
982    end
983end
984
985%% reinitialise status callback
986if isfield(handles,'status')
987    set(handles.status,'Value',0);%suppress status display
988    status_Callback(hObject, eventdata, handles)
989end
990
991%% read the PARAM.xml file to get the binaries (and batch_mode if batch)
992path_civ=fileparts(which('civ')); %path to the source directory of uvmat
993xmlfile='PARAM.xml';
994if exist(xmlfile,'file')% search parameter xml file in the whole matlab path
995    t=xmltree(xmlfile);
996    s=convert(t);
997else
998    errormsg=['no file ' xmlfile];
999    return
1000end
1001test_interp=0; %eviter les variables test_ (LG)
1002if batch
1003    if isfield(s,'BatchParam')
1004        Param.xml=s.BatchParam;
1005        if isfield(Param.xml,'BatchMode')
1006            batch_mode=Param.xml.BatchMode;
1007            if ~ismember(batch_mode,{'sge','oar'})
1008                errormsg=['batch mode ' batch_mode ' not supported by UVMAT'];
1009                return
1010            end
1011        end
1012    else
1013        errormsg='no batch civ binaries defined in PARAM.xml';
1014        return
1015    end
1016else % run
1017    if isfield(s,'RunParam')
1018        Param.xml=s.RunParam;
1019    else
1020        msgbox_uvmat('ERROR','no run civ binaries defined in PARAM.xml')
1021        return
1022    end
1023end
1024
1025%% check batch mode supported
1026if batch
1027    switch batch_mode
1028        case 'sge'
1029            test_command='qstat';
1030        case 'oar'
1031            test_command='oarstat';
1032    end   
1033    [s,w]=system(test_command);
1034    if ~isequal(s,0)
1035        msgbox_uvmat('ERROR',[batch_mode ' batch system not available'])
1036        return
1037    end
1038end
1039
1040%% check if the binaries exist
1041if isequal(get(handles.MenuMatlab,'checked'),'on')
1042    CivMode='Matlab';
1043else
1044    CivMode='CivX';
1045end
1046binary_list={};
1047switch CivMode
1048    case 'CivX'
1049        binary_list={'Civ1Bin','Civ2Bin','PatchBin','FixBin'};
1050    case 'CivAll'
1051        binary_list={'Civ'};
1052    case 'Matlab'
1053        if batch
1054            % vérifier MenuMatlab installé sur le cluster
1055            % difficile a faire a priori
1056        end         
1057end
1058for bin_name=binary_list %loop on the list of binaries
1059    if isfield(Param.xml,bin_name{1})% bin_name{1} =current name in the list
1060        if ~exist(Param.xml.(bin_name{1}),'file')%look for the full path if the file name has been defined with a relative path in PARAM.xml
1061            fullname=fullfile(path_civ,Param.xml.(bin_name{1}));
1062            if exist(fullname,'file')
1063                Param.xml.(bin_name{1})=fullname;
1064            else
1065                msgbox_uvmat('ERROR',['Binary ' Param.xml.(bin_name{1}) ' defined in PARAM.xml does not exist'])
1066                return
1067            end
1068        else
1069            [path,name,ext]=fileparts(Param.xml.(bin_name{1}));
1070            currentdir=pwd;
1071            cd(path);
1072            binpath=pwd;%path of the binary
1073            Param.xml.(bin_name{1})=fullfile(binpath,[name ext]);
1074            cd(currentdir);
1075        end
1076       
1077    end
1078end
1079display('files OK, processing...')
1080
1081%% set the list of files and check them
1082display('checking the files...')
1083[ref_i,ref_j,errormsg]=find_ref_indices(handles);
1084if ~isempty(errormsg)
1085    return
1086end
1087[filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,xx,yy,compare]=...
1088    set_civ_filenames(handles,ref_i,ref_j,box_test);
1089Rootbat=fileparts(filecell.nc.civ1{1,1});%output netcdf file (without extention)
1090set(handles.civ,'UserData',filecell);%store for futur use of status callback
1091if isempty(filecell)% (error message displayed in fct set_civ_filenames)
1092    return
1093end
1094nbfield=numel(i1_civ1);
1095nbslice=numel(j1_civ1);
1096
1097%% MAIN LOOP
1098time=get(handles.ImaDoc,'UserData'); %get the set of times
1099super_cmd=[];
1100batch_file_list=[];
1101 
1102for ifile=1:nbfield
1103    for j=1:nbslice
1104        % initiate system command
1105        switch CivMode
1106            case 'CivX'
1107                if isunix % check: necessaire aussi en RUN?
1108                    cmd=['#!/bin/bash \n '...
1109                        '#$ -cwd \n '...
1110                        'hostname && date \n '...
1111                        'umask 002 \n'];%allow writting access to created files for user group
1112                else
1113                    cmd=[];
1114                end
1115            case 'CivAll'
1116                CivAllxml=xmltree;% xml contents,  all parameters
1117                CivAllCmd='';
1118                CivAllxml=set(CivAllxml,1,'name','CivDoc');
1119        end
1120           
1121        % define output file name
1122        if Param.CheckCiv2==1 || Param.CheckFix2==1 || Param.CheckPatch2==1
1123            OutputFile=filecell.nc.civ2{ifile,j};
1124        else
1125            OutputFile=filecell.nc.civ1{ifile,j};
1126        end
1127        OutputFile=regexprep(OutputFile,'.nc','');
1128       
1129        if Param.CheckCiv1
1130            % read image-dependent parameters
1131            Param.Civ1.filename_ima_a=filecell.ima1.civ1{ifile,j};
1132            Param.Civ1.filename_ima_b=filecell.ima2.civ1{ifile,j};
1133            if size(time,1)>=i2_civ1(ifile) && size(time,2)>=j2_civ1(j)
1134                Param.Civ1.Dt=(time(i2_civ1(ifile),j2_civ1(j))-time(i1_civ1(ifile),j1_civ1(j)));
1135                Param.Civ1.T0=((time(i2_civ1(ifile),j2_civ1(j))+time(i1_civ1(ifile),j1_civ1(j)))/2);
1136            else
1137                Param.Civ1.Dt=1;
1138                Param.Civ1.T0=0;
1139            end
1140            Param.Civ1.term_a=num2stra(j1_civ1(j),nom_type_nc);%UTILITE?
1141            Param.Civ1.term_b=num2stra(j2_civ1(j),nom_type_nc);%
1142            Param.Civ1.pxcmx=1; %velocities are expressed in pixel dispalcement
1143            Param.Civ1.pxcmy=1;     
1144            Param.Civ1.ImageInfo=imfinfo(filecell.ima1.civ1{1,1});%read the first image to get the size
1145           
1146            %TODO : civ should not need npx and npy
1147           
1148            % read mask parameters
1149            if Param.Civ1.CheckMask % the lines below should be changed with the new gui
1150                %matbe they when check_mask the Maskname is read
1151                if exist(Param.Civ1.MaskName,'file')
1152                    Param.Civ1.MaskFlag='y';
1153                else
1154                    maskbase=[filecell.filebase '_' Param.Civ1.MaskName]; %
1155                    nbslice_mask=str2double(maskdispl(1:end-4)); %
1156                    i1_mask=mod(i1_civ1(ifile)-1,nbslice_mask)+1;
1157                    Param.Civ1.MaskName=name_generator(maskbase,i1_mask,1,'.png','_i');
1158                    if exist(Param.Civ1.MaskName,'file')
1159                        Param.Civ1.maskflag='y';
1160                    else
1161                        Param.Civ1.MaskName='noFile use default';
1162                        Param.Civ1.MaskFlag='n';
1163                    end
1164                end
1165            else
1166                Param.Civ1.MaskName='noFile use default';
1167                Param.Civ1.MaskFlag='n';
1168            end
1169           
1170            % read grid parameters
1171            if Param.Civ1.CheckGrid
1172%                 Param.Civ1.GridFlag='y';
1173                if isequal(Param.Civ1.GridName(end-3:end),'grid')
1174                    nbslice_grid=str2double(Param.Civ1.GridName(1:end-4)); %
1175                    if ~isnan(nbslice_grid)
1176                        i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
1177                        Param.Civ1.GridName=[filecell.filebase '_' name_generator(Param.Civ1.GridName,i1_grid,1,'.grid','_i')];
1178                        if ~exist(Param.Civ1.GridName,'file')
1179                            msgbox_uvmat('ERROR','grid file absent for civ1')
1180                        end
1181                    elseif ~exist(Param.Civ1.GridName,'file')
1182                        msgbox_uvmat('ERROR','grid file absent for civ1')
1183                    end
1184                end
1185%            else
1186%                 Param.Civ1.GridName='noFile use default';
1187%                 Param.Civ1.GridFlag='n';
1188            end
1189           
1190            % send command
1191            switch CivMode
1192                case 'CivX'
1193                    cmd=[cmd...
1194                        cmd_civ1(filecell.nc.civ1{ifile,j},Param) '\n'];
1195                case 'CivAll'
1196                    CivAllCmd=[CivAllCmd ' civ1 '];
1197                    str=CIV1_CMD_Unified(filecell.nc.civ1{ifile,j},'',Param.Civ1);
1198                    fieldnames=fields(str);
1199                    [CivAllxml,uid_civ1]=add(CivAllxml,1,'element','civ1');
1200                    for ilist=1:length(fieldnames)
1201                        val=eval(['str.' fieldnames{ilist}]);
1202                        if ischar(val)
1203                            [CivAllxml,uid_t]=add(CivAllxml,uid_civ1,'element',fieldnames{ilist});
1204                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1205                        end
1206                    end
1207            end
1208        end
1209       
1210        if Param.CheckFix1
1211            switch CivMode
1212                case 'CivX'
1213                    cmd=[cmd...
1214                        cmd_fix(filecell.nc.civ1{ifile,j},Param,'Fix1') '\n'];
1215                case 'CivAll'%to abandon
1216                    fix1.inputFileName=filecell.nc.civ1{ifile,j} ;
1217                    fix1.fi1=num2str(param.fix1.flagindex1(1));
1218                    fix1.fi2=num2str(param.fix1.flagindex1(2));
1219                    fix1.fi3=num2str(param.fix1.flagindex1(3));
1220                    fix1.threshC=num2str(param.fix1.thresh_vecC1);
1221                    fix1.threshV=num2str(param.fix1.thresh_vel1);
1222                    fieldnames=fields(fix1);
1223                    [CivAllxml,uid_fix1]=add(CivAllxml,1,'element','fix1');
1224                    for ilist=1:length(fieldnames)
1225                        val=eval(['fix1.' fieldnames{ilist}]);
1226                        if ischar(val)
1227                            [CivAllxml,uid_t]=add(CivAllxml,uid_fix1,'element',fieldnames{ilist});
1228                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1229                        end
1230                    end
1231                    CivAllCmd=[CivAllCmd ' fix1 '];
1232            end
1233        end
1234       
1235        %CheckPatch1
1236        if Param.CheckPatch1==1
1237            switch CivMode
1238                case 'CivX'
1239                    cmd=[cmd...
1240                        cmd_patch(filecell.nc.civ1{ifile,j},Param,'Patch1') '\n'];
1241                case 'CivAll'
1242                    patch1.inputFileName=filecell.nc.civ1{ifile,j} ;
1243                    patch1.nopt=subdomain_patch1;
1244                    patch1.maxdiff=thresh_patch1;
1245                    patch1.ro=rho_patch1;
1246                    test_grid=get(handles.get_gridpatch1,'Value');
1247                    if test_grid
1248                        patch1.gridflag='y';
1249                        gridname=get(handles.grid_patch1,'String');
1250                        if isequal(gridname(end-3:end),'grid')
1251                            nbslice_grid=str2double(gridname(1:end-4)); %
1252                            if ~isnan(nbslice_grid)
1253                                i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
1254                                patch1.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
1255                                if ~exist(patch1.gridPatch,'file')
1256                                    msgbox_uvmat('ERROR','grid file absent for patch1')
1257                                end
1258                            elseif exist(gridname,'file')
1259                                patch1.gridPatch=gridname;
1260                            else
1261                                msgbox_uvmat('ERROR','grid file absent for patch1')
1262                            end
1263                        end
1264                    else
1265                        patch1.gridPatch='none';
1266                        patch1.gridflag='n';
1267                        patch1.m=nx_patch1;
1268                        patch1.n=ny_patch1;
1269                    end
1270                    patch1.convectFlow='n';
1271                    fieldnames=fields(patch1);
1272                    [CivAllxml,uid_patch1]=add(CivAllxml,1,'element','patch1');
1273                    for ilist=1:length(fieldnames)
1274                        val=eval(['patch1.' fieldnames{ilist}]);
1275                        if ischar(val)
1276                            [CivAllxml,uid_t]=add(CivAllxml,uid_patch1,'element',fieldnames{ilist});
1277                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1278                        end
1279                    end
1280                    CivAllCmd=[CivAllCmd ' patch1 '];
1281            end
1282        end
1283        if Param.CheckCiv2==1
1284            Param.Civ2.filename_ima_a=filecell.ima1.civ2{ifile,j};
1285            Param.Civ2.filename_ima_b=filecell.ima2.civ2{ifile,j};
1286            if size(time,1)>=i2_civ2(ifile) && size(time,2)>=j2_civ2(j)
1287                Param.Civ2.Dt=num2str(time(i2_civ2(ifile),j2_civ2(j))-time(i1_civ2(ifile),j1_civ2(j)));
1288                Param.Civ2.T0=num2str((time(i2_civ2(ifile),j2_civ2(j))+time(i1_civ2(ifile),j1_civ2(j)))/2);
1289            else
1290                Param.Civ2.Dt=1;
1291                Param.Civ2.T0=0;
1292            end
1293            Param.Civ2.term_a=num2stra(j1_civ2(j),nom_type_nc);
1294            Param.Civ2.term_b=num2stra(j2_civ2(j),nom_type_nc);
1295            Param.Civ2.filename_nc1=filecell.nc.civ1{ifile,j};
1296            Param.Civ2.filename_nc1(end-2:end)=[]; % remove '.nc'
1297            Param.Civ2.pxcmx=1; %velocities are expressed in pixel dispalcement
1298            Param.Civ2.pxcmy=1;
1299            if Param.Civ2.CheckMask
1300                maskdispl=get(handles.txt_Mask,'String');
1301                if exist(maskdispl,'file')
1302                    Param.Civ2.MaskName=maskdispl;
1303                    Param.Civ2.MaskFlag='y';
1304                else
1305                    maskbase=[filecell.filebase '_' maskdispl]; %
1306                    nbslice_mask=str2double(maskdispl(1:end-4)); %
1307                    i1_mask=mod(i1_civ2(ifile)-1,nbslice_mask)+1;
1308                    Param.Civ2.MaskName=name_generator(maskbase,i1_mask,1,'.png','_i');
1309                    if exist(Param.Civ2.MaskName,'file')
1310                        Param.Civ2.MaskFlag='y';
1311                    else
1312                        Param.Civ2.MaskName='noFile use default';
1313                        Param.Civ2.MaskFlag='n';
1314                    end
1315                end
1316            else
1317                Param.Civ2.MaskName='noFile use default';
1318                Param.Civ2.MaskFlag='n';
1319            end
1320            gridname=get(handles.txt_GridName,'String');
1321            if numel(gridname)>=4 && isequal(gridname(end-3:end),'grid')
1322                nbslice_grid=str2double(gridname(1:end-4)); %
1323                if ~isnan(nbslice_grid)
1324                    Param.Civ2.GridFlag='y';
1325                    i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
1326                    Param.Civ2.GridName=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
1327%                     if exist(Param.Civ2.GridName,'file')
1328%                         Param.Civ2.GridFlag='y';
1329%                     else
1330%                         Param.Civ2.GridName='noFile use default';
1331%                         Param.Civ2.GridFlag='n';
1332%                     end
1333                elseif exist(gridname,'file')
1334%                     Param.Civ2.GridFlag='y';
1335%                 else
1336%                     Param.Civ2.GridName='noFile use default';
1337%                     Param.Civ2.GridFlag='n';
1338                end
1339%             else
1340%                 Param.Civ2.GridName='noFile use default';
1341%                 Param.Civ2.GridFlag='n';
1342            end
1343%             A=imread(filecell.ima1.civ2{1,1});%read the first image to get the size
1344%             sizim=size(A);
1345            Param.Civ2.ImageInfo=imfinfo(filecell.ima1.civ2{1,1});%read the first image to get the size
1346            % TODO: case of movie
1347%             Param.Civ2.npx=(sizim(2));
1348%             Param.Civ2.npy=(sizim(1));     
1349            switch CivMode
1350                case 'CivX'
1351                    cmd=[cmd...
1352                        cmd_civ2(filecell.nc.civ2{ifile,j},Param) '\n'];
1353                case 'CivAll'
1354                    CivAllCmd=[CivAllCmd ' civ2 '];
1355                    str=CIV2_CMD_Unified(filecell.nc.civ2{ifile,j},'',Param.Civ2);
1356                    fieldnames=fields(str);
1357                    [CivAllxml,uid_civ2]=add(CivAllxml,1,'element','civ2');
1358                    for ilist=1:length(fieldnames)
1359                        val=eval(['str.' fieldnames{ilist}]);
1360                        if ischar(val)
1361                            [CivAllxml,uid_t]=add(CivAllxml,uid_civ2,'element',fieldnames{ilist});
1362                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1363                        end
1364                    end
1365            end
1366        end
1367       
1368        % CheckFix2
1369        if Param.CheckFix2==1
1370            switch CivMode
1371                case 'CivX'
1372                    cmd=[cmd...
1373                        cmd_fix(filecell.nc.civ2{ifile,j},Param,'Fix2') '\n'];
1374                case 'CivAll'
1375                    fix2.inputFileName=filecell.nc.civ2{ifile,j} ;
1376                    fix2.fi1=num2str(flagindex2(1));
1377                    fix2.fi2=num2str(flagindex2(2));
1378                    fix2.fi3=num2str(flagindex2(3));
1379                    fix2.threshC=num2str(thresh_vec2C);
1380                    fix2.threshV=num2str(thresh_vel2);
1381                    fieldnames=fields(fix2);
1382                    [CivAllxml,uid_fix2]=add(CivAllxml,1,'element','fix2');
1383                    for ilist=1:length(fieldnames)
1384                        val=eval(['fix2.' fieldnames{ilist}]);
1385                        if ischar(val)
1386                            [CivAllxml,uid_t]=add(CivAllxml,uid_fix2,'element',fieldnames{ilist});
1387                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1388                        end
1389                    end
1390                    CivAllCmd=[CivAllCmd ' fix2 '];
1391            end
1392        end
1393       
1394        %CheckPatch2
1395        if Param.CheckPatch2==1
1396           
1397            switch CivMode
1398               
1399                case 'CivX'
1400                    cmd=[cmd...
1401                        cmd_patch(filecell.nc.civ1{ifile,j},Param,'Patch2') '\n'];
1402                   
1403                case 'CivAll'
1404                    patch2.inputFileName=filecell.nc.civ1{ifile,j} ;
1405                    patch2.nopt=subdomain_patch2;
1406                    patch2.maxdiff=thresh_patch2;
1407                    patch2.ro=rho_patch2;
1408                    test_grid=get(handles.get_gridpatch2,'Value');
1409                    if test_grid
1410                        patch2.gridflag='y';
1411                        gridname=get(handles.grid_patch2,'String');
1412                        if isequal(gridname(end-3:end),'grid')
1413                            nbslice_grid=str2double(gridname(1:end-4)); %
1414                            if ~isnan(nbslice_grid)
1415                                i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
1416                                patch2.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
1417                                if ~exist(patch2.gridPatch,'file')
1418                                    msgbox_uvmat('ERROR','grid file absent for patch2')
1419                                end
1420                            elseif exist(gridname,'file')
1421                                patch2.gridPatch=gridname;
1422                            else
1423                                msgbox_uvmat('ERROR','grid file absent for patch2')
1424                            end
1425                        end
1426                    else
1427                        patch2.gridPatch='none';
1428                        patch2.gridflag='n';
1429                        patch2.m=nx_patch2;
1430                        patch2.n=ny_patch2;
1431                    end
1432                    patch2.convectFlow='n';
1433                    fieldnames=fields(patch2);
1434                    [CivAllxml,uid_patch2]=add(CivAllxml,1,'element','patch2');
1435                    for ilist=1:length(fieldnames)
1436                        val=eval(['patch2.' fieldnames{ilist}]);
1437                        if ischar(val)
1438                            [CivAllxml,uid_t]=add(CivAllxml,uid_patch2,'element',fieldnames{ilist});
1439                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1440                        end
1441                    end
1442                    CivAllCmd=[CivAllCmd ' patch2 '];
1443            end
1444        end
1445       
1446        switch CivMode
1447           
1448            case {'CivX','CivAll'}
1449                if isequal(CivMode,'CivAll')
1450                    save(CivAllxml,[OutputFile '.xml']);
1451                    cmd=[cmd sparam.CivBin ' -f ' OutputFile '.xml '  CivAllCmd ' >' OutputFile '.log' '\n'];
1452                end             
1453                % create the .bat file used in run or batch
1454                filename_bat=[OutputFile '.bat'];
1455                [fid,message]=fopen(filename_bat,'w');
1456                if isequal(fid,-1)
1457                    msgbox_uvmat('ERROR', ['creation of .bat file: ' message])
1458                    return
1459                end
1460                fprintf(fid,cmd);
1461                fclose(fid);           
1462                if isunix
1463                    system(['chmod +x ' filename_bat]);
1464                end             
1465                batch_file_list{length(batch_file_list)+1}=filename_bat;
1466               
1467            case 'Matlab'
1468                drawnow
1469                if ~strcmp(compare,'stereo PIV')
1470                    [Data,erromsg]=civ_matlab(Param,filecell.nc.civ1{ifile,j});
1471                    if isempty(errormsg)
1472                        display([filecell.nc.civ1{ifile,j} ' written'])
1473                    else
1474                        msgbox_uvmat('ERROR',errormsg)
1475                    end                 
1476                end
1477        end
1478    end
1479end
1480
1481if batch 
1482    switch batch_mode   
1483       
1484        case 'sge'
1485            for p=1:length(batch_file_list)
1486                cmd=['!qsub -p ' pvalue ' -q civ.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
1487                display(cmd);eval(cmd);
1488            end
1489           
1490        case 'oar_old'
1491                for p=1:length(batch_file_list)
1492                    oar_command=['!oarsub -n CIVX -q nicejob '...
1493                   '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
1494                    '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
1495                display(oar_command);eval(oar_command);
1496                end
1497       case 'oar' %oar-dispatch.pl
1498           
1499                filename_joblist=fullfile(Rootbat,'job_list.txt');
1500                fid=fopen(filename_joblist,'w');
1501                walltime_onejob=600;%seconds
1502                for p=1:length(batch_file_list)
1503                    oar_command=['oarsub -n CIVX '...
1504                   '-E ' regexprep(batch_file_list{p},'\.bat\>','.errors') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.log ')...
1505                        '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
1506                    fprintf(fid,[oar_command '\n']);
1507                end
1508                fclose(fid);
1509                ncores=36;
1510                oar_command=['oarsub -t container -n civx-container '...
1511                    '-l /core=' num2str(ncores)...
1512                    ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13)...
1513                    ' "oar-dispatch -f ' filename_joblist '"'];
1514                filename_oarcommand=fullfile(Rootbat,'oar_command');
1515                fid=fopen(filename_oarcommand,'w');
1516                fprintf(fid,[oar_command '\n']);
1517                fclose(fid);
1518                display(oar_command);
1519                eval(['! . ' filename_oarcommand])
1520               
1521        case 'oar_mpi'
1522                filename_joblist=fullfile(Rootbat,'job_list.txt');
1523                fid=fopen(filename_joblist,'w');
1524
1525                for p=1:length(batch_file_list)
1526                    fprintf(fid,[batch_file_list{p} '\n']);
1527                end
1528                fclose(fid)
1529                text_oarscript=[...
1530                    '#!/bin/bash \n'...
1531                    '#OAR -n Mylauncher \n'...
1532                    '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
1533                    '#OAR -E stderrfile.log \n'...
1534                    '#OAR -O stdoutfile.log \n'...
1535                    '# ========================================================= \n'...
1536                    '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
1537                    '# application for coriolis PIV post-processing. \n'...
1538                    '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
1539                    '# This wrapper assert that the user has the same environment on all the \n'...
1540                    '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
1541                    '# \n'...
1542                    '# REQUIREMENT: \n'...
1543                    '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
1544                    '# If a different location is used, change the line following the comment "Bidouille" \n'...
1545                    '# ========================================================= \n'...
1546                    '#   USER should only modify these 2 lines  \n'...
1547                    'WORKDIR=/home/users/gostiaux/tmp/begou \n'...
1548                    'COMMANDE="/home/users/gostiaux/tmp/begou/mpilauncher  -f ' filename_joblist '" \n'...
1549                    '# ========================================================= \n'...
1550                    '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
1551                    'echo "job starting on: "`hostname` \n'...
1552                    'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
1553                    'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
1554                    '#========== Bidouille ============== \n'...
1555                    'export OMPI_MCA_plm_rsh_agent=$HOME/tmp/begou/oarshmost \n'...
1556                    'cd $WORKDIR \n'...
1557                    'CMD="mpirun -np $NCPUS  -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
1558                    'echo "I run: $CMD"  \n'...
1559                    '$CMD \n'...
1560                    'echo "job ending" \n'...
1561                    ];
1562%                 oarsub -S ./oar.sub
1563                filename_oarscript=fullfile(Rootbat,'oar_command');
1564                fid=fopen(filename_oarscript,'w');
1565                fprintf(fid,[text_oarscript]);
1566                fclose(fid);
1567                eval(['!chmod +x  ' filename_oarscript]);
1568                eval(['!oarsub -S ' filename_oarscript]);
1569               
1570        case 'oar_new' % to be develloped with Patrick Begou
1571                filename_joblist=fullfile(Rootbat,'job_list.txt');
1572                fid=fopen(filename_superbat,'w');
1573                if fid==-1
1574                    msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1575                    return
1576                end
1577                for p=1:length(batch_file_list)
1578                    fprintf(fid,[batch_file_list{p} '\n']);
1579                end
1580                fclose(fid);
1581                walltime=datestr(length(super_cmd)*10/24/60,13);
1582                eval(  ['!oarsub -n CIVX -q nicejob -l "/core=1+{type = ''smalljob''}/licence=1,walltime=' walltime '"   ' filename_superbat]);
1583           oar_modes={'oar-dispatch','mpilauncher'};
1584           text={'Batch processing on servcalcul3 LEGI';...
1585               'Please choose one of the followint modes';...
1586               '* oar-dispatch : jobs in a container';...
1587               '* mpilauncher : one single job using several cores';...
1588               '**********************************'...
1589               };
1590           [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
1591               'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
1592           switch oar_modes{S}
1593               
1594               case 'oar-dispatch' %oar-dispatch.pl
1595                   filename_joblist=fullfile(Rootbat,'job_list.txt');
1596                   fid=fopen(filename_joblist,'w');
1597                   walltime_onejob=600;%seconds
1598                   for p=1:length(batch_file_list)
1599                       oar_command=['oarsub -n CIVX '...
1600                           '-E ' regexprep(batch_file_list{p},'\.bat\>','.errors') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.log ')...
1601                           '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
1602                       fprintf(fid,[oar_command '\n']);
1603                   end
1604                   fclose(fid);
1605                   ncores=36;
1606                   oar_command=['oarsub -t container -n civx-container '...
1607                       '-l /core=' num2str(ncores)...
1608                       ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13)...
1609                       ' "oar-dispatch -f ' filename_joblist '"'];
1610                   filename_oarcommand=fullfile(Rootbat,'oar_command');
1611                   fid=fopen(filename_oarcommand,'w');
1612                   fprintf(fid,[oar_command '\n']);
1613                   fclose(fid);
1614                   display(oar_command);
1615                   eval(['! . ' filename_oarcommand])
1616               case 'mpilauncher'
1617                   filename_joblist=fullfile(Rootbat,'job_list.txt');
1618                   fid=fopen(filename_joblist,'w');
1619                   
1620                   for p=1:length(batch_file_list)
1621                       fprintf(fid,[batch_file_list{p} '\n']);
1622                   end
1623                   fclose(fid)
1624                   text_oarscript=[...
1625                       '#!/bin/bash \n'...
1626                       '#OAR -n Mylauncher \n'...
1627                       '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
1628                       '#OAR -E stderrfile.log \n'...
1629                       '#OAR -O stdoutfile.log \n'...
1630                       '# ========================================================= \n'...
1631                       '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
1632                       '# application for coriolis PIV post-processing. \n'...
1633                       '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
1634                       '# This wrapper assert that the user has the same environment on all the \n'...
1635                       '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
1636                       '# \n'...
1637                       '# REQUIREMENT: \n'...
1638                       '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
1639                       '# If a different location is used, change the line following the comment "Bidouille" \n'...
1640                       '# ========================================================= \n'...
1641                       '#   USER should only modify these 2 lines  \n'...
1642                       'WORKDIR=' pwd ' \n'...
1643                       'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
1644                       '# ========================================================= \n'...
1645                       '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
1646                       'echo "job starting on: "`hostname` \n'...
1647                       'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
1648                       'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
1649                       '#========== Bidouille ============== \n'...
1650                       'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
1651                       'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
1652                       'echo "I run: $CMD"  \n'...
1653                       '$CMD \n'...
1654                       'echo "job ending" \n'...
1655                       ];
1656                   %                 oarsub -S ./oar.sub
1657                   filename_oarscript=fullfile(Rootbat,'oar_command');
1658                   fid=fopen(filename_oarscript,'w');
1659                   fprintf(fid,[text_oarscript]);
1660                   fclose(fid);
1661                   eval(['!chmod +x  ' filename_oarscript]);
1662                   eval(['!oarsub -S ' filename_oarscript]);
1663           end
1664    end
1665else
1666    if ~isequal(CivMode,'Matlab')
1667        filename_superbat=fullfile(Rootbat,'job_list.bat');
1668        fid=fopen(filename_superbat,'w');
1669        if fid==-1
1670            msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1671            return
1672        end
1673        for p=1:length(batch_file_list)
1674            if isunix
1675                fprintf(fid,['sh ' batch_file_list{p} '\n']);
1676            else
1677                fprintf(fid,['@call "' regexprep(filename_bat,'\\','\\\\') '"' '\n']);
1678            end
1679        end
1680        fclose(fid);
1681        if(isunix)
1682            system(['chmod +x ' filename_superbat]);
1683        end
1684        system([filename_superbat ' &']);% execute main commmand
1685    end
1686end
1687
1688
1689%% save interface state
1690if isfield(filecell,'nc')
1691    if isfield(filecell.nc,'civ2')
1692        fileresu=filecell.nc.civ2{1,1};
1693    else
1694        fileresu=filecell.nc.civ1{1,1};
1695    end
1696end
1697[RootPath,RootFile,field_count,str2,str_a,str_b,ext,nom_type,subdir]=name2display(fileresu);
1698namedoc=fullfile(RootPath,subdir,RootFile);
1699detect=1;
1700while detect==1
1701    namefigfull=[namedoc '.fig'];
1702    hh=dir(namefigfull);
1703    if ~isempty(hh)
1704        detect=1;
1705        namedoc=[namedoc '.0'];
1706    else
1707        detect=0;
1708    end
1709end
1710saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
1711
1712%Save info in personal profile (initiate browser next time) TODO
1713MenuFile={};
1714dir_perso=prefdir;
1715profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1716if exist(profil_perso,'file')
1717    hh=load (profil_perso);
1718      if isfield(hh,'MenuFile')
1719          MenuFile=hh.MenuFile;
1720      end
1721      if isfield(filecell.nc,'civ2')
1722          MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
1723      else
1724           MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
1725      end
1726      save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
1727else
1728    MenuFile=filecell.ima1.civ1(1,1);
1729    save (profil_perso,'MenuFile')
1730end
1731
1732%------------------------------------------------------------------------
1733% --- determine the list of reference indices of processing file
1734function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
1735%------------------------------------------------------------------------
1736errormsg=''; %default error message
1737first_i=str2double(get(handles.first_i,'String'));%first index i
1738last_i=str2double(get(handles.last_i,'String'));%last index i
1739incr_i=str2double(get(handles.incr_i,'String'));% increment
1740if isequal(get(handles.first_j,'Visible'),'on')
1741    first_j=str2double(get(handles.first_j,'String'));%first index j
1742    last_j=str2double(get(handles.last_j,'String'));%last index j
1743    incr_j=str2double(get(handles.incr_j,'String'));% increment
1744else
1745    first_j=1;
1746    last_j=1;
1747    incr_j=1;
1748end
1749ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
1750ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
1751if isnan(first_i)||isnan(first_j)
1752    errormsg='first field number not defined';
1753elseif isnan(last_i)||isnan(last_j)
1754    errormsg='last field number not defined';
1755elseif isnan(incr_i)||isnan(incr_j)
1756    errormsg='increment in field number not defined';
1757elseif last_i < first_i || last_j < first_j
1758    errormsg='last field number must be larger than the first one';
1759end
1760
1761%------------------------------------------------------------------------
1762% --- determine the list of filenames and indices needed for launch_job
1763function [filecell,num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2,nom_type_nc,file_ref_fix1,file_ref_fix2,compare]=...
1764    set_civ_filenames(handles,ref_i,ref_j,checkbox)
1765%------------------------------------------------------------------------
1766filecell=[];%default
1767
1768%% get the root names nomenclature and numbers
1769filebase=get(handles.RootName,'String');
1770
1771if isempty(filebase)||isequal(filebase,'')
1772    msgbox_uvmat('ERROR','please open an image with the upper menu option Open/Browse...')
1773    return
1774end
1775
1776%filebase=regexprep(filebase,'\.fsnet','fsnet');% temporary fix for cluster Coriolis
1777filecell.filebase=filebase;
1778
1779browse=get(handles.RootName,'UserData');
1780compare_list=get(handles.ListCompareMode,'String');
1781val=get(handles.ListCompareMode,'Value');
1782compare=compare_list{val};
1783if strcmp(compare,'displacement')
1784    mode='displacement';
1785else
1786    mode_list=get(handles.ListPairMode,'String');
1787    mode_value=get(handles.ListPairMode,'Value');
1788    mode=mode_list{mode_value};
1789end
1790%time=get(handles.RootName,'UserData'); %get the set of times
1791ext_ima=get(handles.ImaExt,'String');
1792nom_type_nc=browse.nom_type_nc;
1793if isfield(browse,'nom_type_ima')
1794    nom_type_ima2=browse.nom_type_ima;
1795end
1796if isempty(nom_type_ima2),nom_type_ima2='1';end; %default
1797if isempty(nom_type_nc),nom_type_nc='_i1-i2';end; %default
1798[num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
1799    find_pair_indices(handles,ref_i,ref_j,mode);
1800%determine the new filebase for 'displacement' ListPairMode (comparison of two series)
1801filebase_B=filebase;% root name of the second field series for stereo
1802if strcmp(compare,'displacement') || strcmp(compare,'stereo PIV')
1803%     test_disp=1;
1804    nom_type_ima1=browse.nom_type_ima_1; %nomenclature type of the second file series
1805    [Path2,Name2]=fileparts(filebase_B);
1806    Path1=Path2;
1807    Name1=get(handles.RootName_1,'String');% root name of the first field series for stereo
1808    filebase_A=fullfile(Path1,Name1);
1809    if length(Name1)>6
1810        Name1=Name1(end-5:end);
1811    end
1812    if length(Name2)>6
1813        Name2=Name2(end-5:end);
1814    end
1815    filebase_AB=fullfile(Path2,[Name2 '-' Name1]);
1816else
1817%     test_disp=0;
1818    filebase_A=filebase;
1819    nom_type_ima1=nom_type_ima2;
1820    filebase_AB=filebase;
1821end
1822if strcmp(compare,'displacement')
1823    filebase_ima1=filebase_A;
1824    filebase_ima2=filebase_B;
1825    filebase_nc=filebase_AB; %root name for the result of civ2
1826else
1827    filebase_ima1=filebase_B;
1828    filebase_ima2=filebase_B;
1829    filebase_nc=filebase_B;
1830end
1831
1832%determine reference files for fix:
1833file_ref_fix1={};%default
1834file_ref_fix2={};
1835nbfield=length(num1_civ1);
1836nbslice=length(num_a_civ1);
1837if checkbox(2)==1% fix1 performed
1838    ref=get(handles.ref_fix1,'UserData');%read data on the ref file stored by get_ref_fix1_Callback
1839    if ~isempty(ref)
1840        first_i=str2double(get(handles.first_i,'String'));
1841        last_i=str2double(get(handles.last_i,'String'));
1842        incr_i=str2double(get(handles.incr_i,'String'));
1843        first_j=str2double(get(handles.first_j,'String'));
1844        last_j=str2double(get(handles.last_j,'String'));
1845        incr_j=str2double(get(handles.incr_j,'String'));
1846        num_i_ref=first_i:incr_i:last_i;
1847        num_j_ref=first_j:incr_j:last_j;
1848        if isequal(mode,'displacement')
1849            num_i1=num_i_ref;
1850            num_i2=num_i_ref;
1851            num_j1=num_j_ref;
1852            num_j2=num_j_ref;
1853        elseif isequal(mode,'pair j1-j2')% isequal(mode,'st_pair j1-j2')
1854            num_i1=num_i_ref;
1855            num_i2=num_i1;
1856            num_j1=ref.num_a*ones(size(num_i_ref));
1857            num_j2=ref.num_b*ones(size(num_i_ref));
1858        elseif isequal(mode,'series(Di)') % isequal(mode,'st_series(Di)')
1859            delta1=floor((ref.num2-ref.num1)/2);
1860            delta2=ceil((ref.num2-ref.num1)/2);
1861            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
1862            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
1863            if isempty(ref.num_a)
1864                ref.num_a=1;
1865            end
1866            num_j1=ref.num_a*ones(size(num_i1));
1867            num_j2=num_j1;
1868        elseif isequal(mode,'series(Dj)')%| isequal(mode,'st_series(Dj)')
1869            delta1=floor((ref.num_b-ref.num_a)/2);
1870            delta2=ceil((ref.num_b-ref.num_a)/2);
1871            num_i1=ref.num1*ones(size(num_i_ref));
1872            num_i2=num_i1;
1873            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
1874            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
1875        end
1876        for ifile=1:nbfield
1877            for j=1:nbslice
1878                file_ref=name_generator(ref.filebase,num_i1(ifile),num_j1(j),'.nc',ref.nom_type,1,num_i2(ifile),num_j2(j),ref.subdir);%
1879                file_ref_fix1(ifile,j)={file_ref};
1880                if ~exist(file_ref,'file')
1881                    msgbox_uvmat('ERROR',['reference file ' file_ref ' not found for fix1'])
1882                    filecell=[];
1883                    return
1884                end
1885            end
1886        end
1887    end
1888end
1889
1890%determine reference files for checkfix2:
1891if checkbox(5)==1% fix2 performed
1892    ref=get(handles.ref_fix2,'UserData');
1893    if ~isempty(ref)
1894        first_i=str2double(get(handles.first_i,'String'));
1895        last_i=str2double(get(handles.last_i,'String'));
1896        incr_i=str2double(get(handles.incr_i,'String'));
1897        first_j=str2double(get(handles.first_j,'String'));
1898        last_j=str2double(get(handles.last_j,'String'));
1899        incr_j=str2double(get(handles.incr_j,'String'));
1900        num_i_ref=first_i:incr_i:last_i;
1901        num_j_ref=first_j:incr_j:last_j;
1902        if isequal(mode,'displacement')
1903            num_i1=num_i_ref;
1904            num_i2=num_i_ref;
1905            num_j1=num_j_ref;
1906            num_j2=num_j_ref;
1907        elseif isequal(mode,'pair j1-j2')
1908            num_i1=num_i_ref;
1909            num_i2=num_i1;
1910            num_j1=ref.num_a;
1911            num_j2=ref.num_b;
1912        elseif isequal(mode,'series(Di)')
1913            delta1=floor((ref.num2-ref.num1)/2);
1914            delta2=ceil((ref.num2-ref.num1)/2);
1915            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
1916            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
1917            num_j1=ref.num_a*ones(size(num_i1));
1918            num_j2=num_j1;
1919        elseif isequal(mode,'series(Dj)')
1920            delta1=floor((ref.num_b-ref.num_a)/2);
1921            delta2=ceil((ref.num_b-ref.num_a)/2);
1922            num_i1=ref.num1*ones(size(num_i_ref));
1923            num_i2=num_i1;
1924            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
1925            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
1926        end
1927        for ifile=1:nbfield
1928            for j=1:nbslice
1929                file_ref=name_generator(ref.filebase,num_i1(ifile),num_j1(j),'.nc',ref.nom_type,1,num_i2(ifile),num_j2(j),ref.subdir);%
1930                file_ref_fix2(ifile,j)={file_ref};
1931                if ~exist(file_ref,'file')
1932                    msgbox_uvmat('ERROR',['reference file ' file_ref ' not found for fix2'])
1933                    filecell={};
1934                    return
1935                end
1936            end
1937        end
1938    end
1939end
1940
1941%check dir
1942subdir_civ1=get(handles.txt_SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf output data
1943subdir_civ2=get(handles.txt_SubdirCiv2,'String');
1944if isequal(subdir_civ1,''),subdir_civ1='CIV'; end% put default subdir
1945if isequal(subdir_civ2,''),subdir_civ2=subdir_civ1; end% put default subdir
1946% currentdir=pwd;%store the current working directory
1947[Path_ima,Name]=fileparts(filebase);%Path of the image files (.civ)
1948if ~exist(Path_ima,'dir')
1949    msgbox_uvmat('ERROR',['path to images ' Path_ima ' not found'])
1950    filecell={};
1951    return
1952end
1953[xx,message]=fileattrib(Path_ima);
1954if ~isempty(message) && ~isequal(message.UserWrite,1)
1955    msgbox_uvmat('ERROR',['No writting access to ' Path_ima])
1956    filecell={};
1957%     cd(currentdir);
1958    return
1959end
1960
1961%check the existence of the netcdf and image files involved
1962% %%%%%%%%%%%%  case CheckCiv1 activated   %%%%%%%%%%%%%
1963if checkbox(1)==1;
1964    detect=1;
1965    vers=0;
1966    subdir_civ1_new=subdir_civ1;
1967    while detect==1 %create a new subdir if the netcdf files already exist
1968        for ifile=1:nbfield
1969            for j=1:nbslice
1970                filename=name_generator(filebase_nc,num1_civ1(ifile),num_a_civ1(j),'.nc',nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1_new);
1971                detect=exist(filename,'file')==2;
1972                if detect% if a netcdf file already exists
1973                    indstr=regexp(subdir_civ1_new,'\D');
1974                    if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
1975                        vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
1976                        subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
1977                    else
1978                        vers=vers+1;
1979                        subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) '_' num2str(vers)];       
1980                    end
1981                    subdir_civ2=subdir_civ1_new;
1982                    break
1983                end
1984                filecell.nc.civ1(ifile,j)={filename};
1985            end
1986            if detect% if a netcdf file already exists
1987                break
1988            end
1989        end
1990 
1991        %create the new txt_SubdirCiv1
1992        if ~exist(fullfile(Path_ima,subdir_civ1_new),'dir')
1993%             cd(Path_ima);         
1994            [xx,msg1]=mkdir(fullfile(Path_ima,subdir_civ1_new));
1995
1996            if ~strcmp(msg1,'')
1997                msgbox_uvmat('ERROR',['cannot create ' subdir_civ1_new ': ' msg1])%error message for directory creation
1998                filecell={};
1999                return
2000            elseif isunix         
2001                [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2002                if ~strcmp(msg2,'')
2003                    msgbox_uvmat('ERROR',['pb of permission for  ' fullfile(Path_ima,subdir_civ1_new) ': ' msg2])%error message for directory creation
2004                    filecell={};
2005                    return
2006                end
2007            end
2008%             cd(currentdir);
2009        end
2010        if strcmp(compare,'stereo PIV')&&(strcmp(mode,'pair j1-j2')||strcmp(mode,'series(Dj)')||strcmp(mode,'series(Di)'))%check second nc series
2011            for ifile=1:nbfield
2012                for j=1:nbslice
2013                    filename=name_generator(filebase_A,num1_civ1(ifile),num_a_civ1(j),'.nc',nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1_new);%
2014                    detect=exist(filename,'file')==2;
2015                    if detect% if a netcdf file already exists
2016                       indstr=regexp(subdir_civ1_new,'\D');
2017                       if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
2018                           vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
2019                           subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
2020                       else
2021                           vers=vers+1;
2022                           subdir_civ1_new=[subdir_civ1_new '_' num2str(vers)];
2023                       end
2024                       subdir_civ2=subdir_civ1;
2025                       break
2026                    end
2027                    filecell.ncA.civ1(ifile,j)={filename};
2028                end
2029                if detect% if a netcdf file already exists
2030                    break
2031                end
2032            end
2033            %create the new txt_SubdirCiv1
2034            if ~exist(fullfile(Path_ima,subdir_civ1_new),'dir')
2035%                    cd(Path_ima);         
2036                [xx,msg1]=mkdir(fullfile(Path_ima,subdir_civ1_new));
2037%                             cd(currentdir);
2038                if ~strcmp(msg1,'')
2039                    msgbox_uvmat('ERROR',['cannot create ' subdir_civ1_new ': ' msg1])
2040%                     cd(currentdir)
2041                    filecell={};
2042                    return
2043                else
2044                    [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2045                    if ~strcmp(msg2,'')
2046                        msgbox_uvmat('ERROR',['pb of permission for ' subdir_civ1_new ': ' msg2])%error message for directory creation
2047%                         cd(currentdir)
2048                        filecell={};
2049                        return
2050                    end
2051                end
2052            end
2053        end
2054    end
2055    subdir_civ1=subdir_civ1_new;
2056    % get image names
2057    for ifile=1:nbfield
2058        for j=1:nbslice
2059            filename=name_generator(filebase_ima1, num1_civ1(ifile),num_a_civ1(j),ext_ima,nom_type_ima1);
2060            idetect(j)=exist(filename,'file')==2;
2061            filecell.ima1.civ1(ifile,j)={filename}; %first image
2062            filename=name_generator(filebase_ima2, num2_civ1(ifile),num_b_civ1(j),ext_ima,nom_type_ima2);
2063            idetect_1(j)=exist(filename,'file')==2;
2064            filecell.ima2.civ1(ifile,j)={filename};%second image
2065        end
2066        [idetectmin,indexj]=min(idetect);
2067        if idetectmin==0,
2068            msgbox_uvmat('ERROR',[filecell.ima1.civ1{ifile,indexj} ' not found'])
2069            filecell={};
2070           % cd(currentdir)
2071            return
2072        end
2073        [idetectmin,indexj]=min(idetect_1);
2074        if idetectmin==0,
2075            msgbox_uvmat('ERROR',[filecell.ima2.civ1{ifile,indexj} ' not found'])
2076            filecell={};
2077            %cd(currentdir)
2078            return
2079        end
2080    end
2081    if strcmp(compare,'stereo PIV') && (strcmp(mode,'pair j1-j2') || strcmp(mode,'series(Dj)') || strcmp(mode,'series(Di)'))
2082        for ifile=1:nbfield
2083            for j=1:nbslice
2084                filename=name_generator(filebase_A, num1_civ1(ifile),num_a_civ1(j),ext_ima,nom_type_ima1);
2085                idetect(j)=exist(filename,'file')==2;
2086                filecell.imaA1.civ1(ifile,j)={filename} ;%first image
2087                filename=name_generator(filebase_A, num2_civ1(ifile),num_b_civ1(j),ext_ima,nom_type_ima2);
2088                idetect_1(j)=exist(filename,'file')==2;
2089                filecell.imaA2.civ1(ifile,j)={filename};%second image
2090            end
2091            [idetectmin,indexj]=min(idetect);
2092            if idetectmin==0,
2093                msgbox_uvmat('ERROR',[filecell.imaA1.civ1{ifile,indexj} ' not found'])
2094                filecell={};
2095               % cd(currentdir)
2096                return
2097            end
2098            [idetectmin,indexj]=min(idetect_1);
2099            if idetectmin==0,
2100                msgbox_uvmat('ERROR',[filecell.imaA2.civ1{ifile,indexj} ' not found'])
2101                filecell={};
2102               % cd(currentdir)
2103                return
2104            end
2105        end
2106    end
2107   
2108    %%%%%%%%%%%%%  checkfix1 or checkpatch1 activated but no checkciv1   %%%%%%%%%%%%%
2109elseif (checkbox(2)==1 || checkbox(3)==1);
2110    for ifile=1:nbfield
2111        for j=1:nbslice
2112            filename=name_generator(filebase_nc,num1_civ1(ifile),num_a_civ1(j),'.nc',...
2113                nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1);%
2114            detect=exist(filename,'file')==2;
2115            if detect==0
2116                msgbox_uvmat('ERROR',[filename ' not found'])
2117                filecell={};
2118               % cd(currentdir)
2119                return
2120            end
2121            filecell.nc.civ1(ifile,j)={filename};
2122        end
2123    end
2124    if strcmp(compare,'stereo PIV')
2125        for ifile=1:nbfield
2126            for j=1:nbslice
2127                filename=name_generator(filebase_A,num1_civ1(ifile),num_a_civ1(j),'.nc',nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1);%
2128                filecell.ncA.civ1(ifile,j)={filename};
2129                if ~exist(filename,'file')
2130                    msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2131                    set(handles.RUN, 'Enable','On')
2132                    set(handles.RUN,'BackgroundColor',[1 0 0])
2133                    filecell={};
2134                    %cd(currentdir)
2135                    return
2136                end
2137            end
2138        end
2139    end
2140end
2141
2142%%%%%%%%%%%%%  if checkciv2 performed with pairs different than checkciv1  %%%%%%%%%%%%%
2143testdiff=0;
2144if (checkbox(4)==1)&&...
2145        ((get(handles.ListPairCiv1,'Value')~=get(handles.ListPairCiv2,'Value'))||~strcmp(subdir_civ2,subdir_civ1))
2146    testdiff=1;
2147    detect=1;
2148    vers=0;
2149    subdir_civ2_new=subdir_civ2;
2150    while detect==1 %create a new subdir if the netcdf files already exist
2151        for ifile=1:nbfield
2152            for j=1:nbslice
2153                filename=name_generator(filebase_nc,num1_civ2(ifile),num_a_civ2(j),'.nc',nom_type_nc,1,num2_civ2(ifile),num_b_civ2(j),subdir_civ2_new);%
2154                detect=exist(filename,'file')==2;
2155                if detect% if a netcdf file already exists
2156                    indstr=regexp(subdir_civ2,'\D');
2157                    if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2158                        vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2159                        subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2160                    else
2161                        vers=vers+1;
2162                        subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2163                    end
2164                    break
2165                end
2166                filecell.nc.civ2(ifile,j)={filename};
2167            end
2168            if detect% if a netcdf file already exists
2169                break
2170            end
2171        end
2172        %create the new subdir_civ2_new
2173        if ~exist(fullfile(Path_ima,subdir_civ2_new),'dir')
2174            [xx,m2]=mkdir(fullfile(Path_ima,subdir_civ2_new));
2175            [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2176            if ~isequal(m2,'')
2177                msgbox_uvmat('ERROR',['cannot create ' fullfile(Path_ima,subdir_civ2_new) ': ' m2])
2178                filecell={};
2179               % cd(currentdir)
2180                return
2181            end
2182        end
2183        if strcmp(compare,'stereo PIV')%check second nc series
2184            for ifile=1:nbfield
2185                for j=1:nbslice
2186                    filename=name_generator(filebase_A,num1_civ2(ifile),num_a_civ2(j),'.nc',...
2187                        nom_type_nc,1,num2_civ2(ifile),num_b_civ1(j),subdir_civ2_new);%
2188                    detect=exist(filename,'file')==2;
2189                    if detect% if a netcdf file already exists
2190                        indstr=regexp(subdir_civ2,'\D');
2191                        if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2192                           vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2193                           subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2194                        else
2195                           vers=vers+1;
2196                           subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2197                        end
2198                        break
2199                    end
2200                    filecell.ncA.civ2(ifile,j)={filename};
2201                end
2202                if detect% if a netcdf file already exists
2203                    break
2204                end
2205            end
2206            subdir_civ2=subdir_civ2_new;
2207            %create the new txt_SubdirCiv1
2208            if ~exist(fullfile(Path_ima,subdir_civ2_new),'dir')
2209                [xx,m2]=mkdir(subdir_civ2_new);
2210                 [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2211                if ~isequal(m2,'')
2212                    msgbox_uvmat('ERROR', ['cannot create ' fullfile(Path_ima,subdir_civ2_new) ': ' m2])%error message for directory creation
2213                  %  cd(currentdir)
2214                    filecell={};
2215                    return
2216                end
2217            end
2218        end
2219    end
2220    subdir_civ2=subdir_civ2_new;
2221end
2222%cd(currentdir);%come back to the current working directory
2223
2224%%%%%%%%%%%%%  if checkciv2 results are obtained or used  %%%%%%%%%%%%%
2225if checkbox(4)==1 || checkbox(5)==1 || checkbox(6)==1 %civ2
2226    %check source netcdf file of checkciv1 estimates
2227    if checkbox(1)==0; %no civ1 performed
2228        for ifile=1:nbfield
2229            for j=1:nbslice
2230                filename=name_generator(filebase_nc,num1_civ1(ifile),num_a_civ1(j),'.nc',...
2231                    nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1);%
2232                filecell.nc.civ1(ifile,j)={filename};% name of the civ1 file
2233                if ~exist(filename,'file')
2234                    msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2235                    filecell={};
2236                    return
2237                end
2238                if ~testdiff % civ2 or patch2 are written in the same file as civ1
2239                    if checkbox(4)==0 ; %check the existence of civ2 if it is not calculated
2240                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2241                        if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2242                            msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2243                            filecell=[];
2244                            return
2245                        elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2246                            msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2247                            filecell=[];
2248                            return
2249                        end
2250                    elseif checkbox(3)==0; %check the existence of patch if it is not calculated
2251                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','patch');
2252                        if ~isempty(Data.CivStage)
2253                            if Data.CivStage<3 %test for civ files
2254                                msgbox_uvmat('ERROR',['no patch data in ' filename])
2255                                filecell=[];
2256                                return
2257                            end
2258                        elseif isempty(Data.patch)||isequal(Data.patch,0)
2259                            msgbox_uvmat('ERROR',['no patch data in ' filename])
2260                            filecell=[];
2261                            return
2262                        end
2263                    end
2264                end
2265            end
2266        end
2267        if strcmp(compare,'stereo PIV')
2268            for ifile=1:nbfield
2269                for j=1:nbslice
2270                    filename=name_generator(filebase_A,num1_civ2(ifile),num_a_civ2(j),'.nc',...
2271                        nom_type_nc,1,num2_civ2(ifile),num_b_civ2(j),subdir_civ2);%
2272                    filecell.ncA.civ2(ifile,j)={filename};
2273                    if ~exist(filename,'file')
2274                        msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2275                        set(handles.RUN, 'Enable','On')
2276                        set(handles.RUN,'BackgroundColor',[1 0 0])
2277                        return
2278                    end
2279                end
2280            end
2281        end
2282    end
2283   
2284    detect=1;
2285    %     while detect==1%creates a new subdir if the netcdf files already contain checkciv2 data
2286    for ifile=1:nbfield
2287        for j=1:nbslice
2288            filename=name_generator(filebase_nc,num1_civ2(ifile),num_a_civ2(j),'.nc',...
2289                nom_type_nc,1,num2_civ2(ifile),num_b_civ2(j),subdir_civ2);
2290            detect=exist(filename,'file')==2;
2291            filecell.nc.civ2(ifile,j)={filename};
2292        end
2293    end
2294    %get first image names for checkciv2
2295    if checkbox(1)==1 && isequal(num1_civ1,num1_civ2) && isequal(num_a_civ1,num_a_civ2)
2296        filecell.ima1.civ2=filecell.ima1.civ1;
2297    elseif checkbox(4)==1
2298        for ifile=1:nbfield
2299            for j=1:nbslice
2300                filename=name_generator(filebase_ima1, num1_civ2(ifile),num_a_civ2(j),ext_ima,nom_type_ima1);
2301                idetect_2(j)=exist(filename,'file')==2;
2302                filecell.ima1.civ2(ifile,j)={filename};%first image
2303            end
2304            [idetectmin,indexj]=min(idetect_2);
2305            if idetectmin==0,
2306                msgbox_uvmat('ERROR',['input image ' filecell.ima1.civ2{ifile,indexj} ' not found'])
2307                filecell=[];
2308                return
2309            end
2310        end
2311    end
2312   
2313    %get second image names for checkciv2
2314    if checkbox(1)==1 && isequal(num2_civ1,num2_civ2) && isequal(num_b_civ1,num_b_civ2)
2315        filecell.ima2.civ2=filecell.ima2.civ1;
2316    elseif checkbox(4)==1
2317        for ifile=1:nbfield
2318            for j=1:nbslice
2319                filename=name_generator(filebase_ima2, num2_civ2(ifile),num_b_civ2(j),ext_ima,nom_type_ima2);
2320                idetect_3(j)=exist(filename,'file')==2;
2321                filecell.ima2.civ2(ifile,j)={filename};%first image
2322            end
2323            [idetectmin,indexj]=min(idetect_3);
2324            if idetectmin==0,
2325                msgbox_uvmat('ERROR',['input image ' filecell.ima2.civ2{ifile,indexj} ' not found'])
2326                filecell=[];
2327                return
2328            end
2329        end
2330    end
2331end
2332if (checkbox(5) || checkbox(6)) && ~checkbox(4)  % need to read an existing netcdf civ2 file
2333    if ~testdiff
2334        filecell.nc.civ2=filecell.nc.civ1;% file already checked
2335    else     % check the civ2 files
2336        for ifile=1:nbfield
2337            for j=1:nbslice
2338                filename=name_generator(filebase_nc,num1_civ2(ifile),num_a_civ2(j),'.nc',...
2339                    nom_type_nc,1,num2_civ2(ifile),num_b_civ2(j),subdir_civ2);%
2340                filecell.nc.civ2(ifile,j)={filename};
2341                if ~exist(filename,'file')
2342                    msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2343                    filecell=[];
2344                    return
2345                else
2346                    Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2347                    if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2348                            msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2349                            filecell=[];
2350                            return
2351                    elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2352                        msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2353                        filecell=[];
2354                        return
2355                    end
2356                end
2357            end
2358        end
2359    end
2360end
2361
2362%%%%%%%%%%%%%  if stereo fields are calculated by PATCH %%%%%%%%%%%%%
2363if strcmp(compare,'stereo PIV')
2364    if  checkbox(3) && isequal(get(handles.test_stereo1,'Value'),1)
2365        for ifile=1:nbfield
2366            for j=1:nbslice
2367                filename=name_generator(filebase_AB,num1_civ1(ifile),num_a_civ1(j),'.nc',...
2368                    nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1);%
2369                filecell.st(ifile,j)={filename};
2370            end
2371        end
2372    end
2373    if  checkbox(6) && isequal(get(handles.CheckStereo,'Value'),1)
2374        for ifile=1:nbfield
2375            for j=1:nbslice
2376                filename=name_generator(filebase_AB,num1_civ2(ifile),num_a_civ2(j),'.nc',...
2377                    nom_type_nc,1,num2_civ2(ifile),num_b_civ2(j),subdir_civ2);%
2378                filecell.st(ifile,j)={filename};
2379            end
2380        end
2381    end
2382end
2383set(handles.txt_SubdirCiv1,'String',subdir_civ1);%update the edit box
2384set(handles.txt_SubdirCiv2,'String',subdir_civ2);%update the edit box
2385browse.nom_type_nc=nom_type_nc;
2386set(handles.RootName,'UserData',browse); %update the nomenclature type for uvmat
2387
2388
2389%COPY IMAGES TO THE FORMAT .png IF NEEDED
2390if isequal(nom_type_ima1,'*')%case of movie files
2391    nom_type_imanew1='_i';
2392else
2393    nom_type_imanew1=nom_type_ima1;
2394end
2395if isequal(nom_type_ima2,'*')%case of movie files
2396    nom_type_imanew2='_i';
2397else
2398    nom_type_imanew2=nom_type_ima2;
2399end
2400if ~isequal(ext_ima,'.png')
2401    %%type of image file
2402    type_ima1='none';%default
2403    movieobject1=[];%default
2404    if strcmpi(ext_ima,'.avi')
2405        hhh=which('mmreader');
2406        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()% if the mmreader function is found (recent version of matlab)
2407            type_ima1='movie';
2408            movieobject1=mmreader([filebase_ima2 ext_ima]);
2409        else
2410            type_ima1='avi';
2411        end
2412    elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2413        form=imformats(ext_ima(2:end));
2414        if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2415            if isequal(nom_type_ima1,'*');
2416                type_ima1='multimage';%image series in a single image file
2417            else
2418                type_ima1='image';
2419            end
2420        end
2421    end
2422    type_ima2='none';%default
2423    movieobject2=[];
2424    if strcmpi(ext_ima,'.avi')
2425        hhh=which('mmreader');
2426        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()% if the mmreader function is found (recent version of matlab)
2427            type_ima2='movie';
2428            movieobject2=mmreader([filebase_ima2 ext_ima]);
2429        else
2430            type_ima2='avi';
2431        end
2432    elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2433        form=imformats(ext_ima(2:end));
2434        if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2435            if isequal(nom_type_ima1,'*');
2436                type_ima2='multimage';%image series in a single image file
2437            else
2438                type_ima2='image';
2439            end
2440        end
2441    end
2442    %npxy=get(handles.ImaExt,'UserData');
2443    % %     if numel(npxy)<2
2444    %
2445    %         filename=name_generator(filebase_ima1,num1_civ1(1),num_a_civ1(1),ImaExt,nom_type_ima1);
2446    %         A=imread(filename);
2447    %         npxy=size(A);
2448    % %     end
2449    %     npy=npxy(1);
2450    %     npx=npxy(2);
2451    if checkbox(1) %if civ1 is performed
2452        h = waitbar(0,'copy images to the .png format for civ1');% display a wait bar
2453        for ifile=1:nbfield
2454            waitbar(ifile/nbfield);
2455            for j=1:nbslice
2456                filename=name_generator(filebase_ima1,num1_civ1(ifile),num_a_civ1(j),'.png',nom_type_imanew1);
2457                if ~exist(filename,'file')
2458                    A=read_image(filecell.ima1.civ1{ifile,j},type_ima1,num1_civ1(ifile),movieobject1);
2459                    imwrite(A,filename,'BitDepth',16);
2460                end
2461                filecell.ima1.civ1(ifile,j)={filename};
2462                filename=name_generator(filebase_ima2, num2_civ1(ifile),num_b_civ1(j),'.png',nom_type_imanew2);
2463                if ~exist(filename,'file')
2464                    A=read_image(filecell.ima2.civ1{ifile,j},type_ima2,num2_civ1(ifile),movieobject2);
2465                    imwrite(A,filename,'BitDepth',16);
2466                end
2467                filecell.ima2.civ1(ifile,j)={filename};
2468            end
2469        end
2470        close(h)
2471    end
2472    if checkbox(4) %if civ2 is performed
2473        h = waitbar(0,'copy images to the .png format for civ2');% display a wait bar
2474        for ifile=1:nbfield
2475            waitbar(ifile/nbfield);
2476            for j=1:nbslice
2477                filename=name_generator(filebase_ima1,num1_civ2(ifile),num_a_civ2(j),'.png',nom_type_imanew1);
2478                if ~exist(filename,'file')
2479                    A=read_image(cell2mat(filecell.ima1.civ2(ifile,j)),type_ima2,num1_civ2(ifile));
2480                    imwrite(A,filename,'BitDepth',16);
2481                end
2482                filecell.ima1.civ2(ifile,j)={filename};
2483                filename=name_generator(filebase_ima2, num2_civ2(ifile),num_b_civ2(j),'.png',nom_type_imanew2);
2484                if ~exist(filename,'file')
2485                    A=read_image(cell2mat(filecell.ima2.civ2(ifile,j)),type_ima2,num2_civ2(ifile));
2486                    imwrite(A,filename,'BitDepth',16);
2487                end
2488                filecell.ima2.civ2(ifile,j)={filename};
2489            end
2490        end
2491        close(h);
2492    end
2493end
2494
2495%------------------------------------------------------------------------
2496% --- determine the list of index pairs of processing file
2497function [num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
2498    find_pair_indices(handles,ref_i,ref_j,mode)
2499%------------------------------------------------------------------------
2500
2501list_civ1=get(handles.ListPairCiv1,'String');
2502index_civ1=get(handles.ListPairCiv1,'Value');
2503str_civ1=list_civ1{index_civ1};%string defining the image pairs for civ1
2504if isempty(str_civ1)||isequal(str_civ1,'')
2505    msgbox_uvmat('ERROR','no image pair selected for civ1')
2506    return
2507end
2508list_civ2=get(handles.ListPairCiv2,'String');
2509index_civ2=get(handles.ListPairCiv2,'Value');
2510if index_civ2>length(list_civ2)
2511    list_civ2=list_civ1;
2512    index_civ2=index_civ1;
2513end
2514str_civ2=list_civ2{index_civ2};%string defining the image pairs for civ2
2515
2516if isequal (mode,'series(Di)')
2517    lastfield=str2double(get(handles.nb_field,'String'));
2518    num1_civ1=ref_i-floor(index_civ1/2)*ones(size(ref_i));% set of first image numbers
2519    num2_civ1=ref_i+ceil(index_civ1/2)*ones(size(ref_i));
2520    num_a_civ1=ref_j;
2521    num_b_civ1=ref_j;
2522    num1_civ2=ref_i-floor(index_civ2/2)*ones(size(ref_i));
2523    num2_civ2=ref_i+ceil(index_civ2/2)*ones(size(ref_i));
2524    num_a_civ2=ref_j;
2525    num_b_civ2=ref_j;   
2526   
2527    % adjust the first and last field number
2528    lastfield=str2double(get(handles.nb_field,'String'));
2529    if isnan(lastfield)
2530        indsel=find((num1_civ1 >= 1)&(num1_civ2 >= 1));
2531    else
2532        indsel=find((num2_civ1 <= lastfield)&(num2_civ2 <= lastfield)&(num1_civ1 >= 1)&(num1_civ2 >= 1));
2533    end
2534    if length(indsel)>=1
2535        firstind=indsel(1);
2536        lastind=indsel(end);
2537        set(handles.first_i,'String',num2str(ref_i(firstind)))%update the display of first and last fields
2538        set(handles.last_i,'String',num2str(ref_i(lastind)))
2539        ref_i=ref_i(indsel);
2540        num1_civ1=num1_civ1(indsel);
2541        num1_civ2=num1_civ2(indsel);
2542        num2_civ1=num2_civ1(indsel);
2543        num2_civ2=num2_civ2(indsel);
2544    end
2545elseif isequal (mode,'series(Dj)')
2546    lastfield_j=str2double(get(handles.nb_field2,'String'));
2547    num1_civ1=ref_i;% set of first image numbers
2548    num2_civ1=ref_i;
2549    num_a_civ1=ref_j-floor(index_civ1/2)*ones(size(ref_j));
2550    num_b_civ1=ref_j+ceil(index_civ1/2)*ones(size(ref_j));
2551    num1_civ2=ref_i;
2552    num2_civ2=ref_i;
2553    num_a_civ2=ref_j-floor(index_civ2/2)*ones(size(ref_j));
2554    num_b_civ2=ref_j+ceil(index_civ2/2)*ones(size(ref_j));
2555    % adjust the first and last field number
2556    if isnan(lastfield_j)
2557        indsel=find((num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2558    else
2559        indsel=find((num_b_civ1 <= lastfield_j)&(num_b_civ2 <= lastfield_j)&(num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2560    end
2561    if length(indsel)>=1
2562        firstind=indsel(1);
2563        lastind=indsel(end);
2564        set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
2565        set(handles.last_j,'String',num2str(ref_j(lastind)))
2566        ref_j=ref_j(indsel);
2567        num_a_civ1=num_a_civ1(indsel);
2568        num_b_civ1=num_b_civ1(indsel);
2569        num_a_civ2=num_a_civ2(indsel);
2570        num_b_civ2=num_b_civ2(indsel);
2571    end
2572elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
2573    displ_num=get(handles.ListPairCiv1,'UserData');
2574    num1_civ1=ref_i;
2575    num2_civ1=ref_i;
2576    num_a_civ1=displ_num(1,index_civ1);
2577    num_b_civ1=displ_num(2,index_civ1);
2578    num1_civ2=ref_i;
2579    num2_civ2=ref_i;
2580    num_a_civ2=displ_num(1,index_civ2);
2581    num_b_civ2=displ_num(2,index_civ2);
2582elseif isequal(mode,'displacement')
2583    num1_civ1=ref_i;
2584    num2_civ1=ref_i;
2585    num_a_civ1=ref_j;
2586    num_b_civ1=ref_j;
2587    num1_civ2=ref_i;
2588    num2_civ2=ref_i;
2589    num_a_civ2=ref_j;
2590    num_b_civ2=ref_j;
2591end
2592
2593%------------------------------------------------------------------------
2594% --- Executes on button press in ListCompareMode.
2595function ListCompareMode_Callback(hObject, eventdata, handles)
2596%------------------------------------------------------------------------
2597test=get(handles.ListCompareMode,'Value');
2598if test==2 || test==3 % case 'dispalcemen' or 'stereo PIV'
2599    filebase=get(handles.RootName,'String');
2600    browse=get(handlesRootName,'Userdata');
2601    browse.nom_type_ima1=browse.nom_type_ima;
2602    set(handlesRootName,'UserData',browse);
2603    set(handles.sub_txt,'Visible','on')
2604    set(handles.RootName_1,'Visible','On');%mkes the second file input window visible
2605    mode_store=get(handles.ListPairMode,'String');%get the present 'mode'
2606    set(handles.ListCompareMode,'UserData',mode_store);%store the mode display
2607    set(handles.ListPairMode,'Visible','off')
2608    if test==2
2609        set(handles.ListPairMode,'Visible','off')
2610        set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2611    else
2612        set(handles.ListPairMode,'Visible','on')
2613        set(handles.ListPairMode,'Value',3) % mode 'Matlab' selected for stereo
2614    end
2615   
2616    %% menuopen an image file with the browser
2617    ind_opening=1;%default
2618    browse.incr_pair=[0 0]; %default
2619    oldfile=get(handles.RootName,'String');
2620     menu={'*.xml;*.civ;*.png;*.jpg;*.tif;*.avi;*.AVI;*.nc;', ' (*.xml,*.civ,*.png,*.jpg ,.tif, *.avi,*.nc)';
2621       '*.xml',  '.xml files '; ...
2622        '*.civ',  '.civ files '; ...
2623        '*.png','.png image files'; ...
2624        '*.jpg',' jpeg image files'; ...
2625        '*.tif','.tif image files'; ...
2626        '*.avi;*.AVI','.avi movie files'; ...
2627        '*.nc','.netcdf files'; ...
2628        '*.*',  'All Files (*.*)'};
2629    [FileName, PathName, filtindex] = uigetfile( menu, 'Pick a file of the second series',oldfile);
2630    fileinput=[PathName FileName];%complete file name
2631    sizf=size(fileinput);
2632    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
2633    [path,name,ext]=fileparts(fileinput);
2634    [path1]=fileparts(filebase);
2635    if isunix
2636        [status,path]=system(['readlink ' path]);
2637        [status,path1]=system(['readlink ' path1]);% look for the true path in case of symbolic paths
2638    end
2639    if ~strcmp(path1,path)
2640        msgbox_uvmat('ERROR','The second image series must be in the same directory as the first one')
2641        return
2642     end
2643%     set(handles.RootName_1,'String',name);
2644    [RootPath,RootFile,field_count,str2,str_a,str_b,xx,nom_type,subdir]=name2display(name);
2645    set(handles.RootName_1,'String',RootFile);
2646    browse=get(handlesRootName,'UserData');
2647    browse.nom_type_ima_1=nom_type;
2648    set(handlesRootName,'UserData',browse)
2649   
2650    %check image extension
2651    if ~strcmp(ext,get(handles.ImaExt,'String'))
2652        msgbox_uvmat('ERROR','The second image series must have the same extension name as the first one')
2653        return
2654    end
2655   
2656    %% check coincidence of image sizes
2657%     ref_i=get(handles.ref_i,'string');
2658%     ref_j=get(handles.ref_j,'string');
2659%     [filecell,num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2,nom_type_nc]=set_civ_filenames(handles,ref_i,ref_j,[1 0 0 0 0 0]);
2660%     A=imread(filecell.ima1.checkciv1{1});
2661%     A_1=imread(fileinput);
2662%     npxy=size(A);
2663%     npxy_1=size(A_1);
2664%     if ~isequal(size(A),size(A_1))
2665%         msgbox_uvmat('ERROR','The two input image series do not have the same size')
2666%         return
2667%     end
2668else
2669    set(handles.ListPairMode,'Visible','on')
2670    set(handles.RootName_1,'Visible','Off');
2671    set(handles.sub_txt,'Visible','off')
2672    set(handles.RootName_1,'String',[]);
2673    mode_store=get(handles.ListCompareMode,'UserData');
2674    set(handles.ListPairMode,'Value',1)
2675    set(handles.ListPairMode,'String',mode_store)
2676    set(handles.test_stereo1,'Value',0)
2677    set(handles.CheckStereo,'Value',0)
2678    set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2679end
2680if test==3 && get(handles.CheckPatch1,'Value')
2681    set(handles.test_stereo1,'Visible','on')
2682else
2683    set(handles.test_stereo1,'Visible','off')
2684end
2685if test==3 && get(handles.CheckPatch2,'Value')
2686    set(handles.CheckStereo,'Visible','on')
2687else
2688    set(handles.CheckStereo,'Visible','off')
2689end
2690mode_Callback(hObject, eventdata, handles)
2691
2692
2693%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2694% Callbacks in the uipanel Pair Indices
2695%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2696%------------------------------------------------------------------------
2697% --- Executes on button press in ListPairMode.
2698function ListPairMode_Callback(hObject, eventdata, handles)
2699%------------------------------------------------------------------------
2700compare_list=get(handles.ListCompareMode,'String');
2701val=get(handles.ListCompareMode,'Value');
2702compare=compare_list{val};
2703if strcmp(compare,'displacement')
2704    mode='displacement';
2705else
2706    mode_list=get(handles.ListPairMode,'String');
2707    if ischar(mode_list)
2708        mode_list={mode_list};
2709    end
2710    mode_value=get(handles.ListPairMode,'Value');
2711    mode=mode_list{mode_value};
2712end
2713displ_num=[];%default
2714ref_i=str2double(get(handles.ref_i,'String'));
2715% last_i=str2num(get(handles.last_i,'String'));
2716time=get(handles.ImaDoc,'UserData'); %get the set of times
2717siztime=size(time);
2718nbfield=siztime(1);
2719nbfield2=siztime(2);
2720indchosen=1;  %%first pair selected by default
2721%displ_num used to define the indices of the civ pairs
2722% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
2723% are relative to the reference indices ref_i and ref_j respectively.
2724if isequal(mode,'pair j1-j2')%| isequal(mode,'st_pair j1-j2')
2725    dt=1;
2726    displ='';
2727    index=0;
2728    numlist_a=[];
2729    numlist_B=[];
2730    %get all the time intervals in bursts
2731    displ_dt=1;%default
2732    nbfield2=min(nbfield2,10);%limitate the number of pairs to 10x10
2733    for numod_a=1:nbfield2-1 %nbfield2 always >=2 for 'pair j1-j2' mode
2734        for numod_b=(numod_a+1):nbfield2
2735            index=index+1;
2736            numlist_a(index)=numod_a;
2737            numlist_b(index)=numod_b;
2738            if ~isempty(time)
2739                dt(numod_a,numod_b)=time(ref_i,numod_b)-time(ref_i,numod_a);%first time interval dt
2740                displ_dt(index)=dt(numod_a,numod_b);
2741            else
2742                displ_dt(index)=1;
2743            end
2744        end
2745    end
2746    [dtsort,indsort]=sort(displ_dt);
2747    if ~isempty(numlist_a)
2748        displ_num(1,:)=numlist_a(indsort);
2749        displ_num(2,:)=numlist_b(indsort);
2750    end
2751    displ_num(3,:)=0;
2752    displ_num(4,:)=0;
2753    set(handles.jtext,'Visible','Off')
2754    set(handles.first_j,'Visible','Off')
2755    set(handles.last_j,'Visible','Off')
2756    set(handles.incr_j,'Visible','Off')
2757    set(handles.nb_field2,'Visible','Off')
2758    set(handles.ref_j,'Visible','Off')
2759elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)')
2760    index=1:200;
2761    displ_num(1,index)=-floor(index/2);
2762    displ_num(2,index)=ceil(index/2);
2763    displ_num(3:4,index)=zeros(2,200);
2764%     for index=1:min(nbfield2-1,200)
2765%         displ_num(1,index)=-floor(index/2);
2766%         displ_num(2,index)=ceil(index/2);
2767%         displ_num(3,index)=0;
2768%         displ_num(4,index)=0;
2769%     end
2770    set(handles.jtext,'Visible','On')
2771    set(handles.first_j,'Visible','On')
2772    set(handles.last_j,'Visible','On')
2773    set(handles.incr_j,'Visible','On')
2774    set(handles.nb_field2,'Visible','On')
2775    set(handles.ref_j,'Visible','On')
2776    if nbfield > 1
2777        set(handles.itext,'Visible','On')
2778        set(handles.first_i,'Visible','On')
2779        set(handles.last_i,'Visible','On')
2780        set(handles.incr_i,'Visible','On')
2781        set(handles.nb_field,'Visible','On')
2782        set(handles.ref_i,'Visible','On')
2783    else
2784        set(handles.itext,'Visible','Off')
2785        set(handles.first_i,'Visible','Off')
2786        set(handles.last_i,'Visible','Off')
2787        set(handles.incr_i,'Visible','Off')
2788        set(handles.nb_field,'Visible','Off')
2789        set(handles.ref_i,'Visible','Off')
2790    end
2791elseif isequal(mode,'series(Di)') %| isequal(mode,'st_series(Di)')
2792    index=1:200;
2793    displ_num(1:2,index)=zeros(2,200);
2794    displ_num(3,index)=-floor(index/2);
2795    displ_num(4,index)=ceil(index/2);
2796%     for index=1:200%min(nbfield-1,200)
2797%         displ_num(1,index)=0;
2798%         displ_num(2,index)=0;
2799%         displ_num(3,index)=-floor(index/2);
2800%         displ_num(4,index)=ceil(index/2);
2801%     end
2802    set(handles.itext,'Visible','On')
2803    set(handles.first_i,'Visible','On')
2804    set(handles.last_i,'Visible','On')
2805    set(handles.incr_i,'Visible','On')
2806    set(handles.nb_field,'Visible','On')
2807    set(handles.ref_i,'Visible','On')
2808    if nbfield2 > 1
2809        set(handles.jtext,'Visible','On')
2810        set(handles.first_j,'Visible','On')
2811        set(handles.last_j,'Visible','On')
2812        set(handles.incr_j,'Visible','On')
2813        set(handles.nb_field2,'Visible','On')
2814        set(handles.ref_j,'Visible','On')
2815    else
2816        set(handles.jtext,'Visible','Off')
2817        set(handles.first_j,'Visible','Off')
2818        set(handles.last_j,'Visible','Off')
2819        set(handles.incr_j,'Visible','Off')
2820        set(handles.nb_field2,'Visible','Off')
2821        set(handles.ref_j,'Visible','Off')
2822    end
2823elseif isequal(mode,'displacement')%the pairs have the same indices
2824    displ_num(1,1)=0;
2825    displ_num(2,1)=0;
2826    displ_num(3,1)=0;
2827    displ_num(4,1)=0;
2828    if nbfield > 1
2829        set(handles.itext,'Visible','On')
2830        set(handles.first_i,'Visible','On')
2831        set(handles.last_i,'Visible','On')
2832        set(handles.incr_i,'Visible','On')
2833        set(handles.nb_field,'Visible','On')
2834        set(handles.ref_i,'Visible','On')
2835    else
2836        set(handles.itext,'Visible','Off')
2837        set(handles.first_i,'Visible','Off')
2838        set(handles.last_i,'Visible','Off')
2839        set(handles.incr_i,'Visible','Off')
2840        set(handles.nb_field,'Visible','Off')
2841        set(handles.ref_i,'Visible','Off')
2842    end
2843    if nbfield2 > 1
2844        set(handles.jtext,'Visible','On')
2845        set(handles.first_j,'Visible','On')
2846        set(handles.last_j,'Visible','On')
2847        set(handles.incr_j,'Visible','On')
2848        set(handles.nb_field2,'Visible','On')
2849        set(handles.ref_j,'Visible','On')
2850    else
2851        set(handles.jtext,'Visible','Off')
2852        set(handles.first_j,'Visible','Off')
2853        set(handles.last_j,'Visible','Off')
2854        set(handles.incr_j,'Visible','Off')
2855        set(handles.nb_field2,'Visible','Off')
2856        set(handles.ref_j,'Visible','Off')
2857    end
2858end
2859set(handles.ListPairCiv1,'UserData',displ_num);
2860find_netcpair_civ1( handles)
2861find_netcpair_civ2(handles)
2862
2863%------------------------------------------------------------------------
2864% --- Executes on selection change in ListPairCiv1.
2865function ListPairCiv1_Callback(hObject, eventdata, handles)
2866%------------------------------------------------------------------------
2867%reproduce by default the chosen pair in the checkciv2 menu
2868list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
2869index_pair=get(handles.ListPairCiv1,'Value');
2870displ_num=get(handles.ListPairCiv1,'UserData');
2871% num_a=displ_num(1,index_pair);
2872% num_b=displ_num(2,index_pair);
2873list_pair2=get(handles.ListPairCiv2,'String');%get the menu of image pairs
2874if index_pair<=length(list_pair2)
2875    set(handles.ListPairCiv2,'Value',index_pair);
2876end
2877
2878%update first_i and last_i according to the chosen image pairs
2879mode_list=get(handles.ListPairMode,'String');
2880mode_value=get(handles.ListPairMode,'Value');
2881mode=mode_list{mode_value};
2882if isequal(mode,'series(Di)')
2883    first_i=str2double(get(handles.first_i,'String'));
2884    last_i=str2double(get(handles.last_i,'String'));
2885    incr_i=str2double(get(handles.incr_i,'String'));
2886    num1=first_i:incr_i:last_i;
2887    lastfield=str2double(get(handles.nb_field,'String'));
2888    if ~isnan(lastfield)
2889        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2890            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2891        num1=num1(test_find);
2892    end
2893    set(handles.first_i,'String',num2str(num1(1)));
2894    set(handles.last_i,'String',num2str(num1(end)));
2895elseif isequal(mode,'series(Dj)')
2896    first_j=str2double(get(handles.first_j,'String'));
2897    last_j=str2double(get(handles.last_j,'String'));
2898    incr_j=str2double(get(handles.incr_j,'String'));
2899    num_j=first_j:incr_j:last_j;
2900    lastfield2=str2double(get(handles.nb_field2,'String'));
2901    if ~isnan(lastfield2)
2902        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2903            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2904        num1=num_j(test_find);
2905    end
2906    set(handles.first_j,'String',num2str(num1(1)));
2907    set(handles.last_j,'String',num2str(num1(end)));
2908end
2909
2910%------------------------------------------------------------------------
2911% --- Executes on selection change in ListPairCiv2.
2912function ListPairCiv2_Callback(hObject, eventdata, handles)
2913%------------------------------------------------------------------------
2914index_pair=get(handles.ListPairCiv2,'Value');%get the selected position index in the menu
2915
2916%update first_i and last_i according to the chosen image pairs
2917mode_list=get(handles.ListPairMode,'String');
2918mode_value=get(handles.ListPairMode,'Value');
2919mode=mode_list{mode_value};
2920if isequal(mode,'series(Di)')
2921    first_i=str2double(get(handles.first_i,'String'));
2922    last_i=str2double(get(handles.last_i,'String'));
2923    incr_i=str2double(get(handles.incr_i,'String'));
2924    num1=first_i:incr_i:last_i;
2925    lastfield=str2double(get(handles.nb_field,'String'));
2926    if ~isnan(lastfield)
2927        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2928            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2929        num1=num1(test_find);
2930    end
2931    set(handles.first_i,'String',num2str(num1(1)));
2932    set(handles.last_i,'String',num2str(num1(end)));
2933elseif isequal(mode,'series(Dj)')
2934    first_j=str2double(get(handles.first_j,'String'));
2935    last_j=str2double(get(handles.last_j,'String'));
2936    incr_j=str2double(get(handles.incr_j,'String'));
2937    num_j=first_j:incr_j:last_j;
2938    lastfield2=str2double(get(handles.nb_field2,'String'));
2939    if ~isnan(lastfield2)
2940        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2941            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2942        num1=num_j(test_find);
2943    end
2944    set(handles.first_j,'String',num2str(num1(1)));
2945    set(handles.last_j,'String',num2str(num1(end)));
2946end
2947
2948%------------------------------------------------------------------------
2949function ref_i_Callback(hObject, eventdata, handles)
2950%------------------------------------------------------------------------
2951mode_list=get(handles.ListPairMode,'String');
2952mode_value=get(handles.ListPairMode,'Value');
2953mode=mode_list{mode_value};
2954find_netcpair_civ1(handles);% update the menu of pairs depending on the available netcdf files
2955if isequal(mode,'series(Di)') || ...% we do patch2 only
2956        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2957    find_netcpair_civ2( handles);
2958end
2959
2960%------------------------------------------------------------------------
2961function ref_j_Callback(hObject, eventdata, handles)
2962%------------------------------------------------------------------------
2963mode_list=get(handles.ListPairMode,'String');
2964mode_value=get(handles.ListPairMode,'Value');
2965mode=mode_list{mode_value};
2966if isequal(get(handles.CheckCiv1,'Value'),0)|| isequal(mode,'series(Dj)')
2967    find_netcpair_civ1(handles);% update the menu of pairs depending on the available netcdf files
2968end
2969if isequal(mode,'series(Dj)') || ...
2970        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2971    find_netcpair_civ2(handles);
2972end
2973%
2974%------------------------------------------------------------------------
2975% determine the menu for checkciv1 pairs depending on existing netcdf file at the middle of
2976% the field series set by first_i, incr, last_i
2977function find_netcpair_civ1(handles)
2978%------------------------------------------------------------------------
2979set(gcf,'Pointer','watch')
2980%nomenclature types
2981filebase=get(handles.RootName,'String');
2982[filepath,Nme,ext_dir]=fileparts(filebase);
2983browse=get(handles.RootName,'UserData');
2984compare_list=get(handles.ListCompareMode,'String');
2985val=get(handles.ListCompareMode,'Value');
2986compare=compare_list{val};
2987if strcmp(compare,'displacement')
2988    mode='displacement';
2989else
2990    mode_list=get(handles.ListPairMode,'String');
2991    mode_value=get(handles.ListPairMode,'Value');
2992    if isempty(mode_list)
2993        return
2994    end
2995    mode=mode_list{mode_value};
2996end
2997
2998% nomenclature type of the .nc files
2999nom_type_ima=[];%default
3000if isfield(browse,'nom_type_ima')
3001    nom_type_ima=browse.nom_type_ima;
3002end
3003
3004%determine nom_type_nc:
3005nom_type_nc=[];%default
3006if isfield(browse,'nom_type_nc')
3007    nom_type_nc=browse.nom_type_nc;
3008end
3009if isempty(nom_type_nc)
3010    [nom_type_nc]=nomtype2pair(nom_type_ima,isequal(mode,'series(Di)'),isequal(mode,'series(Dj)'));
3011end
3012browse.nom_type_nc=nom_type_nc;
3013set(handles.RootName,'UserData',browse)
3014
3015%reads .nc subdirectoy and image numbers from the interface
3016subdir_civ1=get(handles.txt_SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
3017ref_i=str2double(get(handles.ref_i,'String'));
3018if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
3019    ref_j=0;
3020else
3021    ref_j=str2double(get(handles.ref_j,'String'));
3022end
3023time=get(handles.ImaDoc,'UserData');%get the set of times
3024if isempty(time)
3025    time=[0 1];
3026end
3027dt_unit=1000;%default
3028displ_num=get(handles.ListPairCiv1,'UserData');
3029
3030%eliminate the first pairs inconsistent with the position
3031if isempty(displ_num)
3032    nbpair=0;
3033else
3034    nbpair=length(displ_num(1,:));%nbre of displayed pairs
3035    if  isequal(mode,'series(Di)')  %| isequal(mode,'st_series(Di)')
3036        nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
3037    elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3038        nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
3039    end
3040end
3041nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
3042
3043%look for existing processed pairs involving the field at the middle of the series if checkciv1 will not
3044% be performed, while the result is needed for next steps.
3045displ_pair={''};
3046select=ones(size(1:nbpair));%flag for displayed pairs =1 for display
3047testpair=0;
3048
3049%% case with no Civ1 operation, netcdf files need to exist for reading
3050if ~get(handles.CheckCiv1,'Value') %
3051    if ~exist(fullfile(filepath,subdir_civ1,ext_dir),'dir')
3052        msgbox_uvmat('ERROR',['no civ1 file available: subdirectory ' subdir_civ1 ' does not exist']);
3053        set(handles.ListPairCiv1,'String',{});
3054        return
3055    end
3056    for ipair=1:nbpair
3057        filename=name_generator(filebase,ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair),'.nc',nom_type_nc,1,...
3058            ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair),subdir_civ1);
3059        select(ipair)=exist(filename,'file')==2;% put flag to 0 if the file does not exist
3060    end   
3061    % case of no displayed pair
3062    if isequal(select,zeros(size(1:nbpair)))
3063        if isfield(browse,'incr_pair') && ~isequal(browse.incr_pair,[0 0])
3064            num_i1=ref_i-floor(browse.incr_pair(1)/2);
3065            num_i2=ref_i+ceil(browse.incr_pair(1)/2);
3066            num_j1=ref_j-floor(browse.incr_pair(2)/2);
3067            num_j2=ref_j+ceil(browse.incr_pair(2)/2);
3068            filename=name_generator(filebase,num_i1,num_j1,'.nc',nom_type_nc,1,num_i2,num_j2,subdir_civ1);
3069            select(1)=exist(filename,'file')==2;
3070            testpair=1;
3071        else
3072            if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3073                msgbox_uvmat('ERROR',['no civ1 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ1]);
3074            else
3075                msgbox_uvmat('ERROR',['no civ1 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ1]);
3076            end
3077            set(handles.ListPairCiv1,'String',{''});
3078            %COMPLETER CAS STEREO
3079            return
3080        end
3081    end
3082end
3083
3084%% determine the menu display in .ListPairCiv1
3085% the menu depends on the mode defined in ListPairMode_callback through the array displ_num:
3086% displ_num(1,:)=indices j1
3087% displ_num(2,:)=indices j2
3088% displ_num(3,:)=indices i1
3089% displ_num(4,:)=indices i2
3090% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
3091% are relative to the reference indices ref_i and ref_j respectively.
3092if isequal(mode,'series(Di)')
3093    if testpair
3094        displ_pair{1}=['Di= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3095    else
3096        for ipair=1:nbpair
3097            if select(ipair)
3098                displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3099                if size(time,1)>=ref_i+displ_num(4,ipair) && size(time,2)>=ref_j+displ_num(2,ipair)
3100                    dt=time(ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair))-time(ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair));%time interval dt
3101                    displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3102                end
3103            else
3104                displ_pair{ipair}='...'; %pair not displayed in the menu
3105            end
3106        end
3107    end
3108elseif isequal(mode,'series(Dj)')
3109    if testpair
3110        displ_pair{1}=['Dj= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3111    else
3112        for ipair=1:nbpair
3113            if select(ipair)
3114                displ_pair{ipair}=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3115                if size(time,1)>=ref_i+displ_num(4,ipair) && size(time,2)>=ref_j+displ_num(2,ipair)
3116                    dt=time(ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair))-time(ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair));%time interval dt
3117                    displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3118                end
3119            else
3120                displ_pair{ipair}='...'; %pair not displayed in the menu
3121            end
3122        end
3123    end
3124elseif isequal(mode,'pair j1-j2')%case of pairs
3125    for ipair=1:nbpair
3126        if select(ipair)
3127            dt=time(ref_i+displ_num(4,ipair),displ_num(2,ipair))-time(ref_i+displ_num(3,ipair),displ_num(1,ipair));%time interval dt
3128            displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair),nom_type_ima) '-' num2stra(displ_num(2,ipair),nom_type_ima) ...
3129                ' :dt= ' num2str(dt*1000)];
3130        else
3131            displ_pair{ipair}='...'; %pair not displayed in the menu
3132        end
3133    end
3134elseif isequal(mode,'displacement')
3135    displ_pair={'Di=Dj=0'};
3136end
3137set(handles.ListPairCiv1,'String',displ_pair');
3138
3139%% determine the default selection in the pair menu
3140ichoice=find(select,1);% index of selected pair
3141if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3142initial=get(handles.ListPairCiv1,'Value');%initial choice of pair
3143if initial>nbpair || (numel(select)>=initial && ~isequal(select(initial),1))
3144    set(handles.ListPairCiv1,'Value',ichoice);% first valid pair proposed by default in the menu
3145end
3146initial=get(handles.ListPairCiv2,'Value');
3147if initial>length(displ_pair')%|~isequal(select(initial),1)
3148    if ichoice <= length(displ_pair')
3149        set(handles.ListPairCiv2,'Value',ichoice);% same pair proposed by default for civ2
3150    else
3151        set(handles.ListPairCiv2,'Value',1);% same pair proposed by default for civ2
3152    end
3153end
3154set(handles.ListPairCiv2,'String',displ_pair');
3155set(gcf,'Pointer','arrow')
3156
3157%------------------------------------------------------------------------
3158% determine the menu for checkciv2 pairs depending on the existing netcdf file at the
3159%middle of the series set by first_i, incr, last_i
3160function find_netcpair_civ2(handles)
3161%------------------------------------------------------------------------
3162set(gcf,'Pointer','watch')
3163%nomenclature types
3164filebase=get(handles.RootName,'String');
3165[filepath,Nme,ext_dir]=fileparts(filebase);
3166browse=get(handles.RootName,'UserData');
3167compare_list=get(handles.ListCompareMode,'String');
3168val=get(handles.ListCompareMode,'Value');
3169compare=compare_list{val};
3170if strcmp(compare,'displacement')
3171    mode='displacement';
3172else
3173    mode_list=get(handles.ListPairMode,'String');
3174    if isempty(mode_list)
3175        msgbox_uvmat('ERROR','please enter an input image or netcdf file')
3176        return
3177    end
3178    mode_value=get(handles.ListPairMode,'Value');
3179    mode=mode_list{mode_value};
3180end
3181
3182% nomenclature type of the .nc files
3183nom_type_ima='ima_num';%default
3184if isfield(browse,'nom_type_ima')
3185    nom_type_ima=browse.nom_type_ima;
3186end
3187nom_type_nc='_i1-i2';%default
3188if isfield(browse,'nom_type_nc')
3189    nom_type_nc=browse.nom_type_nc;
3190end
3191if isequal(nom_type_ima,'png_old') || isequal(nom_type_ima,'netc_old')|| isequal(nom_type_ima,'raw_SMD')|| isequal(nom_type_nc,'netc_old')
3192    nom_type_nc='netc_old';%nom_type for the netcdf files
3193elseif isequal(nom_type_ima,'none')||isequal(nom_type_nc,'none')
3194    nom_type_nc='none';
3195elseif isequal(nom_type_ima,'avi')||isequal(nom_type_ima,'_i')||isequal(nom_type_ima,'ima_num')||isequal(nom_type_nc,'_i1-i2')
3196    nom_type_nc='_i1-i2';
3197else
3198    if  isequal(mode,'series(Di)')%|isequal(mode,'st_series(Di)')
3199        nom_type_nc='_i1-i2_j'; % PIV in volume
3200    else
3201        nom_type_nc='_i_j1-j2';
3202    end
3203end
3204browse.nom_type_nc=nom_type_nc;
3205set(handles.RootName,'UserData',browse)
3206
3207%reads .nc subdirectory and image numbers from the interface
3208subdir_civ1=get(handles.txt_SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
3209subdir_civ2=get(handles.txt_SubdirCiv2,'String');%subdirectory subdir_civ2 for the netcdf data
3210ref_i=str2double(get(handles.ref_i,'String'));
3211if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
3212    ref_j=0;
3213else
3214    ref_j=str2double(get(handles.ref_j,'String'));
3215end
3216time=get(handles.ImaDoc,'UserData'); %get the set of times
3217if isempty(time)
3218    time=[0 1];%default
3219end
3220displ_num=get(handles.ListPairCiv1,'UserData');
3221
3222%eliminate the first pairs inconsistent with the position
3223if isempty(displ_num)
3224    nbpair=0;
3225else
3226    nbpair=length(displ_num(1,:));%nbre of displayed pairs
3227    if  isequal(mode,'series(Di)')% | isequal(mode,'st_series(Di)')
3228        nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
3229    elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3230        nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
3231    end
3232end
3233nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
3234
3235%% look for existing processed pairs at the reference indices if Civ1 will not
3236% be performed, while the result is needed for next steps.
3237displ_pair={''}; %default
3238select=ones(size(1:nbpair));%default =1 for numbers of displayed pairs
3239if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
3240    if ~exist(fullfile(filepath,subdir_civ2,ext_dir),'dir')
3241        errordlg(['no civ2 file available: subdirectory ' subdir_civ2 ' does not exist'])
3242        set(handles.ListPairCiv2,'Value',1);
3243        set(handles.ListPairCiv2,'String',{''});
3244        return
3245    end
3246    for ipair=1:nbpair
3247        filename=name_generator(filebase,ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair),'.nc',nom_type_nc,1,...
3248            ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair),subdir_civ1);
3249        select(ipair)=exist(filename,'file')==2;
3250    end
3251    if  isequal(select,zeros(size(1:nbpair)))
3252        if isfield(browse,'incr_pair')
3253            num_i1=ref_i-floor(browse.incr_pair(1)/2);
3254            num_i2=ref_i+floor((browse.incr_pair(1)+1)/2);
3255            num_j1=ref_j-floor(browse.incr_pair(2)/2);
3256            num_j2=ref_j+floor((browse.incr_pair(2)+1)/2);
3257            filename=name_generator(filebase,num_i1,num_j1,'.nc',nom_type_nc,1,num_i2,num_j2,subdir_civ2);
3258            select(1)=exist(filename,'file')==2;
3259        else
3260            if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3261                errordlg(['no civ2 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ2])
3262            else
3263                errordlg(['no civ2 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ2])
3264            end
3265            set(handles.ListPairCiv2,'Value',1);
3266            set(handles.ListPairCiv2,'String',{''});
3267            return
3268        end
3269    end
3270end
3271if isequal(mode,'series(Di)')
3272    for ipair=1:nbpair
3273        if select(ipair)
3274            displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
3275            if size(time,1)>=ref_i+displ_num(4,ipair) && size(time,2)>=ref_j+displ_num(2,ipair)
3276                dt=time(ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair))-time(ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair));%time interval dt
3277                displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3278            end
3279        else
3280            displ_pair{ipair}='...'; %pair not displayed in the menu
3281        end
3282    end
3283elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)') % series on the j index
3284    for ipair=1:nbpair
3285        if select(ipair)
3286            displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
3287            if size(time,1)>=ref_i+displ_num(4,ipair) && size(time,2)>=ref_j+displ_num(2,ipair)
3288                dt=time(ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair))-time(ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair));%time interval dt
3289                displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3290            end
3291        else
3292            displ_pair{ipair}='...'; %pair not displayed in the menu
3293        end
3294    end
3295elseif isequal(mode,'pair j1-j2')% | isequal(mode,'st_pair j1-j2') %case of pairs
3296    for ipair=1:nbpair
3297        if select(ipair)
3298            dt=time(ref_i+displ_num(4,ipair),displ_num(2,ipair))-time(ref_i+displ_num(3,ipair),displ_num(1,ipair));%time interval dt
3299            displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair),nom_type_ima) '-' num2stra(displ_num(2,ipair),nom_type_ima) ...
3300                ' :dt= ' num2str(dt*1000)];
3301        else
3302            displ_pair{ipair}='...'; %pair not displayed in the menu
3303        end
3304    end
3305elseif isequal(mode,'displacement')
3306    displ_pair={'Di=Dj=0'};
3307end
3308val=get(handles.ListPairCiv2,'Value');
3309ichoice=find(select,1);
3310if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3311if get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0
3312    val=ichoice;% first valid pair proposed by default in the menu
3313end
3314if val>length(displ_pair')
3315    set(handles.ListPairCiv2,'Value',1);% first valid pair proposed by default in the menu
3316else
3317    set(handles.ListPairCiv2,'Value',val);
3318end
3319set(handles.ListPairCiv2,'String',displ_pair');
3320set(gcf,'Pointer','arrow')
3321
3322
3323
3324
3325%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3326% Callbacks in the uipanel Reference Indices
3327%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3328%------------------------------------------------------------------------
3329function first_i_Callback(hObject, eventdata, handles)
3330%------------------------------------------------------------------------
3331first_i=str2double(get(handles.first_i,'String'));
3332set(handles.ref_i,'String', num2str(first_i))% reference index for pair dt = first index
3333ref_i_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3334
3335%------------------------------------------------------------------------
3336function first_j_Callback(hObject, eventdata, handles)
3337%------------------------------------------------------------------------
3338first_j=str2num(get(handles.first_j,'String'));
3339set(handles.ref_j,'String', num2str(first_j))% reference index for pair dt = first index
3340ref_j_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3341
3342%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3343% Callbacks in the uipanel Civ1
3344%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3345%------------------------------------------------------------------------
3346% --- Executes on button press in SearchRange: determine the search range num_Searchx,num_Searchy
3347function SearchRange_Callback(hObject, eventdata, handles)
3348%------------------------------------------------------------------------
3349%determine pair numbers
3350if strcmp(get(handles.umin,'Visible'),'off')
3351    set(handles.u_title,'Visible','on')
3352    set(handles.v_title,'Visible','on')
3353    set(handles.umin,'Visible','on')
3354    set(handles.umax,'Visible','on')
3355    set(handles.vmin,'Visible','on')
3356    set(handles.vmax,'Visible','on')
3357    set(handles.CoordUnit,'Visible','on')
3358    set(handles.TimeUnit,'Visible','on')
3359    set(handles.slash_title,'Visible','on')
3360    set(handles.min_title,'Visible','on')
3361    set(handles.max_title,'Visible','on')
3362    set(handles.unit_title,'Visible','on')
3363else
3364    get_search_range(hObject, eventdata, handles)
3365end
3366
3367%------------------------------------------------------------------------
3368% ---  determine the search range num_Searchx,num_Searchy and shift
3369function get_search_range(hObject, eventdata, handles)
3370umin=str2double(get(handles.umin,'String'));
3371umax=str2double(get(handles.umax,'String'));
3372vmin=str2double(get(handles.umin,'String'));
3373vmax=str2double(get(handles.vmax,'String'));
3374%switch min_title and max_title in case of error
3375if umax<=umin
3376    umin_old=umin;
3377    umin=umax;
3378    umax=umin_old;
3379    set(handles.umin,'String', num2str(umin))
3380    set(handles.umax,'String', num2str(umax))
3381end
3382if vmax<=vmin
3383    vmin_old=vmin;
3384    vmin=vmax;
3385    vmax=vmin_old;
3386    set(handles.vmin,'String', num2str(vmin))
3387    set(handles.vmax,'String', num2str(vmax))
3388end   
3389if ~(isnan(umin)||isnan(umax)||isnan(vmin)||isnan(vmax))
3390    list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
3391    index=get(handles.ListPairCiv1,'Value');
3392    displ_num=get(handles.ListPairCiv1,'UserData');
3393    time=get(handles.ImaDoc,'UserData'); %get the set of times
3394    pxcm_xy=get(handles.SearchRange,'UserData');
3395    pxcmx=pxcm_xy(1);
3396    pxcmy=pxcm_xy(2);
3397    mode_list=get(handles.ListPairMode,'String');
3398    mode_value=get(handles.ListPairMode,'Value');
3399    mode=mode_list{mode_value};
3400    if isequal (mode, 'series(Di)' )
3401        ref_i=str2double(get(handles.ref_i,'String'));
3402        num1=ref_i-floor(index/2);%  first image numbers
3403        num2=ref_i+ceil(index/2);
3404        num_a=1;
3405        num_b=1;
3406    elseif isequal (mode, 'series(Dj)')
3407        num1=1;
3408        num2=1;
3409        ref_j=str2double(get(handles.ref_j,'String'));
3410        num_a=ref_j-floor(index/2);%  first image numbers
3411        num_b=ref_j+ceil(index/2);
3412    elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
3413        ref_i=str2double(get(handles.ref_i,'String'));
3414        num1=ref_i;
3415        num2=ref_i;
3416        num_a=displ_num(1,index);
3417        num_b=displ_num(2,index);
3418    end
3419    dt=time(num2,num_b)-time(num1,num_a);
3420    ibx=str2double(get(handles.num_Bx,'String'));
3421    iby=str2double(get(handles.num_By,'String'));
3422    umin=dt*pxcmx*umin;
3423    umax=dt*pxcmx*umax;
3424    vmin=dt*pxcmy*vmin;
3425    vmax=dt*pxcmy*vmax;
3426    shiftx=round((umin+umax)/2);
3427    shifty=round((vmin+vmax)/2);
3428    isx=(umax+2-shiftx)*2+ibx;
3429    isx=2*ceil(isx/2)+1;
3430    isy=(vmax+2-shifty)*2+iby;
3431    isy=2*ceil(isy/2)+1;
3432    set(handles.num_Shiftx,'String',num2str(shiftx));
3433    set(handles.num_Shifty,'String',num2str(shifty));
3434    set(handles.num_Searchx,'String',num2str(isx));
3435    set(handles.num_Searchy,'String',num2str(isy));
3436end
3437
3438
3439%------------------------------------------------------------------------
3440% --- Executes on button press in CheckMask.
3441function get_mask_fix1_Callback(hObject, eventdata, handles)
3442%------------------------------------------------------------------------
3443maskval=get(handles.CheckMask,'Value');
3444if isequal(maskval,0)
3445    set(handles.txt_MaskName,'String','')
3446else
3447    mask_displ='no mask'; %default
3448    filebase=get(handles.RootName,'String');
3449    [nbslice, flag_mask]=get_mask(filebase,handles);
3450    if isequal(flag_mask,1)
3451        mask_displ=[num2str(nbslice) 'mask'];
3452    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3453        filebase_a=get(handles.RootName_1,'String');
3454        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3455        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3456            mask_displ='no mask';
3457        end
3458    end
3459    if isequal(mask_displ,'no mask')
3460        [FileName, PathName, filterindex] = uigetfile( ...
3461            {'*.png', ' (*.png)';
3462            '*.png',  '.png files '; ...
3463            '*.*', 'All Files (*.*)'}, ...
3464            'Pick a mask file *.png',filebase);
3465        mask_displ=fullfile(PathName,FileName);
3466        if ~exist(mask_displ,'file')
3467            mask_displ='no mask';
3468        end
3469    end
3470    if isequal(mask_displ,'no mask')
3471        set(handles.CheckMask,'Value',0)
3472        set(handles.CheckMask,'Value',0)
3473        set(handles.CheckMask,'Value',0)
3474    else
3475        %set(handles.CheckMask,'Value',1)
3476        set(handles.CheckMask,'Value',1)
3477    end
3478    set(handles.txt_MaskName,'String',mask_displ)
3479    set(handles.txt_Mask,'String',mask_displ)
3480    set(handles.txt_MaskName,'String',mask_displ)
3481end
3482
3483%------------------------------------------------------------------------
3484% --- Executes on button press in CheckMask: select box for mask option
3485function get_mask_civ2_Callback(hObject, eventdata, handles)
3486%------------------------------------------------------------------------
3487maskval=get(handles.CheckMask,'Value');
3488if isequal(maskval,0)
3489    set(handles.txt_Mask,'String','')
3490else
3491    mask_displ='no mask'; %default
3492    filebase=get(handles.RootName,'String');
3493    [nbslice, flag_mask]=get_mask(filebase,handles);
3494    if isequal(flag_mask,1)
3495        mask_displ=[num2str(nbslice) 'mask'];
3496    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3497        filebase_a=get(handles.RootName_1,'String');
3498        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3499        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3500            mask_displ='no mask';
3501        end
3502    end
3503    if isequal(mask_displ,'no mask')
3504        [FileName, PathName, filterindex] = uigetfile( ...
3505            {'*.png', ' (*.png)';
3506            '*.png',  '.png files '; ...
3507            '*.*', 'All Files (*.*)'}, ...
3508            'Pick a mask file *.png',filebase);
3509        mask_displ=fullfile(PathName,FileName);
3510        if ~exist(mask_displ,'file')
3511            mask_displ='no mask';
3512        end
3513    end
3514    if isequal(mask_displ,'no mask')
3515        set(handles.CheckMask,'Value',0)
3516        set(handles.CheckMask,'Value',0)
3517    else
3518        set(handles.CheckMask,'Value',1)
3519    end
3520    set(handles.txt_Mask,'String',mask_displ)
3521    set(handles.txt_MaskName,'String',mask_displ)
3522end
3523
3524%------------------------------------------------------------------------
3525% --- Executes on button press in CheckMask.
3526function get_mask_fix2_Callback(hObject, eventdata, handles)
3527%------------------------------------------------------------------------
3528maskval=get(handles.CheckMask,'Value');
3529if isequal(maskval,0)
3530    set(handles.txt_MaskName,'String','')
3531else
3532    mask_displ='no mask'; %default
3533    filebase=get(handles.RootName,'String');
3534    [nbslice, flag_mask]=get_mask(filebase,handles);
3535    if isequal(flag_mask,1)
3536        mask_displ=[num2str(nbslice) 'mask'];
3537    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3538        filebase_a=get(handles.RootName_1,'String');
3539        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3540        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3541            mask_displ='no mask';
3542        end
3543    end
3544    if isequal(mask_displ,'no mask')
3545        [FileName, PathName, filterindex] = uigetfile( ...
3546            {'*.png', ' (*.png)';
3547            '*.png',  '.png files '; ...
3548            '*.*', 'All Files (*.*)'}, ...
3549            'Pick a mask file *.png',filebase);
3550        mask_displ=fullfile(PathName,FileName);
3551        if ~exist(mask_displ,'file')
3552            mask_displ='no mask';
3553        end
3554    end
3555    if isequal(mask_displ,'no mask')
3556        set(handles.CheckMask,'Value',0)
3557    end
3558    set(handles.txt_MaskName,'String',mask_displ)
3559end
3560
3561%------------------------------------------------------------------------
3562% --- function called to look for mask files
3563function [nbslice, flag_mask]=get_mask(filebase,handles)
3564%------------------------------------------------------------------------
3565%detect mask files, images with appropriate file base
3566%[filebase '_' xx 'mask'], xx=nbslice
3567%flag_mask=1 indicates detection
3568
3569flag_mask=0;%default
3570nbslice=1;
3571
3572% subdir=get(handles.txt_SubdirCiv1,'String');
3573[Path,Name]=fileparts(filebase);
3574if ~isdir(Path)
3575    msgbox_uvmat('ERROR','no path for input files')
3576    return
3577end
3578% currentdir=pwd;
3579% cd(Path);%move in the dir of the root name filebase
3580maskfiles=dir(fullfile(Path,[Name '_*mask_*.png']));%look for mask files
3581% cd(currentdir);%come back to the current working directory
3582if ~isempty(maskfiles)
3583    %     msgbox_uvmat('ERROR','no mask available, to create it use Tools/Make mask in the upper menu bar of uvmat')
3584    % else
3585    flag_mask=1;
3586    maskname=maskfiles(1).name;% take the first mask file in the list
3587    [Path2,Name,ext]=fileparts(maskname);
3588    Namedouble=double(Name);
3589    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3590    ind_mask=findstr('mask',Name);
3591    i=ind_mask-1;
3592    while val(i)==0 && i>0
3593        i=i-1;
3594    end
3595    nbslice=str2double(Name(i+1:ind_mask-1));
3596    if ~isnan(nbslice) && Name(i)=='_'
3597        flag_mask=1;
3598    else
3599        msgbox_uvmat('ERROR',['bad mask file ' Name ext ' found in ' Path2])
3600        return
3601        nbslice=1;
3602    end
3603end
3604
3605%------------------------------------------------------------------------
3606% --- function called to look for grid files
3607function [nbslice, flag_mask]=get_grid(filebase,handles)
3608%------------------------------------------------------------------------
3609flag_mask=0;%default
3610nbslice=1;
3611[Path,Name]=fileparts(filebase);
3612currentdir=pwd;
3613cd(Path);%move in the dir of the root name filebase
3614maskfiles=dir([Name '_*grid_*.grid']);%look for mask files
3615cd(currentdir);%come back to the current working directory
3616if ~isempty(maskfiles)
3617    flag_mask=1;
3618    maskname=maskfiles(1).name;% take the first mask file in the list
3619    [Path2,Name,ext]=fileparts(maskname);
3620    Namedouble=double(Name);
3621    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3622    ind_mask=findstr('grid',Name);
3623    i=ind_mask-1;
3624    while val(i)==0 && i>0
3625        i=i-1;
3626    end
3627    nbslice=str2double(Name(i+1:ind_mask-1));
3628    if ~isnan(nbslice) && Name(i)=='_'
3629        flag_mask=1;
3630    else
3631        msgbox_uvmat('ERROR',['bad grid file ' Name ext ' found in ' Path2])
3632        return
3633        nbslice=1;
3634    end
3635end
3636
3637%------------------------------------------------------------------------
3638% --- transform numbers to letters
3639function str=num2stra(num,nom_type)
3640%------------------------------------------------------------------------
3641if isempty(nom_type)
3642    str='';
3643elseif strcmp(nom_type(end),'a')
3644    str=char(96+num);
3645elseif strcmp(nom_type(end),'A')
3646    str=char(96+num);
3647elseif isempty(nom_type(2:end))%a single index
3648    str='';
3649else
3650    str=num2str(num);
3651end
3652
3653%------------------------------------------------------------------------
3654% --- Executes on button press in ListSubdirCiv1.
3655function ListSubdirCiv1_Callback(hObject, eventdata, handles)
3656%------------------------------------------------------------------------
3657list_subdir_civ1=get(handles.ListSubdirCiv1,'String');
3658val=get(handles.ListSubdirCiv1,'Value');
3659subdir=list_subdir_civ1{val};
3660if strcmp(subdir,'new...')
3661    if get(handles.CheckCiv1,'Value')
3662        subdir='CIV'; %default subdirectory
3663    else
3664        msgbox_uvmat('ERROR','select CheckCiv1 to perform a new Civ operation')
3665        return
3666    end   
3667end
3668set(handles.txt_SubdirCiv1,'String',subdir);
3669find_netcpair_civ1(handles)
3670
3671%------------------------------------------------------------------------
3672% --- Executes on button press in ListSubdirCiv2.
3673function ListSubdirCiv2_Callback(hObject, eventdata, handles)
3674%------------------------------------------------------------------------
3675list_subdir_civ2=get(handles.ListSubdirCiv2,'String');
3676val=get(handles.ListSubdirCiv2,'Value');
3677subdir=list_subdir_civ2{val};
3678if strcmp(subdir,'new...')
3679    if get(handles.CheckCiv2,'Value')
3680        subdir='CIV'; %default subdirectory
3681    else
3682        msgbox_uvmat('ERROR','select CheckCiv2 to perform a new Civ operation')
3683        return
3684    end
3685end
3686set(handles.txt_SubdirCiv2,'String',subdir);
3687
3688%------------------------------------------------------------------------
3689% --- Executes on button press in CheckGrid.
3690function CheckGrid_Callback(hObject, eventdata, handles)
3691%------------------------------------------------------------------------
3692value=get(hObject,'Value');
3693hparent=get(hObject,'parent');
3694hchildren=get(hparent,'children');
3695handle_txtbox=findobj(hchildren,'tag','txt_GridName');
3696handle_dx=findobj(hchildren,'tag','num_Dx');
3697handle_dy=findobj(hchildren,'tag','num_Dy');
3698testgrid=0;
3699filegrid='';
3700if value
3701    filebase=get(handles.RootName,'String');
3702    [nbslice, flag_grid]=get_grid(filebase,handles);% look for a grid with appropriate name
3703    if isequal(flag_grid,1)
3704        filegrid=[num2str(nbslice) 'grid'];
3705        testgrid=1;
3706    else % browse for a grid
3707        filegrid=get(hObject,'UserData');%look for previous grid name stored as UserData
3708        if exist(filegrid,'file')
3709            filebase=filegrid;
3710        end
3711        [FileName, PathName, filterindex] = uigetfile( ...
3712            {'*.grid', ' (*.grid)';
3713            '*.grid',  '.grid files '; ...
3714            '*.*', 'All Files (*.*)'}, ...
3715            'Pick a file',filebase);
3716        filegrid=fullfile(PathName,FileName);
3717        set(hObject,'UserData',filegrid);%store for future use
3718        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filegrid,'file'))
3719            testgrid=1;
3720        end
3721    end
3722end
3723if testgrid
3724    set(handle_dx,'Visible','off');
3725    set(handle_dy,'Visible','off');
3726    set(handle_txtbox,'Visible','on')
3727    set(handle_txtbox,'String',filegrid)
3728else
3729    set(hObject,'Value',0);
3730    set(handle_dx,'Visible','on');
3731    set(handle_dy,'Visible','on');
3732    set(handle_txtbox,'Visible','off')
3733end
3734
3735%% if hObject is on the checkciv1 frame, duplicate action for checkciv2 frame
3736PanelName=get(hparent,'tag');
3737if strcmp(PanelName,'panel_Civ1')
3738    hchildren=get(handles.Civ2,'children');
3739    handle_checkbox=findobj(hchildren,'tag','check_Grid');
3740    handle_txtbox=findobj(hchildren,'tag','txt_GridName');
3741    handle_dx=findobj(hchildren,'tag','num_Dx');
3742    handle_dy=findobj(hchildren,'tag','num_Dy');
3743    set(handle_checkbox,'UserData',filegrid);%store for future use
3744    if testgrid
3745        set(handle_checkbox,'Value',1);
3746        set(handle_dx,'Visible','off');
3747        set(handle_dy,'Visible','off');
3748        set(handle_txtbox,'Visible','on')
3749        set(handle_txtbox,'String',filegrid)
3750    else
3751        set(handle_checkbox,'Value',0);
3752        set(handles.CheckGrid,'Value',0);
3753        set(handle_dx,'Visible','on');
3754        set(handle_dy,'Visible','on');
3755        set(handle_txtbox,'Visible','off')
3756    end
3757end
3758%------------------------------------------------------------------------
3759% --- Executes on button press in CheckMask.
3760function CheckMask_Callback(hObject, eventdata, handles)
3761%------------------------------------------------------------------------
3762value=get(hObject,'Value');
3763testmask=0;
3764if value
3765    filebase=get(handles.RootName,'String');
3766    [nbslice, flag_mask]=get_mask(filebase,handles);% look for a mask with appropriate name
3767    if isequal(flag_mask,1)
3768        filemask=[num2str(nbslice) 'mask'];
3769        testmask=1;
3770    else % browse for a mask
3771        filemask=get(handles.CheckMask,'UserData');%look for previous mask name stored as UserData
3772        if exist(filemask,'file')
3773            filebase=filemask;
3774        end
3775        [FileName, PathName, filterindex] = uigetfile( ...
3776            {'*.png', ' (*.png)';
3777            '*.png',  '.png files '; ...
3778            '*.*', 'All Files (*.*)'}, ...
3779            'Pick a mask file *.png',filebase);
3780        filemask=fullfile(PathName,FileName);
3781        set(handles.CheckMask,'UserData',filemask);%store for future use
3782        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filemask,'file'))
3783            testmask=1;
3784        end
3785    end
3786end
3787if testmask
3788    set(handles.num_Dx,'Visible','off');
3789    set(handles.num_Dy,'Visible','off');
3790    set(handles.num_Dx,'Visible','off');
3791    set(handles.num_Dy,'Visible','off');
3792    set(handles.txt_MaskName,'Visible','on')
3793    set(handles.txt_MaskName,'String',filemask)
3794else
3795    set(handles.CheckMask,'Value',0);
3796    set(handles.CheckGrid,'Value',0);
3797    set(handles.num_Dx,'Visible','on');
3798    set(handles.num_Dy,'Visible','on');
3799    set(handles.num_Dx,'Visible','on');
3800    set(handles.num_Dy,'Visible','on');
3801    set(handles.txt_MaskName,'Visible','off')
3802end
3803
3804
3805% --- Executes on button press in get_gridpatch1.
3806function get_gridpatch1_Callback(hObject, eventdata, handles)
3807% hObject    handle to get_gridpatch1 (see GCBO)
3808% eventdata  reserved - to be defined in a future version of MENUMATLAB
3809% handles    structure with handles and user data (see GUIDATA)
3810
3811filebase=get(handles.RootName,'String');
3812[FileName, PathName, filterindex] = uigetfile( ...
3813    {'*.grid', ' (*.grid)';
3814    '*.grid',  '.grid files '; ...
3815    '*.*', 'All Files (*.*)'}, ...
3816    'Pick a file',filebase);
3817filegrid=fullfile(PathName,FileName);
3818set(handles.grid_patch1,'string',filegrid);
3819% set(handles.grid_patch2,'string',filegrid
3820
3821%------------------------------------------------------------------------
3822% --- Executes on button press in get_gridpatch2.
3823function get_gridpatch2_Callback(hObject, eventdata, handles)
3824%------------------------------------------------------------------------
3825
3826
3827%------------------------------------------------------------------------
3828% --- STEREO Interp
3829function cmd=RUN_STINTERP(stinterpBin,filename_A_nc,filename_B_nc,filename_nc,nx_patch,ny_patch,rho_patch,subdomain_patch,thresh_value,xmlA,xmlB)
3830%------------------------------------------------------------------------
3831namelog=[filename_nc(1:end-3) '_stinterp.log'];
3832cmd=[stinterpBin ' -f1 ' filename_A_nc  ' -f2 ' filename_B_nc ' -f  ' filename_nc ...
3833    ' -m ' nx_patch  ' -n ' ny_patch ' -ro ' rho_patch ' -nopt ' subdomain_patch ' -c1 ' xmlA ' -c2 ' xmlB '  -xy  x -Nfy 1024 > ' namelog ' 2>&1']; % redirect standard output to the log file
3834
3835%------------------------------------------------------------------------
3836%--read images and convert them to the uint16 format used for PIV
3837function A=read_image(filename,type_ima,num,movieobject)
3838%------------------------------------------------------------------------
3839%num is the view number needed for an avi movie
3840switch type_ima
3841    case 'movie'
3842        A=read(movieobject,num);
3843    case 'avi'
3844        mov=aviread(filename,num);
3845        A=frame2im(mov(1));
3846    case 'multimage'
3847        A=imread(filename,num);
3848    case 'image'
3849        A=imread(filename);
3850end
3851siz=size(A);
3852if length(siz)==3;%color images
3853    A=sum(double(A),3);
3854    A=uint16(A);
3855end
3856
3857
3858%------------------------------------------------------------------------
3859% --- Executes on button press in get_ref_fix1.
3860function get_ref_fix1_Callback(hObject, eventdata, handles)
3861%------------------------------------------------------------------------
3862filebase=get(handles.RootName,'String');
3863[FileName, PathName, filterindex] = uigetfile( ...
3864    {'*.nc', ' (*.nc)';
3865    '*.nc',  'netcdf files '; ...
3866    '*.*', 'All Files (*.*)'}, ...
3867    'Pick a file',filebase);
3868
3869fileinput=[PathName FileName];
3870sizf=size(fileinput);
3871if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3872[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3873ref.filebase=fullfile(Path,File);
3874ref.num_a=stra2num(str_a);
3875ref.num_b=stra2num(str_b);
3876ref.num1=str2double(field_count);
3877ref.num2=str2double(str2);
3878browse=[];%initialisation
3879if ~isequal(ref.ext,'.nc')
3880    msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3881    return
3882end
3883set(handles.ref_fix1,'String',[fullfile(ref.subdir,File) '....nc']);
3884set(handles.ref_fix1,'UserData',ref)
3885menu_field{1}='civ1';
3886Data=nc2struct(fileinput,[]);
3887if isfield(Data,'patch') && isequal(Data.patch,1)
3888    menu_field{2}='filter1';
3889end
3890if isfield(Data,'civ2') && isequal(Data.civ2,1)
3891    menu_field{3}='civ2';
3892end
3893if isfield(Data,'patch2') && isequal(Data.patch2,1)
3894    menu_field{4}='filter2';
3895end
3896set(handles.field_ref1,'String',menu_field);
3897set(handles.field_ref1,'Value',length(menu_field));
3898set(handles.num_MinVel,'Value',2);
3899set(handles.num_MinVel,'String','1');%default threshold
3900set(handles.ref_fix1,'Enable','on')
3901
3902%------------------------------------------------------------------------
3903% --- Executes on button press in get_ref_fix2.
3904function get_ref_fix2_Callback(hObject, eventdata, handles)
3905%------------------------------------------------------------------------
3906if isequal(get(handles.get_ref_fix2,'Value'),1)
3907    filebase=get(handles.RootName,'String');
3908    [FileName, PathName, filterindex] = uigetfile( ...
3909        {'*.nc', ' (*.nc)';
3910        '*.nc',  'netcdf files '; ...
3911        '*.*', 'All Files (*.*)'}, ...
3912        'Pick a file',filebase);
3913    fileinput=[PathName FileName];
3914    sizf=size(fileinput);
3915    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3916    [Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3917    ref.filebase=fullfile(Path,File);
3918    ref.num_a=stra2num(str_a);
3919    ref.num_b=stra2num(str_b);
3920    ref.num1=str2num(field_count);
3921    ref.num2=str2num(str2);
3922    browse=[];%initialisation
3923    if ~isequal(ref.ext,'.nc')
3924        msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3925        return
3926    end
3927    set(handles.ref_fix2,'String',[fullfile(ref.subdir,File) '....nc']);
3928    set(handles.ref_fix2,'UserData',ref)
3929    menu_field{1}='civ1';
3930    Data=nc2struct(fileinput,[]);
3931    if isfield(Data,'patch') && isequal(Data.patch,1)
3932        menu_field{2}='filter1';
3933    end
3934    if isfield(Data,'civ2') && isequal(Data.civ2,1)
3935        menu_field{3}='civ2';
3936    end
3937    if isfield(Data,'patch2') && isequal(Data.patch2,1)
3938        menu_field{4}='filter2';
3939    end
3940    set(handles.field_ref2,'String',menu_field);
3941    set(handles.field_ref2,'Value',length(menu_field));
3942    set(handles.num_MinVel,'Value',2);
3943    set(handles.num_MinVel,'String','1');%default threshold
3944    set(handles.ref_fix2,'Enable','on')
3945    set(handles.ref_fix2,'Visible','on')
3946    set(handles.field_ref2,'Visible','on')
3947else
3948    set(handles.ref_fix2,'Visible','off')
3949    set(handles.field_ref2,'Visible','off')
3950end
3951
3952%------------------------------------------------------------------------
3953function ref_fix1_Callback(hObject, eventdata, handles)
3954%------------------------------------------------------------------------
3955set(handles.num_MinVel,'Value',1);
3956set(handles.field_ref1,'Value',1)
3957set(handles.field_ref1,'String',{' '})
3958set(handles.ref_fix1,'UserData',[]);
3959set(handles.ref_fix1,'String','');
3960set(handles.thresh_vel1,'String','0');
3961
3962%------------------------------------------------------------------------
3963function ref_fix2_Callback(hObject, eventdata, handles)
3964%------------------------------------------------------------------------
3965set(handles.num_MinVel,'Value',1);
3966set(handles.field_ref2,'Value',1)
3967set(handles.field_ref2,'String',{' '})
3968set(handles.ref_fix2,'UserData',[]);
3969set(handles.ref_fix2,'String','');
3970set(handles.num_MinVel,'String','0');
3971
3972%------------------------------------------------------------------------
3973% --- Executes on button press in test_stereo1.
3974function test_stereo1_Callback(hObject, eventdata, handles)
3975%------------------------------------------------------------------------
3976if isequal(get(handles.test_stereo1,'Value'),0)
3977    set(handles.subdomain_patch1,'Visible','on')
3978    set(handles.rho_patch1,'Visible','on')
3979else
3980    set(handles.subdomain_patch1,'Visible','off')
3981    set(handles.rho_patch1,'Visible','off')
3982end
3983
3984%------------------------------------------------------------------------
3985% --- Executes on button press in CheckStereo.
3986function StereoCheck_Callback(hObject, eventdata, handles)
3987%------------------------------------------------------------------------
3988if isequal(get(handles.CheckStereo,'Value'),0)
3989    set(handles.num_SubdomainSize,'Visible','on')
3990    set(handles.num_SmoothingParam,'Visible','on')
3991else
3992    set(handles.num_SubdomainSize,'Visible','off')
3993    set(handles.num_SmoothingParam,'Visible','off')
3994end
3995
3996%------------------------------------------------------------------------
3997% --- Executes on button press in TestCiv1: display image correlation function
3998function TestCiv1_Callback(hObject, eventdata, handles)
3999%------------------------------------------------------------------------
4000set(handles.TestCiv1,'BackgroundColor',[1 1 0])
4001drawnow
4002if get(handles.TestCiv1,'Value')
4003    ref_i=str2double(get(handles.ref_i,'String'));
4004    if strcmp(get(handles.ref_j,'Visible'),'on')
4005        ref_j=str2double(get(handles.ref_j,'String'));
4006    else
4007        ref_j=1;%default
4008    end
4009    [filecell,num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2,nom_type_nc,file_ref_fix1,file_ref_fix2]=...
4010        set_civ_filenames(handles,ref_i,ref_j,[1 0 0 0 0 0]);
4011    Data.ListVarName={'ny','nx','A'};
4012    Data.VarDimName={'ny','nx',{'ny','nx'}};
4013    Data.A=imread(filecell.ima1.civ1{1});
4014    Data.ny=[size(Data.A,1) 1];
4015    Data.nx=[1 size(Data.A,2)];
4016    par_civ1=read_GUI(handles.Civ1);
4017    par_civ1.filename_ima_a=filecell.ima1.civ1{1};
4018    par_civ1.filename_ima_b=filecell.ima2.civ1{1};
4019    par_civ1.T0=0;
4020    par_civ1.Dt=1;
4021    Param.Civ1=par_civ1;
4022    Data=civ_uvmat(Param);
4023    Data.ListVarName=[Data.ListVarName {'ny','nx','A'}];
4024    Data.VarDimName=[Data.VarDimName {'ny','nx',{'ny','nx'}}];
4025    Data.A=imread(filecell.ima1.civ1{1});
4026    Data.ny=[size(Data.A,1) 1];
4027    Data.nx=[1 size(Data.A,2)];
4028    hview_field=view_field(Data);
4029    set(0,'CurrentFigure',hview_field)
4030    hhview_field=guihandles(hview_field);
4031    set(hview_field,'CurrentAxes',hhview_field.axes3)
4032    ViewData=get(hview_field,'UserData');
4033    ViewData.CivHandle=handles.civ;% indicate the handle of the civ GUI in view_field
4034    ViewData.axes3.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
4035    ViewData.axes3.X=Data.Civ1_X; %keep the set of points in memeory
4036    ViewData.axes3.Y=Data.Civ1_Y;
4037    set(hview_field,'UserData',ViewData)
4038    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4039    if isempty(corrfig)
4040        corrfig=figure;
4041        set(corrfig,'tag','corrfig')
4042        set(corrfig,'name','image correlation')
4043        set(corrfig,'DeleteFcn',{@closeview_field})%
4044    end
4045    set(handles.TestCiv1,'BackgroundColor',[1 0 0])
4046else
4047    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4048    if ~isempty(corrfig)
4049        delete(corrfig)
4050    end
4051    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
4052    if ~isempty(hview_field)
4053        delete(hview_field)
4054    end
4055end
4056
4057%-------------------------------------------------------------------
4058% ---
4059function closeview_field(gcbo,eventdata)
4060hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
4061    if ~isempty(hview_field)
4062        delete(hview_field)
4063    end
4064   
4065   
4066%------------------------------------------------------------------------   
4067% call 'view_field.fig' to display the  field selected in the list of 'status'
4068function open_view_field(hObject, eventdata)
4069%------------------------------------------------------------------------
4070list=get(hObject,'String');
4071index=get(hObject,'Value');
4072rootroot=get(hObject,'UserData');
4073filename=list{index};
4074ind_dot=findstr(filename,'...');
4075filename=filename(1:ind_dot-1);
4076filename=fullfile(rootroot,filename);
4077delete(get(hObject,'parent'))%delete the display figure to stop the check process
4078if exist(filename,'file')%visualise the vel field if it exists
4079    uvmat(filename)
4080    set(gcbo,'Value',1)
4081end
4082
4083%------------------------------------------------------------------------   
4084% launched by pressing OK on the status figure
4085function close_GUI(hObject, eventdata)
4086%------------------------------------------------------------------------
4087    delete(gcbf)
4088   
4089%------------------------------------------------------------------------   
4090% launched by deleting the status figure
4091function stop_status(hObject, eventdata)
4092%------------------------------------------------------------------------
4093hciv=findobj(allchild(0),'tag','civ');
4094hhciv=guidata(hciv);
4095set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
4096set(hhciv.status,'BackgroundColor',[0 1 0])
4097
4098%------------------------------------------------------------------------
4099% % --- Executes on button press in ListPairMode.
4100% function CivMode_Callback(hObject, eventdata, handles)
4101% %------------------------------------------------------------------------
4102% Listprog=get(handles.ListPairMode,'String');
4103% index=get(handles.ListPairMode,'Value');
4104% prog=Listprog{index};
4105% switch prog
4106%     case 'MenuCivX'
4107%         set(handles.thresh_patch1,'Visible','off')
4108%         set(handles.thresh_text1,'Visible','off')
4109%         set(handles.num_MaxDiff,'Visible','off')
4110%         set(handles.thresh_text2,'Visible','off')
4111%         set(handles.num_Rho,'Style','edit')
4112%         set(handles.num_Rho,'String','1')
4113%         set(handles.BATCH,'Enable','on')
4114%     case 'CivAll'
4115%         if get(handles.CheckPatch1,'Value')
4116%             set(handles.thresh_patch1,'Visible','on')
4117%             set(handles.thresh_text1,'Visible','on')
4118%         end
4119%         set(handles.num_Rho,'Style','edit')
4120%         set(handles.num_Rho,'String','1')
4121%         set(handles.BATCH,'Enable','on')
4122%     case 'CivUvmat'
4123%       
4124% end
4125
4126
4127
4128
4129%------------------------------------------------------------------------
4130function cmd=cmd_civ1(filename,Param)
4131%------------------------------------------------------------------------
4132%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4133%changes : filename_cmx -> filename ( no extension )
4134filename=regexprep(filename,'.nc',''); %file name for the result
4135Param.Civ1
4136if isequal(Param.Civ1.Dt,'0')
4137    Param.Civ1.Dt='1' ;%case of 'displacement' mode
4138end
4139Param.Civ1.filename_ima_a=regexprep(Param.Civ1.filename_ima_a,'.png','');
4140Param.Civ1.filename_ima_b=regexprep(Param.Civ1.filename_ima_b,'.png','');
4141fid=fopen([filename '.civ1.cmx'],'w');
4142fprintf(fid,['##############   CMX file' '\n' ]);
4143fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.filename_ima_a,'\\','\\\\') '\n' ]);% for windows compatibility
4144fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.filename_ima_b,'\\','\\\\') '\n' ]);% for windows compatibility
4145fprintf(fid,  ['XX' '\n' ]);
4146fprintf(fid,  ['Mask ' Param.Civ1.MaskFlag '\n' ]);
4147fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.MaskName,'\\','\\\\') '\n' ]);
4148fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageInfo.Width) ' ' num2str(Param.Civ1.ImageInfo.Height) '\n' ]);   %VERIFIER CAS GENERAL ?
4149fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.Bx) ' ' num2str(Param.Civ1.By) '\n' ]);
4150fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.Searchx) ' ' num2str(Param.Civ1.Searchy) '\n' ]);
4151fprintf(fid,   ['RO ' num2str(Param.Civ1.Rho) '\n' ]);
4152if isfield(Param.Civ1,'GridName')
4153    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4154else
4155    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
4156end
4157fprintf(fid,   ['XX 1.0' '\n' ]);
4158fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.T0) '\n' ]);
4159fprintf(fid,  ['PixCmXY ' num2str(Param.Civ1.pxcmx) ' ' num2str(Param.Civ1.pxcmy) '\n' ]);
4160fprintf(fid,  ['XX 1' '\n' ]);
4161fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.Shiftx) ' '  num2str(Param.Civ1.Shifty) '\n' ]);
4162if isfield(Param.Civ1,'GridName')
4163    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4164    fprintf(fid,   ['GridName ' regexprep(Param.Civ1.GridName,'\\','\\\\') '\n' ]);
4165else
4166    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4167    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4168end
4169fprintf(fid,   ['XX 85' '\n' ]);
4170fprintf(fid,   ['XX 1.0' '\n' ]);
4171fprintf(fid,   ['XX 1.0' '\n' ]);
4172fprintf(fid,   ['Hart 1' '\n' ]);
4173fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
4174fprintf(fid,   ['Deformation 0' '\n' ]);
4175fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4176fprintf(fid,   ['IntensityMin 0' '\n' ]);
4177if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
4178    fprintf(fid,  ['SeuilImage n' '\n' ]);
4179    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4180else% Image threshold  activated
4181    if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
4182        Param.Civ1.MaxIma=2^Param.Civ1.ImageInfo.BitDepth;%take the max image value as upper bound by default
4183    end
4184    fprintf(fid,  ['SeuilImage y' '\n' ]);
4185    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
4186end
4187fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
4188fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
4189fclose(fid);
4190
4191if(isunix) %unix (or Mac) system
4192    cmd=['cp -f ' filename '.civ1.cmx ' filename '.cmx \n '];% the cmx file gives the name to the nc file
4193    cmd=[cmd Param.xml.Civ1Bin ' -f ' filename '.cmx >' filename '.civ1.log \n ' ]; % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
4194    cmd=[cmd 'rm ' filename '.cmx'];
4195else %Windows system
4196    filename=regexprep(filename,'\\','\\\\');
4197    cmd=['copy /Y "' filename '.civ1.cmx" "' filename '.cmx" \n '];
4198    cmd=[cmd '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\')...
4199        '" -f "' filename '.cmx" >"' filename '.civ1.log" \n ' ]; % redirect standard output to the log file
4200    cmd=[cmd 'del "' filename '.cmx"'];
4201end
4202
4203
4204function cmd=cmd_fix(filename,Param,fixname)
4205%%
4206switch fixname
4207    case 'Fix1'
4208        fi2_value=num2str(Param.(fixname).CheckF2);
4209    case 'Fix2'
4210        fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
4211end
4212filename=regexprep(filename,'.nc','');
4213MaskName_string='';%default
4214if Param.(fixname).CheckMask
4215    MaskName_string=[' -maskName "' Param.(fixname).MaskName '"'];
4216end
4217MaxVel_string='';%default
4218if ~isempty(Param.(fixname).MaxVel)
4219    MaxVel_string=[' -threshV ' num2str(Param.(fixname).MaxVel)];
4220end
4221if isunix
4222    cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
4223        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4224        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4225        ' >' filename '.' lower(fixname) '.log 2>&1'];
4226else
4227    cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
4228        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4229        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4230        ' > "' filename '.' lower(fixname) '.log"'];
4231    cmd=regexprep(cmd,'\\','\\\\');
4232end
4233
4234
4235function cmd=cmd_patch(filename,Param,patchname)
4236%% ------------------------------------------------------------------------
4237filename=regexprep(filename,'.nc','');
4238if isunix
4239    cmd=[Param.xml.PatchBin...
4240        ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
4241        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).SmoothingParam)...
4242        ' -nopt ' num2str(Param.(patchname).SubdomainSize) ...
4243        '  > ' filename '.' lower(patchname) '.log 2>&1']; % redirect standard output to the log file
4244else
4245    cmd=['"' Param.xml.PatchBin...
4246        '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
4247        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).SmoothingParam)...
4248        ' -nopt ' num2str(Param.(patchname).SubdomainSize)...
4249        '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
4250    cmd=regexprep(cmd,'\\','\\\\');
4251end
4252
4253%------------------------------------------------------------------------
4254% --- CheckCiv2  CheckCiv2  CheckCiv2 CheckCiv2
4255function cmd=cmd_civ2(filename,Param)
4256%------------------------------------------------------------------------
4257%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4258% global civ2Bin sge%name of the executable for checkciv1 calculation
4259filename=regexprep(filename,'.nc','');
4260if isequal(Param.Civ2.Dt,'0')
4261    Param.Civ2.Dt='1' ;%case of 'displacement' mode
4262end
4263Param.Civ2.filename_ima_a=regexprep(Param.Civ2.filename_ima_a,'.png','');
4264Param.Civ2.filename_ima_b=regexprep(Param.Civ2.filename_ima_b,'.png','');% bug : .png appears two times ?
4265[fid,errormsg]=fopen([filename '.civ2.cmx'],'w');
4266if isequal(fid,-1)
4267    msgbox_uvmat('ERROR',errormsg)
4268    cmd='';
4269    return
4270end
4271fprintf(fid,['##############   CMX file' '\n' ]);
4272fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.filename_ima_a,'\\','\\\\') '\n' ]);% for windows compatibility
4273fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.filename_ima_b,'\\','\\\\') '\n' ]);% for windows compatibility
4274fprintf(fid,  ['XX' '\n' ]);
4275fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
4276fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
4277fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageInfo.Width) ' ' num2str(Param.Civ2.ImageInfo.Height) '\n' ]); 
4278% fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
4279fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.Bx) ' ' num2str(Param.Civ2.By) '\n' ]);
4280fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.Bx) ' ' num2str(Param.Civ2.By) '\n']);
4281fprintf(fid, ['RO ' num2str(Param.Civ2.Rho) '\n']);
4282if isfield(Param.Civ2,'GridName')
4283    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4284else
4285    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
4286end
4287% fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
4288fprintf(fid, ['XX 1.0' '\n' ]);
4289fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.T0) '\n' ]);
4290fprintf(fid, ['PixCmXY ' num2str(Param.Civ2.pxcmx) ' ' num2str(Param.Civ2.pxcmy) '\n' ]);
4291fprintf(fid, ['XX 1' '\n' ]);
4292fprintf(fid, 'ShiftXY 0 0\n');
4293if isfield(Param.Civ2,'GridName')
4294    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4295    fprintf(fid,   ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n' ]);
4296else
4297    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4298    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4299end
4300% fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
4301% fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
4302fprintf(fid, ['XX 85' '\n' ]);
4303fprintf(fid, ['XX 1.0' '\n' ]);
4304fprintf(fid, ['XX 1.0' '\n' ]);
4305fprintf(fid, ['Hart 1' '\n' ]);
4306fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
4307fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
4308fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4309fprintf(fid,   ['IntensityMin 0' '\n' ]);
4310
4311if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
4312    fprintf(fid,  ['SeuilImage n' '\n' ]);
4313    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4314else% Image threshold  activated
4315    if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
4316        Param.Civ2.MaxIma=2^Param.Civ2.ImageInfo.BitDepth;%take the max image value as upper bound by default
4317    end
4318    fprintf(fid,  ['SeuilImage y' '\n' ]);
4319    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
4320end
4321fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
4322fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
4323fclose(fid);
4324
4325if(isunix)
4326    cmd=['cp -f ' filename '.civ2.cmx ' filename '.cmx\n'...
4327        Param.xml.Civ2Bin ' -f ' filename  '.cmx >' filename '.civ2.log \n '... % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
4328        'rm ' filename '.cmx \n'];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
4329else
4330    filename=regexprep(filename,'\\','\\\\');
4331    cmd=['copy /Y "' filename '.civ2.cmx" "' filename '.cmx" \n'...
4332        '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f "' filename  '.cmx" >"' filename '.civ2.log" \n'...
4333        'del "' filename '.cmx" \n'];
4334end
4335
4336%------------------------------------------------------------------------
4337% --- Executes on button press in CheckThreshold.
4338function CheckThreshold_Callback(hObject, eventdata, handles)
4339%------------------------------------------------------------------------
4340huipanel=get(hObject,'parent');
4341obj(1)=findobj(huipanel,'Tag','num_MinIma');
4342obj(2)=findobj(huipanel,'Tag','num_MaxIma');
4343obj(3)=findobj(huipanel,'Tag','title_Threshold');
4344if get(hObject,'Value')
4345    set(obj,'Visible','on')
4346else
4347    set(obj,'Visible','off')
4348end
4349
4350%------------------------------------------------------------------------
4351% --- CheckCiv1  Unified: TO ABADON
4352function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
4353%------------------------------------------------------------------------
4354%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4355%global CivBin%name of the executable for checkciv1 calculation
4356
4357civ1.image1=par.filename_ima_a;
4358civ1.image2=par.filename_ima_b;
4359civ1.imageSize_X=par.npx;
4360civ1.imageSize_Y=par.npy;
4361civ1.outputFileName=[filename '.nc'];
4362civ1.correlationBoxesSize_X=par.ibx;
4363civ1.correlationBoxesSize_Y=par.iby;
4364civ1.searchBoxesSize_X=par.isx;
4365civ1.searchBoxesSize_Y=par.isy;
4366civ1.globalShift_X=par.shiftx;
4367civ1.globalShift_Y=par.shifty;
4368civ1.ro=par.rho;
4369civ1.hart='y';
4370if isequal(par.gridflag,'y')
4371    civ1.grid=par.gridname;
4372else
4373    civ1.grid='n';
4374    civ1.gridSpacing_X=par.dx;
4375    civ1.gridSpacing_Y=par.dy;
4376end
4377if isequal(par.maskflag,'y')
4378    civ1.mask=par.maskname;
4379end
4380civ1.dt=par.Dt;
4381civ1.unit='pixel';
4382civ1.absolut_time_T0=par.T0;
4383civ1.pixcmx=par.pxcmx;
4384civ1.pixcmy=par.pxcmy;
4385civ1.convectFlow='n';
4386
4387xml_civ1_parameters=civ1;
4388
4389%------------------------------------------------------------------------
4390% --- CheckCiv2  Unified: TO ABADON
4391function civ2=CIV2_CMD_Unified(filename,namelog,par)
4392%------------------------------------------------------------------------
4393%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4394%global CivBin%name of the executable for checkciv1 calculation
4395
4396filename=regexprep(filename,'.nc','');
4397
4398civ2.image1=par.filename_ima_a;
4399civ2.image2=par.filename_ima_b;
4400civ2.imageSize_X=par.npx;
4401civ2.imageSize_Y=par.npy;
4402civ2.inputFileName=[par.filename_nc1 '.nc'];
4403civ2.outputFileName=[filename '.nc'];
4404civ2.correlationBoxesSize_X=par.ibx;
4405civ2.correlationBoxesSize_Y=par.iby;
4406civ2.ro=par.rho;
4407%checkciv2.decimalShift=par.CheckDecimal;
4408%checkciv2.CheckDeformation=par.CheckDeformation;
4409if isequal(par.decimal,'1')
4410    civ2.decimalShift='y';
4411else
4412    civ2.decimalShift='n';
4413end
4414if isequal(par.deformation,'1')
4415    civ2.deformation='y';
4416else
4417    civ2.deformation='n';
4418end
4419if isequal(par.gridflag,'y')
4420    civ2.grid=par.gridname;
4421else
4422    civ2.grid='n';
4423    civ2.gridSpacing_X=par.dx;
4424    civ2.gridSpacing_Y=par.dy;
4425end
4426civ2.gridSpacing_X='10';
4427civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
4428if isequal(par.maskflag,'y')
4429    civ2.mask=par.maskname;
4430else
4431    civ2.mask='n';
4432end
4433civ2.dt=par.Dt;
4434civ2.unit='pixel';
4435civ2.absolut_time_T0=par.T0;
4436civ2.pixcmx=par.pxcmx;
4437civ2.pixcmy=par.pxcmy;
4438civ2.convectFlow='n';
4439civ2.pixcmx=par.pxcmx;
4440civ2.pixcmy=par.pxcmy;
4441civ2.convectFlow='n';
Note: See TracBrowser for help on using the repository browser.