Changeset 598 for trunk/src/series


Ignore:
Timestamp:
Apr 2, 2013, 9:13:42 AM (11 years ago)
Author:
sommeria
Message:

various bugs repaired . civ_series further developed

Location:
trunk/src/series
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/series/aver_stat.m

    r596 r598  
    166166end
    167167
    168 %% MAIN LOOP ON SLICES
    169168% for i_slice=1:NbSlice
    170    % index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
    171     nbfiles=0;
    172     nbmissing=0;
    173 
    174     %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
    175     for index=1:nbfield
    176     %for index=index_slice
    177           if checkrun
    178                 stopstate=get(Param.RUNHandle,'BusyAction');
    179                 update_waitbar(Param.WaitbarHandle,index/nbfield)
    180           else
    181                 stopstate='queue';
    182           end
    183         if isequal(stopstate,'queue')% enable STOP command
    184            
    185         %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
    186         for iview=1:nbview
    187             % reading input file(s)
    188             [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
     169% index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
     170nbfiles=0;
     171nbmissing=0;
     172
     173%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
     174for index=1:nbfield
     175%for index=index_slice
     176      if checkrun
     177            stopstate=get(Param.RUNHandle,'BusyAction');
     178            update_waitbar(Param.WaitbarHandle,index/nbfield)
     179      else
     180            stopstate='queue';
     181      end
     182    if isequal(stopstate,'queue')% enable STOP command
     183
     184    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
     185    for iview=1:nbview
     186        % reading input file(s)
     187        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
     188        if ~isempty(errormsg)
     189            errormsg=['error of input reading: ' errormsg];
     190            break
     191        end
     192        if ~isempty(NbSlice_calib)
     193            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
     194        end
     195    end
     196    else
     197        errormsg='stop';
     198    end
     199    %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
     200    %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
     201    % EDIT FROM HERE
     202
     203    if isempty(errormsg)
     204        Field=Data{1}; % default input field structure
     205        %% coordinate transform (or other user defined transform)
     206        if ~isempty(transform_fct)
     207            switch nargin(transform_fct)
     208                case 4
     209                    if length(Data)==2
     210                        Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
     211                    else
     212                        Field=transform_fct(Data{1},XmlData{1});
     213                    end
     214                case 3
     215                    if length(Data)==2
     216                        Field=transform_fct(Data{1},XmlData{1},Data{2});
     217                    else
     218                        Field=transform_fct(Data{1},XmlData{1});
     219                    end
     220                case 2
     221                    Field=transform_fct(Data{1},XmlData{1});
     222                case 1
     223                    Field=transform_fct(Data{1});
     224            end
     225        end
     226
     227        %% calculate tps coefficients if needed
     228        if isfield(Param,'ProjObject')&&isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
     229            Field=tps_coeff_field(Field,check_proj_tps);
     230        end
     231
     232        %field projection on an object
     233        if Param.CheckObject
     234            [Field,errormsg]=proj_field(Field,Param.ProjObject);
    189235            if ~isempty(errormsg)
    190                 errormsg=['error of input reading: ' errormsg];
    191                 break
    192             end
    193             if ~isempty(NbSlice_calib)
    194                 Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
    195             end
    196         end
    197         else
    198             errormsg='stop';
    199         end
    200         %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
    201         %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
    202         % EDIT FROM HERE
    203    
    204         if isempty(errormsg)
    205             Field=Data{1}; % default input field structure
    206             %% coordinate transform (or other user defined transform)
    207             if ~isempty(transform_fct)
    208                 switch nargin(transform_fct)
    209                     case 4
    210                         if length(Data)==2
    211                             Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
    212                         else
    213                             Field=transform_fct(Data{1},XmlData{1});
    214                         end
    215                     case 3
    216                         if length(Data)==2
    217                             Field=transform_fct(Data{1},XmlData{1},Data{2});
    218                         else
    219                             Field=transform_fct(Data{1},XmlData{1});
    220                         end
    221                     case 2
    222                         Field=transform_fct(Data{1},XmlData{1});
    223                     case 1
    224                         Field=transform_fct(Data{1});
     236                msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
     237                return
     238            end
     239        end
     240        nbfiles=nbfiles+1;
     241
     242        %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
     243        %update sum
     244        if nbfiles==1 %first field
     245            time_1=[];
     246            if isfield(Field,'Time')
     247                time_1=Field.Time(1);
     248            end
     249            DataOut=Field;%default
     250            for ivar=1:length(Field.ListVarName)
     251                VarName=Field.ListVarName{ivar};
     252                DataOut.(VarName)=double(DataOut.(VarName));
     253            end
     254        else   %current field
     255            for ivar=1:length(Field.ListVarName)
     256                VarName=Field.ListVarName{ivar};
     257                sizmean=size(DataOut.(VarName));
     258                siz=size(Field.(VarName));
     259                if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
     260                    msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
     261                    return
     262                else
     263                    DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
    225264                end
    226265            end
    227            
    228             %% calculate tps coefficients if needed
    229             if isfield(Param,'ProjObject')&&isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
    230                 Field=tps_coeff_field(Field,check_proj_tps);
    231             end
    232 
    233             %field projection on an object
    234             if Param.CheckObject
    235                 [Field,errormsg]=proj_field(Field,Param.ProjObject);
    236                 if ~isempty(errormsg)
    237                     msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
    238                     return
    239                 end
    240             end
    241             nbfiles=nbfiles+1;
    242            
    243             %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
    244             %update sum
    245             if nbfiles==1 %first field
    246                 time_1=[];
    247                 if isfield(Field,'Time')
    248                     time_1=Field.Time(1);
    249                 end
    250                 DataOut=Field;%default
    251                 for ivar=1:length(Field.ListVarName)
    252                     VarName=Field.ListVarName{ivar};
    253                     DataOut.(VarName)=double(DataOut.(VarName));
    254                 end
    255             else   %current field
    256                 for ivar=1:length(Field.ListVarName)
    257                     VarName=Field.ListVarName{ivar};
    258                     sizmean=size(DataOut.(VarName));
    259                     siz=size(Field.(VarName));
    260                     if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
    261                         msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
    262                         return
    263                     else
    264                         DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
    265                     end
    266                 end
    267             end
    268             %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
    269         else
    270             display(errormsg)
    271         end
    272     end
    273     %%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
    274    
    275     for ivar=1:length(Field.ListVarName)
    276         VarName=Field.ListVarName{ivar};
    277         DataOut.(VarName)=DataOut.(VarName)/nbfiles; % normalize the mean
    278     end
    279     if nbmissing~=0
    280         msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
    281     end
    282     if isempty(time) % time is read from files
    283         if isfield(Field,'Time')
    284             time_end=Field.Time(1);%last time read
    285             if ~isempty(time_1)
    286                 DataOut.Time=time_1;
    287                 DataOut.Time_end=time_end;
    288             end
    289         end
    290     else  % time from ImaDoc prevails if it exists
     266        end
     267        %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
     268    else
     269        display(errormsg)
     270    end
     271end
     272%%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
     273
     274for ivar=1:length(Field.ListVarName)
     275    VarName=Field.ListVarName{ivar};
     276    DataOut.(VarName)=DataOut.(VarName)/nbfiles; % normalize the mean
     277end
     278if nbmissing~=0
     279    msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
     280end
     281if isempty(time) % time is read from files
     282    if isfield(Field,'Time')
     283        time_end=Field.Time(1);%last time read
     284        if ~isempty(time_1)
     285            DataOut.Time=time_1;
     286            DataOut.Time_end=time_end;
     287        end
     288    end
     289else  % time from ImaDoc prevails if it exists
    291290%         j1=1;%default
    292291%         if ~isempty(j1_series{1})
    293292%             j1=j1_series{1};
    294293%         end
    295         %DataOut.Time=time(1,i1_series{1}(1),j1);
    296         %DataOut.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
    297         DataOut.Time=time(1);
    298         DataOut.Time_end=time(end);
    299     end
    300    
    301     %writting the result file
    302     OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),j1_series{1}(1),j1_series{1}(end));
    303     if CheckImage{1} %case of images
    304         if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
    305             DataOut.A=uint16(DataOut.A);
    306             imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
    307         else
    308             DataOut.A=uint8(DataOut.A);
    309             imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
    310         end
     294    %DataOut.Time=time(1,i1_series{1}(1),j1);
     295    %DataOut.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
     296    DataOut.Time=time(1);
     297    DataOut.Time_end=time(end);
     298end
     299
     300%writting the result file
     301OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),j1_series{1}(1),j1_series{1}(end));
     302if CheckImage{1} %case of images
     303    if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
     304        DataOut.A=uint16(DataOut.A);
     305        imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
     306    else
     307        DataOut.A=uint8(DataOut.A);
     308        imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
     309    end
     310    display([OutputFile ' written']);
     311else %case of netcdf input file , determine global attributes
     312    errormsg=struct2nc(OutputFile,DataOut); %save result file
     313    if isempty(errormsg)
    311314        display([OutputFile ' written']);
    312     else %case of netcdf input file , determine global attributes
    313         errormsg=struct2nc(OutputFile,DataOut); %save result file
    314         if isempty(errormsg)
    315             display([OutputFile ' written']);
    316         else
    317             msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
    318             display(errormsg)
    319         end
    320     end  % end averaging  loop
     315    else
     316        msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
     317        display(errormsg)
     318    end
     319end  % end averaging  loop
    321320% end
    322321%%%%%%%%%%%%%%%% end loop on slices %%%%%%%%%%%%%%%%
  • trunk/src/series/civ_input.m

    r597 r598  
    2525
    2626
    27 % Last Modified by GUIDE v2.5 30-Mar-2013 09:15:21
     27% Last Modified by GUIDE v2.5 01-Apr-2013 10:00:57
    2828% Begin initialization code - DO NOT EDIT
    2929gui_Singleton = 1;
     
    3535    'gui_Callback',   []);
    3636
    37 if nargin
    38     if ischar(varargin{1}) && ~isempty(regexp(varargin{1},'_Callback$','once'))
     37if nargin && ischar(varargin{1}) && ~isempty(regexp(varargin{1},'_Callback$','once'))
    3938        gui_State.gui_Callback = str2func(varargin{1});
    40     elseif isstruct(varargin{1}) && isequal(varargin{1}.Action.RUN,0)
    41         % set the input elements needed on the GUI series when the action is selected in the menu ActionName
    42         ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
    43             ParamOut.WholeIndexRange='off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
    44             ParamOut.NbSlice='off'; ...%nbre of slices ('off' by default)
    45             ParamOut.VelType='two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
    46             ParamOut.FieldName='two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
    47             ParamOut.FieldTransform = 'off';...%can use a transform function
    48             ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
    49             ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
    50             ParamOut.OutputDirExt='.civ';%set the output dir extension
    51     end
    5239end
    5340
     
    7158set(hObject,'WindowButtonDownFcn',{'mouse_down'}) % allows mouse action with right button (zoom for uicontrol display)
    7259
    73 %% Adjust the GUI according to the binaries available in PARAM.xml
    74 path_civ=fileparts(which('civ_series')); %path to civ
    75 addpath (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)
    76 errormsg=[];%default error message
    77 xmlfile=fullfile(path_civ,'PARAM.xml');
    78 test_batch=0;%default: ,no batch mode available
    79 sparam=[];
    80 if ~exist(xmlfile,'file')
    81     [success,message]=copyfile(fullfile(path_civ,'PARAM.xml.default'),xmlfile);
    82 end
    83 if exist(xmlfile,'file')
    84     try
    85         t=xmltree(xmlfile);
    86         sparam=convert(t);
    87     catch ME
    88         errormsg={' Unable to read the file PARAM.xml defining the civx binaries:';ME.message};
    89          msgbox_uvmat('WARNING',errormsg);
    90     end
    91 else
    92     [s,w]=system('oarstat');
    93     if ~isequal(s,0)
    94         [s,w]=system('qstat');
    95     end
    96     if isequal(s,0)
    97         test_batch=1;
    98     end           
    99 end
    100 if isfield(sparam,'BatchParam') && isfield(sparam.BatchParam,'BatchMode')
    101     batch_mode=sparam.BatchParam.BatchMode;
    102     test_command='';
    103     switch batch_mode
    104         case 'sge'
    105             test_command='qstat';
    106         case 'oar'
    107             test_command='oarstat';
    108     end
    109     if ~isempty(test_command)
    110         [s,w]=system(test_command);
    111         if isequal(s,0)
    112             test_batch=1;
    113         end
    114     end
    115 end
    116 RUNVal=get(handles.RunMode,'Value');
    117 if test_batch==0
    118    if RUNVal>2
    119        set(handles.RunMode,'Value',1)
    120    end
    121    set(handles.RunMode,'String',{'local';'background'})
    122 else
    123     set(handles.RunMode,'String',{'local';'background';'cluster'})
    124 end
    125 
    126 %% load the list of previously browsed files in the upper bar menu Open/
    127 dir_perso=prefdir; % path to the directory .matlab for personal data
    128 profil_perso=fullfile(dir_perso,'uvmat_perso.mat');% personal data file uvmauvmat_perso.mat' in .matlab
    129 if exist(profil_perso,'file')
    130     h=load (profil_perso);
    131     if isfield(h,'MenuFile')
    132         for ifile=1:min(length(h.MenuFile),5)
    133             eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',h.MenuFile{ifile});'])
    134         end
    135     end
    136 end
    137 
    138 %% prepare the GUI with parameters from the input file if opened from uvmat
     60%% set visibility options
     61        set(handles.num_MaxDiff,'Visible','on')
     62        set(handles.num_MaxVel,'Visible','on')
     63        set(handles.title_MaxVel,'Visible','on')
     64        set(handles.title_MaxDiff,'Visible','on')
     65        set(handles.num_Nx,'Visible','off')
     66        set(handles.num_Ny,'Visible','off')
     67        set(handles.title_Nx,'Visible','off')
     68        set(handles.title_Ny,'Visible','off')
     69        set(handles.num_CorrSmooth,'Style','popupmenu')
     70        set(handles.num_CorrSmooth,'Value',1)
     71        set(handles.num_CorrSmooth,'String',{'1';'2'})
     72        set(handles.CheckThreshold,'Visible','on')
     73        set(handles.CheckDeformation,'Value',0)% desactivate (work in progress)
     74        set(handles.CheckDecimal,'Value',0)% desactivate (work in progress)
     75       
     76%% prepare the GUI with input parameters
     77% from the GUI series
     78
     79%from the input file
    13980filecell=get_file_series(Param);
    140     set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
    141     errormsg=display_file_name(handles,filecell{1});
    142     if ~isempty(errormsg)
    143         msgbox_uvmat('ERROR',errormsg)
    144     end
    145     set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
    146    
    147     set(handles.civ_series,'WindowStyle','modal')% Make the GUI modal
     81set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
     82errormsg=display_file_name(handles,filecell{1});
     83if ~isempty(errormsg)
     84    msgbox_uvmat('ERROR',errormsg)
     85end
     86set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
     87if isfield(Param,'ActionInput')&&isfield(Param.ActionInput,'Program')&& strcmp(Param.ActionInput.Program,'civ_series')
     88    fill_GUI(Param.ActionInput,handles.civ_input)
     89end
     90set(handles.civ_input,'WindowStyle','modal')% Make the GUI modal
    14891drawnow
    149 uiwait(handles.civ_series);
     92uiwait(handles.civ_input);
    15093
    15194%Program_Callback([],[], handles)
     
    157100% Get default command line output from handles structure
    158101varargout{1} = handles.output;
    159 delete(handles.civ_series)
     102delete(handles.civ_input)
    160103
    161104% --- Executes when user attempts to close get_field.
    162 function civ_series_CloseRequestFcn(hObject, eventdata, handles)
     105function civ_input_CloseRequestFcn(hObject, eventdata, handles)
    163106if isequal(get(handles.get_field, 'waitstatus'), 'waiting')
    164107    % The GUI is still in UIWAIT, us UIRESUME
    165     uiresume(handles.civ_series);
     108    uiresume(handles.civ_input);
    166109else
    167110    % The GUI is no longer waiting, just close it
    168     delete(handles.civ_series);
     111    delete(handles.civ_input);
    169112end
    170113%------------------------------------------------------------------------
     
    343286
    344287%% enable OK, BATCH button and 'status' display
    345 set(handles.OK, 'Enable','On')
    346 set(handles.OK,'BackgroundColor',[1 0 0])%set RUN button to red color
    347 if isfield(handles,'status')
    348     set(handles.status,'Value',0);       %suppress the 'status' display
    349     status_Callback([], [], handles)
    350 end
     288% set(handles.OK, 'Enable','On')
     289% set(handles.OK,'BackgroundColor',[1 0 0])%set RUN button to red color
     290% if isfield(handles,'status')
     291%     set(handles.status,'Value',0);       %suppress the 'status' display
     292%     status_Callback([], [], handles)
     293% end
    351294
    352295%% determine nomenclature types and extension of the input files
     
    861804%------------------------------------------------------------------------
    862805
    863 handles.output.ActionInput=read_GUI(handles.civ_series);
     806handles.output.ActionInput=read_GUI(handles.civ_input);
    864807guidata(hObject, handles);% Update handles structure
    865 uiresume(handles.civ_series);
     808uiresume(handles.civ_input);
    866809drawnow
    867810
     
    886829end
    887830
    888 %-------------------------------------------------------------------
    889 % --- Executes on button press in status.
    890 function status_Callback(hObject, eventdata, handles)
    891 %-------------------------------------------------------------------
    892 val=get(handles.status,'Value');
    893 if val==0
    894     set(handles.status,'BackgroundColor',[0 1 0])
    895     hfig=findobj(allchild(0),'name','civ_status');
    896     if ~isempty(hfig)
    897         delete(hfig)
    898     end
    899     return
    900 end
    901 set(handles.status,'BackgroundColor',[1 1 0])
    902 drawnow
    903 listtype={'civ1','fix1','patch1','civ2','fix2','patch2'};
    904 Param.CheckCiv1=get(handles.CheckCiv1,'Value');
    905 Param.CheckFix1=get(handles.CheckFix1,'Value');
    906 Param.CheckPatch1=get(handles.CheckPatch1,'Value');
    907 Param.CheckCiv2=get(handles.CheckCiv2,'Value');
    908 Param.CheckFix2=get(handles.CheckFix2,'Value');
    909 Param.CheckPatch2=get(handles.CheckPatch2,'Value');
    910 box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
    911 
    912 option_civ=find(box_test,1,'last');%last selected option (non-zero index of box_test)
    913 filecell=get(handles.civ_series,'UserData');%retrieve the list of output files expected for PIV
    914 test_new=0;
    915 if ~isfield(filecell,'nc')
    916     test_new=1;
    917     [ref_i,ref_j,errormsg]=find_ref_indices(handles);
    918     if ~isempty(errormsg)
    919         msgbox_uvmat('ERROR',errormsg)
    920         return
    921     end
    922     filecell=set_civ_filenames(handles,ref_i,ref_j,box_test);%determine the output file expected from the GUI status
    923 end
    924 if ~isequal(box_test(4:6),[0 0 0])
    925     civ_files=filecell.nc.civ2;%case of civ2 operations
    926 else
    927     civ_files=filecell.nc.civ1;
    928 end
    929 [root,filename,ext]=fileparts(civ_files{1});
    930 [rootroot,SubDir,extdir]=fileparts(root);
    931 hfig=findobj(allchild(0),'name','civ_status');
    932 if isempty(hfig)
    933     hfig=figure('DeleteFcn',@stop_status);
    934     set(hfig,'MenuBar','none')% suppress the menu bar
    935     set(hfig,'NumberTitle','off')%suppress the fig number in the title
    936     set(hfig,'name','civ_status')
    937     set(hfig,'tag','civ_status')
    938     set(hfig,'UserData',civ_files)
    939     hlist= uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', {'open_uvmat'},'tag','list');
    940     uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','msgbox','Max',2,'String','checking files...');
    941     uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
    942     %uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@close_GUI);
    943     uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@stop_status);
    944     hrefresh=uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.1 0.01 0.2 0.07],'String','Refresh','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@refresh_GUI);
    945     BarPosition=[0.05 0.81 0.01 0.05];
    946     uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
    947     drawnow
    948 end
    949 StatusData.time_ref=get(handles.OK,'UserData');% get the time of launch
    950 StatusData.option_civ=option_civ;
    951 set(hrefresh,'UserData',StatusData)
    952 filepath=fileparts(civ_files{1});
    953 set(hlist,'UserData',fileparts(filepath))
    954 refresh_GUI(hrefresh,[])
    955 
    956 %------------------------------------------------------------------------   
    957 % launched by refreshing the status figure
    958 function refresh_GUI(hObject, eventdata)
    959 %------------------------------------------------------------------------
    960 Tabchar={};
    961 BarPosition=[0.05 0.81 0.01 0.05];
    962 hfig=get(hObject,'parent');
    963 StatusData=get(hObject,'UserData');
    964 civ_files=get(hfig,'UserData');
    965 [filepath,filename,ext]=fileparts(civ_files{1});
    966 [tild,SubDir,extdir]=fileparts(filepath);
    967 SubDir=[SubDir extdir];
    968 option_civ=StatusData.option_civ;
    969 nbfiles=numel(civ_files);
    970 testrecent=0;
    971 count=0;
    972 datnum=zeros(1,nbfiles);
    973 filefound=cell(1,nbfiles);
    974 for ifile=1:nbfiles
    975     detect=exist(civ_files{ifile},'file'); % check the existence of the file
    976     option=0;
    977     if detect==0
    978         option_str='not created';
    979     else
    980         datfile=dir(civ_files{ifile});
    981         if isfield(datfile,'datenum')
    982             datnum(ifile)=datfile.datenum;%only available in recent matlab versions
    983             testrecent=1;
    984         end
    985         filefound(ifile)={datfile.name};
    986        
    987         % check the content  netcdf file
    988         Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','CivStage','patch2','fix2','civ2','patch','fix');
    989         option_list={'civ1','fix1','patch1','civ2','fix2','patch2'};
    990         if ~isempty(Data.CivStage)
    991             option=Data.CivStage;%case of Matlab civ
    992         else
    993             if ~isempty(Data.patch2) && isequal(Data.patch2,1)
    994                 option=6;
    995             elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
    996                 option=5;
    997             elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
    998                 option=4;
    999             elseif ~isempty(Data.patch) && isequal(Data.patch,1);
    1000                 option=3;
    1001             elseif ~isempty(Data.fix) && isequal(Data.fix,1);
    1002                 option=2;
    1003             else
    1004                 option=1;
    1005             end
    1006         end
    1007         option_str=option_list{option};
    1008         if datnum(ifile)<StatusData.time_ref
    1009             option_str=[option_str '  --OLD--'];
    1010         end
    1011     end
    1012     if option >= option_civ
    1013         count=count+1;
    1014     end
    1015     [filepath,filename,ext]=fileparts(civ_files{ifile});
    1016     Tabchar{ifile,1}=[fullfile(SubDir,filename) ext  '...' option_str];
    1017 end
    1018 datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
    1019 if isempty(datnum)
    1020     if testrecent
    1021         message='no civ result created yet';
    1022     else
    1023         message='';
    1024     end
    1025 else
    1026     datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
    1027     [first,ind]=min(datnum);
    1028     [last,indlast]=max(datnum);
    1029     message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
    1030         ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
    1031 end
    1032 hlist=findobj(hfig,'tag','list');
    1033 hmsgbox=findobj(hfig,'tag','msgbox');
    1034 hwaitbar=findobj(hfig,'tag','waitbar');
    1035 set(hlist,'String',Tabchar)
    1036 set(hmsgbox,'String', message)
    1037 if count>0 %&& ~test_new
    1038     BarPosition(3)=0.9*count/nbfiles;
    1039     set(hwaitbar,'Position',BarPosition)
    1040 end
    1041 
    1042 
    1043 %------------------------------------------------------------------------   
    1044 % launched by deleting the status figure
    1045 function stop_status(hObject, eventdata)
    1046 %------------------------------------------------------------------------
    1047 hciv=findobj(allchild(0),'tag','civ');
    1048 hhciv=guidata(hciv);
    1049 set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
    1050 set(hhciv.status,'BackgroundColor',[0 1 0])
     831% %-------------------------------------------------------------------
     832% % --- Executes on button press in status.
     833% function status_Callback(hObject, eventdata, handles)
     834% %-------------------------------------------------------------------
     835% val=get(handles.status,'Value');
     836% if val==0
     837%     set(handles.status,'BackgroundColor',[0 1 0])
     838%     hfig=findobj(allchild(0),'name','civ_status');
     839%     if ~isempty(hfig)
     840%         delete(hfig)
     841%     end
     842%     return
     843% end
     844% set(handles.status,'BackgroundColor',[1 1 0])
     845% drawnow
     846% listtype={'civ1','fix1','patch1','civ2','fix2','patch2'};
     847% Param.CheckCiv1=get(handles.CheckCiv1,'Value');
     848% Param.CheckFix1=get(handles.CheckFix1,'Value');
     849% Param.CheckPatch1=get(handles.CheckPatch1,'Value');
     850% Param.CheckCiv2=get(handles.CheckCiv2,'Value');
     851% Param.CheckFix2=get(handles.CheckFix2,'Value');
     852% Param.CheckPatch2=get(handles.CheckPatch2,'Value');
     853% box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
     854%
     855% option_civ=find(box_test,1,'last');%last selected option (non-zero index of box_test)
     856% filecell=get(handles.civ_input,'UserData');%retrieve the list of output files expected for PIV
     857% test_new=0;
     858% if ~isfield(filecell,'nc')
     859%     test_new=1;
     860%     [ref_i,ref_j,errormsg]=find_ref_indices(handles);
     861%     if ~isempty(errormsg)
     862%         msgbox_uvmat('ERROR',errormsg)
     863%         return
     864%     end
     865%     filecell=set_civ_filenames(handles,ref_i,ref_j,box_test);%determine the output file expected from the GUI status
     866% end
     867% if ~isequal(box_test(4:6),[0 0 0])
     868%     civ_files=filecell.nc.civ2;%case of civ2 operations
     869% else
     870%     civ_files=filecell.nc.civ1;
     871% end
     872% [root,filename,ext]=fileparts(civ_files{1});
     873% [rootroot,SubDir,extdir]=fileparts(root);
     874% hfig=findobj(allchild(0),'name','civ_status');
     875% if isempty(hfig)
     876%     hfig=figure('DeleteFcn',@stop_status);
     877%     set(hfig,'MenuBar','none')% suppress the menu bar
     878%     set(hfig,'NumberTitle','off')%suppress the fig number in the title
     879%     set(hfig,'name','civ_status')
     880%     set(hfig,'tag','civ_status')
     881%     set(hfig,'UserData',civ_files)
     882%     hlist= uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', {'open_uvmat'},'tag','list');
     883%     uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','msgbox','Max',2,'String','checking files...');
     884%     uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
     885%     %uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@close_GUI);
     886%     uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@stop_status);
     887%     hrefresh=uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.1 0.01 0.2 0.07],'String','Refresh','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@refresh_GUI);
     888%     BarPosition=[0.05 0.81 0.01 0.05];
     889%     uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
     890%     drawnow
     891% end
     892% StatusData.time_ref=get(handles.OK,'UserData');% get the time of launch
     893% StatusData.option_civ=option_civ;
     894% set(hrefresh,'UserData',StatusData)
     895% filepath=fileparts(civ_files{1});
     896% set(hlist,'UserData',fileparts(filepath))
     897% refresh_GUI(hrefresh,[])
    1051898
    1052899% %------------------------------------------------------------------------   
    1053 % % launched by pressing OK on the status figure
    1054 % function close_GUI(hObject, eventdata)
     900% % launched by refreshing the status figure
     901% function refresh_GUI(hObject, eventdata)
    1055902% %------------------------------------------------------------------------
    1056 %     delete(gcbf)
    1057 
    1058 
    1059 %------------------------------------------------------------------------
    1060 % --- Main lauch command, called by OK and BATCH
    1061 function errormsg=launch_jobs(hObject, eventdata, handles)
    1062 %------------------------------------------------------------------------
    1063 errormsg='';%default
    1064 
    1065 %% read the input parameters from the  GUI civ_input
    1066 Param=read_GUI(handles.civ_series);
    1067 
    1068 %% check the selected list of operations:
    1069 operations={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
    1070 box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
    1071 index_first=find(box_test==1,1);
    1072 if isempty(index_first)
    1073     errormsg='no selected operation';
    1074     return
    1075 end
    1076 index_last=find(box_test==1,1,'last');
    1077 box_used=box_test(index_first : index_last);
    1078 [box_missing,ind_missing]=min(box_used);
    1079 if isequal(box_missing,0); %there is a missing step in the sequence of operations
    1080     errormsg=['missing' cell2mat(operations(ind_missing))];
    1081     return
    1082 end
    1083 
    1084 %% check mask if selecetd
    1085 %could be included in get_mask callback ?
    1086 if isequal(get(handles.CheckMask,'Value'),1)
    1087     maskname=get(handles.Mask,'String');
    1088     if ~exist(maskname,'file')
    1089         get_mask_civ1_Callback(hObject, eventdata, handles);
    1090     end
    1091 end
    1092 if isequal(get(handles.CheckMask,'Value'),1)
    1093     maskname=get(handles.Mask,'String');
    1094     if ~exist(maskname,'file')
    1095         get_mask_fix1_Callback(hObject, eventdata, handles);
    1096     end
    1097 end
    1098 if isequal(get(handles.CheckMask,'Value'),1)
    1099     maskname=get(handles.Mask,'String');
    1100     if ~exist(maskname,'file')
    1101         get_mask_civ2_Callback(hObject, eventdata, handles);
    1102     end
    1103 end
    1104 if isequal(get(handles.CheckMask,'Value'),1)
    1105     maskname=get(handles.Mask,'String');
    1106     if ~exist(maskname,'file')
    1107         get_mask_fix2_Callback(hObject, eventdata, handles);
    1108     end
    1109 end
    1110 
    1111 %% reinitialise status callback
    1112 if isfield(handles,'status')
    1113     set(handles.status,'Value',0);%suppress status display
    1114     status_Callback([], [], handles)
    1115 end
    1116 
    1117 %% read the PARAM.xml file to get the binaries (and batch_mode if batch)
    1118 path_civ=fileparts(which('civ')); %path to the source directory of uvmat
    1119 xmlfile=fullfile(path_civ,'PARAM.xml');
    1120 s=[];
    1121 if exist(xmlfile,'file')% search parameter xml file in the whole matlab path
    1122     t=xmltree(xmlfile);
    1123     s=convert(t);
    1124 end% default configuration
    1125 if ~isfield(s,'RunParam')
    1126     Param.xml.Civ1Bin=fullfile('bin','civ1');
    1127     Param.xml.Civ2Bin=fullfile('bin','civ2');
    1128     Param.xml.FixBin=fullfile('bin','fix_flag');
    1129     Param.xml.PatchBin=fullfile('bin','patch_up');
    1130 end
    1131 if strcmp(Param.RunMode,'cluster') %computation dispatched on a cluster
    1132     if isfield(s,'BatchParam')
    1133         Param.xml=s.BatchParam;
    1134         if isfield(Param.xml,'BatchMode')
    1135             batch_mode=Param.xml.BatchMode;
    1136             if ~ismember(batch_mode,{'sge','oar'})
    1137                 errormsg=['batch mode ' batch_mode ' not supported by UVMAT'];
    1138                 return
    1139             end
    1140         end
    1141     else
    1142         %default configuration
    1143         Param.xml.Civ1Bin=fullfile('bin','civ1');
    1144         Param.xml.Civ2Bin=fullfile('bin','civ2');
    1145         Param.xml.FixBin=fullfile('bin','fix_flag');
    1146         Param.xml.PatchBin=fullfile('bin','patch_up');
    1147    %     Param.xml.CivmBin=fullfile('bin','civ_matlab');
    1148         Param.xml.BatchMode='oar';% TODO : allow choice for sge
    1149     end
    1150 else % run
    1151     if isfield(s,'RunParam')
    1152         Param.xml=s.RunParam;
    1153     else %default configuration
    1154         Param.xml.Civ1Bin=fullfile('bin','civ1');
    1155         Param.xml.Civ2Bin=fullfile('bin','civ2');
    1156         Param.xml.FixBin=fullfile('bin','fix_flag');
    1157         Param.xml.PatchBin=fullfile('bin','patch_up');
    1158     end
    1159 end
    1160 %Param.xml.CivmBin=fullfile('bin','civ_matlab');
    1161 
    1162 %% check if the binaries exist : to move in civ_opening
    1163 binary_list={};
    1164 switch Param.Program
    1165     case 'CivX'
    1166         binary_list={'Civ1Bin','Civ2Bin','PatchBin','FixBin'};
    1167     case 'CivAll'% desactivated option
    1168         binary_list={'Civ'};
    1169 %     case 'civ_matlab.sh'% compiled version of civ_matlab
    1170 %         binary_list={'CivmBin'};         
    1171 end
    1172 for bin_name=binary_list %loop on the list of binaries
    1173     if isfield(Param.xml,bin_name{1})% bin_name{1} =current name in the list
    1174         if ~isunix
    1175         Param.xml.(bin_name{1})=[regexprep(Param.xml.(bin_name{1}),'/','\') '.exe'];
    1176         end
    1177         if exist(Param.xml.(bin_name{1}),'file')
    1178             [path,name,ext]=fileparts(Param.xml.(bin_name{1}));
    1179             currentdir=pwd;
    1180             if isempty(path)
    1181                 path=fileparts(which('civ.m'));
    1182             end
    1183             if exist(path,'dir')
    1184                 cd(path);
    1185                 binpath=pwd;%path of the binary
    1186                 Param.xml.(bin_name{1})=fullfile(binpath,[name ext]);
    1187                 cd(currentdir);
    1188             else
    1189                 errormsg=['path ' path ' for binaries specified in PARAM.xml does not exist'];
    1190                 return
    1191             end         
    1192         else  %look for the full path if the file name has been defined with a relative path in PARAM.xm
    1193             fullname=fullfile(path_civ,Param.xml.(bin_name{1}));
    1194             if exist(fullname,'file')
    1195                 Param.xml.(bin_name{1})=fullname;
    1196             else
    1197                 errormsg=['Binary ' Param.xml.(bin_name{1}) ' specified in PARAM.xml does not exist'];
    1198                 return
    1199             end
    1200         end
    1201     end
    1202 end
    1203 if strcmp(Param.Program,'civ_matlab.sh')
    1204     if ~exist(fullfile(path_civ,'civ_matlab.sh'),'file')
    1205         errormsg=[{'no file civ_matlab.sh found'}; {'run compile_functions.m to create it by compiling civ_matlab.m'}];
    1206             return
    1207     end
    1208 end
    1209 
    1210 %% set the list of files and check them
    1211 display('checking the files...')
    1212 [ref_i,ref_j,errormsg]=find_ref_indices(handles);
    1213 if ~isempty(errormsg)
    1214     return
    1215 end
    1216 [filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,tild,tild,compare,errormsg]=...
    1217     set_civ_filenames(handles,ref_i,ref_j,box_test);
    1218 if ~isempty(errormsg)
    1219     return
    1220 end
    1221 set(handles.civ_series,'UserData',filecell);%store for futur use of status callback
    1222 display('files OK, processing...')
    1223 
    1224 %% create subfolders for log, cmx, nml, xml, bat
    1225 RootBat=fileparts(filecell.nc.civ1{1,1});
    1226 switch(Param.Program)
    1227     case {'CivX','CivAll'}
    1228 dir_list={'0_BAT','0_CMX','0_LOG'};
    1229     case {'civ_matlab','civ_matlab.sh'}
    1230         dir_list={'0_BAT','0_XML'};
    1231 end
    1232 for k=1:length(dir_list)
    1233     if ~exist(fullfile(RootBat,dir_list{k}),'dir')
    1234         mkdir(fullfile(RootBat,dir_list{k}));
    1235     end
    1236 end
    1237 
    1238 %% get information on input images or movies
    1239 nbfield=numel(i1_civ1);
    1240 nbslice=numel(j1_civ1);
    1241 % if strcmp(Param.Program,'civ_matlab')
    1242     if Param.CheckCiv1
    1243         [Param.Civ1.FileTypeA,ImageInfoA_civ1,Param.Civ1.ImageA]=get_file_type(filecell.ima1.civ1{1});
    1244         [Param.Civ1.FileTypeB,ImageInfoB_civ1,Param.Civ1.ImageB]=get_file_type(filecell.ima2.civ1{1});
    1245     end
    1246     if Param.CheckCiv2
    1247         [Param.Civ2.FileTypeA,ImageInfoA_civ2,Param.Civ2.ImageA]=get_file_type(filecell.ima1.civ2{1});
    1248         [Param.Civ2.FileTypeB,ImageInfoB_civ2,Param.Civ2.ImageB]=get_file_type(filecell.ima2.civ2{1});
    1249     end
     903% Tabchar={};
     904% BarPosition=[0.05 0.81 0.01 0.05];
     905% hfig=get(hObject,'parent');
     906% StatusData=get(hObject,'UserData');
     907% civ_files=get(hfig,'UserData');
     908% [filepath,filename,ext]=fileparts(civ_files{1});
     909% [tild,SubDir,extdir]=fileparts(filepath);
     910% SubDir=[SubDir extdir];
     911% option_civ=StatusData.option_civ;
     912% nbfiles=numel(civ_files);
     913% testrecent=0;
     914% count=0;
     915% datnum=zeros(1,nbfiles);
     916% filefound=cell(1,nbfiles);
     917% for ifile=1:nbfiles
     918%     detect=exist(civ_files{ifile},'file'); % check the existence of the file
     919%     option=0;
     920%     if detect==0
     921%         option_str='not created';
     922%     else
     923%         datfile=dir(civ_files{ifile});
     924%         if isfield(datfile,'datenum')
     925%             datnum(ifile)=datfile.datenum;%only available in recent matlab versions
     926%             testrecent=1;
     927%         end
     928%         filefound(ifile)={datfile.name};
     929%         
     930%         % check the content  netcdf file
     931%         Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','CivStage','patch2','fix2','civ2','patch','fix');
     932%         option_list={'civ1','fix1','patch1','civ2','fix2','patch2'};
     933%         if ~isempty(Data.CivStage)
     934%             option=Data.CivStage;%case of Matlab civ
     935%         else
     936%             if ~isempty(Data.patch2) && isequal(Data.patch2,1)
     937%                 option=6;
     938%             elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
     939%                 option=5;
     940%             elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
     941%                 option=4;
     942%             elseif ~isempty(Data.patch) && isequal(Data.patch,1);
     943%                 option=3;
     944%             elseif ~isempty(Data.fix) && isequal(Data.fix,1);
     945%                 option=2;
     946%             else
     947%                 option=1;
     948%             end
     949%         end
     950%         option_str=option_list{option};
     951%         if datnum(ifile)<StatusData.time_ref
     952%             option_str=[option_str '  --OLD--'];
     953%         end
     954%     end
     955%     if option >= option_civ
     956%         count=count+1;
     957%     end
     958%     [filepath,filename,ext]=fileparts(civ_files{ifile});
     959%     Tabchar{ifile,1}=[fullfile(SubDir,filename) ext  '...' option_str];
    1250960% end
    1251 
    1252 %% MAIN LOOP
    1253 time=get(handles.ImaDoc,'UserData'); %get the set of times
    1254 TimeUnit=get(handles.TimeUnit,'String');
    1255 checkframe=strcmp(TimeUnit,'frame');
    1256 batch_file_list=[];%should be renamed file_list, can be used for xml or bash files
    1257 NomTypeIma=get(handles.NomType,'String');
    1258 for ifile=1:nbfield
    1259     for j=1:nbslice
    1260            
    1261         % define output file name
    1262         if Param.CheckCiv2==1 || Param.CheckFix2==1 || Param.CheckPatch2==1
    1263             Param.OutputFile=filecell.nc.civ2{ifile,j};
    1264         else
    1265             Param.OutputFile=filecell.nc.civ1{ifile,j};
    1266         end
    1267         Param.OutputFile=regexprep(Param.OutputFile,'.nc','');
    1268 
    1269         if Param.CheckCiv1
    1270             % read image-dependent parameters         
    1271             if ~checkframe% && size(time,1)>=i2_civ1(ifile) && size(time,2)>=j2_civ1(j)
    1272                 Param.Civ1.Dt=(time(i2_civ1(ifile)+1,j2_civ1(j)+1)-time(i1_civ1(ifile)+1,j1_civ1(j)+1));
    1273             else
    1274                 Param.Civ1.Dt=1;
    1275             end
    1276             Param.Civ1.Time=((time(i2_civ1(ifile)+1,j2_civ1(j)+1)+time(i1_civ1(ifile)+1,j1_civ1(j)+1))/2);
    1277             if strcmp(Param.Program,'CivX')
    1278                 Param.Civ1.term_a=num2stra(j1_civ1(j),nom_type_nc);%UTILITE?
    1279                 Param.Civ1.term_b=num2stra(j2_civ1(j),nom_type_nc);%
    1280             end
    1281             Param.Civ1.ImageA=filecell.ima1.civ1{ifile,j};
    1282             Param.Civ1.ImageB=filecell.ima2.civ1{ifile,j};
    1283             Param.Civ1.ImageBitDepth=ImageInfoA_civ1.BitDepth;
    1284             Param.Civ1.ImageWidth=ImageInfoA_civ1.Width;
    1285             Param.Civ1.ImageHeight=ImageInfoA_civ1.Height;
    1286             if strcmp(NomTypeIma,'*')
    1287                 Param.Civ1.FrameIndexA=i1_civ1(ifile);
    1288                 Param.Civ1.FrameIndexB=i2_civ1(ifile);
    1289             else% case of movies indexed with i, the frame index is then in j
    1290                 Param.Civ1.FrameIndexA=j1_civ1(j);
    1291                 Param.Civ1.FrameIndexB=j2_civ1(j);
    1292             end
    1293             % read mask )parameters
    1294             if Param.Civ1.CheckMask % the lines below should be changed with the new gui
    1295                 if ~exist(Param.Civ1.Mask,'file')
    1296                     maskbase=[filecell.filebase '_' Param.Civ1.Mask]; %
    1297                     nbslice_mask=str2double(Param.Civ1.Mask(1:end-4)); %
    1298                     i1_mask=mod(i1_civ1(ifile)-1,nbslice_mask)+1;
    1299                     [RootPathMask,RootFileMask]=fileparts(maskbase);
    1300                     Param.Civ1.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
    1301                 end
    1302             end
    1303             % read grid parameters
    1304             if Param.Civ1.CheckGrid
    1305                 if numel(Param.Civ1.Grid)>=4 && isequal(Param.Civ1.Grid(end-3:end),'grid')
    1306                     nbslice_grid=str2double(Param.Civ1.Grid(1:end-4)); %
    1307                     if ~isnan(nbslice_grid)
    1308                         i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
    1309                         Param.Civ1.Grid=[filecell.filebase '_' fullfile_uvmat('','',Param.Civ1.Grid,'.grid','_1',i1_grid)];
    1310                         if ~exist(Param.Civ1.GridName,'file')
    1311                             errormsg='grid file absent for civ1';
    1312                             return
    1313                         end
    1314                     elseif ~exist(Param.Civ1.Grid,'file')
    1315                         errormsg='grid file absent for civ1';
    1316                         return
    1317                     end
    1318                 end
    1319             end
    1320            
    1321         end
    1322        
    1323         if Param.CheckCiv2==1
    1324             Param.Civ2.ImageA=filecell.ima1.civ2{ifile,j};
    1325             Param.Civ2.ImageB=filecell.ima2.civ2{ifile,j};         
    1326             if ~checkframe %&& size(time,1)>=i2_civ2(ifile) && size(time,2)>=j2_civ2(j)
    1327                 Param.Civ2.Dt=time(i2_civ2(ifile)+1,j2_civ2(j)+1)-time(i1_civ2(ifile)+1,j1_civ2(j)+1);
    1328             else
    1329                 Param.Civ2.Dt=1;
    1330             end
    1331             Param.Civ2.Time=(time(i2_civ2(ifile)+1,j2_civ2(j)+1)+time(i1_civ2(ifile)+1,j1_civ2(j)+1))/2;
    1332             if strcmp(Param.Program,'CivX')
    1333                 Param.Civ2.term_a=num2stra(j1_civ2(j),nom_type_nc);
    1334                 Param.Civ2.term_b=num2stra(j2_civ2(j),nom_type_nc);
    1335             end
    1336             Param.Civ2.filename_nc1=filecell.nc.civ1{ifile,j};
    1337             Param.Civ2.filename_nc1(end-2:end)=[]; % remove '.nc'
    1338            
    1339             % mask
    1340             if Param.Civ2.CheckMask
    1341                 if ~exist(Param.Civ2.Mask,'file')
    1342                     maskbase=[filecell.filebase '_' Param.Civ2.Mask]; %
    1343                     nbslice_mask=str2double(Param.Civ2.Mask(1:end-4)); %
    1344                     i1_mask=mod(i1_civ2(ifile)-1,nbslice_mask)+1;
    1345                     [RootPathMask,RootFileMask]=fileparts(maskbase);
    1346                     Param.Civ2.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
    1347                     %                     Param.Civ2.Mask=name_generator(maskbase,i1_mask,1,'.png','_i');
    1348                 end
    1349             end
    1350             %grid
    1351             if Param.Civ2.CheckGrid
    1352                 if numel(Param.Civ2.Grid)>=4 && isequal(Param.Civ2.Grid(end-3:end),'grid')
    1353                     nbslice_grid=str2double(Param.Civ2.Grid(1:end-4)); %
    1354                     if ~isnan(nbslice_grid)
    1355                         i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
    1356                         Param.Civ2.Grid=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
    1357                         %                         Param.Civ2.Grid=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
    1358                     end
    1359                 end
    1360             end
    1361 
    1362             Param.Civ2.ImageBitDepth=ImageInfoA_civ2.BitDepth;
    1363             Param.Civ2.ImageWidth=ImageInfoA_civ2.Width;
    1364             Param.Civ2.ImageHeight=ImageInfoA_civ2.Height;
    1365             if strcmp(NomTypeIma,'*')
    1366                 Param.Civ2.FrameIndexA=i1_civ2(ifile);
    1367                 Param.Civ2.FrameIndexB=i2_civ2(ifile);
    1368             else% case of movies indexed with i, the frame index is then in j
    1369                 Param.Civ2.FrameIndexA=j1_civ2(j);
    1370                 Param.Civ2.FrameIndexB=j2_civ2(j);
    1371             end
    1372         end
    1373        
    1374         % write the command and eventually the cmx, xml or nml files
    1375         cmd=write_cmd(Param);
    1376         write_param(Param);
    1377              
    1378         % create the command file name .m, .bat or .sh depending on the ok option
    1379         switch Param.Program
    1380             case {'civ_matlab'}
    1381                 filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.m');           
    1382                 [BatRoot,BatFile]=fileparts(filename_bat);
    1383                  BatFile=regexprep(BatFile,'-','__');%transform name to suppress'-' (not valid for .m files)
    1384                  filename_bat=[fullfile(BatRoot,BatFile) '.m'];
    1385             case {'CivX','CivAll','civ_matlab.sh'}
    1386                 switch computer
    1387                     case {'PCWIN','PCWIN64'}
    1388                         filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.bat');
    1389                     case {'GLNX86','GLNXA64','MACI64'}
    1390                         filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
    1391                 end
    1392         end
    1393        
    1394         % print the command in the bat file
    1395         [fid,message]=fopen(filename_bat,'w');
    1396         if isequal(fid,-1)
    1397             errormsg=['creation of .bat file: ' message];
    1398             return
    1399         end
    1400         fprintf(fid,cmd);
    1401         fclose(fid);
    1402        
    1403         % special case for civ_matlab on cluster
    1404         if strcmp(Param.Program,'civ_matlab') && strcmp(Param.RunMode,'cluster')
    1405             filename_bat2=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
    1406             [fid,message]=fopen(filename_bat2,'w');
    1407             if isequal(fid,-1)
    1408                 errormsg=['creation of .bat file: ' message];
    1409                 return
    1410             end
    1411             fprintf(fid,['#!/bin/bash \n' ...
    1412                 '/etc/sysprofile \n'...
    1413                 'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
    1414                 'addpath(''' path_civ ''');\n']);
    1415 %             for p=1:length(batch_file_list)
    1416                 fprintf(fid,['run ' filename_bat '\n']);
     961% datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
     962% if isempty(datnum)
     963%     if testrecent
     964%         message='no civ result created yet';
     965%     else
     966%         message='';
     967%     end
     968% else
     969%     datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
     970%     [first,ind]=min(datnum);
     971%     [last,indlast]=max(datnum);
     972%     message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
     973%         ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
     974% end
     975% hlist=findobj(hfig,'tag','list');
     976% hmsgbox=findobj(hfig,'tag','msgbox');
     977% hwaitbar=findobj(hfig,'tag','waitbar');
     978% set(hlist,'String',Tabchar)
     979% set(hmsgbox,'String', message)
     980% if count>0 %&& ~test_new
     981%     BarPosition(3)=0.9*count/nbfiles;
     982%     set(hwaitbar,'Position',BarPosition)
     983% end
     984%
     985%
     986% %------------------------------------------------------------------------   
     987% % launched by deleting the status figure
     988% function stop_status(hObject, eventdata)
     989% %------------------------------------------------------------------------
     990% hciv=findobj(allchild(0),'tag','civ');
     991% hhciv=guidata(hciv);
     992% set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
     993% set(hhciv.status,'BackgroundColor',[0 1 0])
     994%
     995% % %------------------------------------------------------------------------   
     996% % % launched by pressing OK on the status figure
     997% % function close_GUI(hObject, eventdata)
     998% % %------------------------------------------------------------------------
     999% %     delete(gcbf)
     1000%
     1001
     1002% %------------------------------------------------------------------------
     1003% % --- Main lauch command, called by OK and BATCH
     1004% function errormsg=launch_jobs(hObject, eventdata, handles)
     1005% %------------------------------------------------------------------------
     1006% errormsg='';%default
     1007%
     1008% %% read the input parameters from the  GUI civ_input
     1009% Param=read_GUI(handles.civ_input);
     1010%
     1011% %% check the selected list of operations:
     1012% operations={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
     1013% box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
     1014% index_first=find(box_test==1,1);
     1015% if isempty(index_first)
     1016%     errormsg='no selected operation';
     1017%     return
     1018% end
     1019% index_last=find(box_test==1,1,'last');
     1020% box_used=box_test(index_first : index_last);
     1021% [box_missing,ind_missing]=min(box_used);
     1022% if isequal(box_missing,0); %there is a missing step in the sequence of operations
     1023%     errormsg=['missing' cell2mat(operations(ind_missing))];
     1024%     return
     1025% end
     1026%
     1027% %% check mask if selecetd
     1028% %could be included in get_mask callback ?
     1029% if isequal(get(handles.CheckMask,'Value'),1)
     1030%     maskname=get(handles.Mask,'String');
     1031%     if ~exist(maskname,'file')
     1032%         get_mask_civ1_Callback(hObject, eventdata, handles);
     1033%     end
     1034% end
     1035% if isequal(get(handles.CheckMask,'Value'),1)
     1036%     maskname=get(handles.Mask,'String');
     1037%     if ~exist(maskname,'file')
     1038%         get_mask_fix1_Callback(hObject, eventdata, handles);
     1039%     end
     1040% end
     1041% if isequal(get(handles.CheckMask,'Value'),1)
     1042%     maskname=get(handles.Mask,'String');
     1043%     if ~exist(maskname,'file')
     1044%         get_mask_civ2_Callback(hObject, eventdata, handles);
     1045%     end
     1046% end
     1047% if isequal(get(handles.CheckMask,'Value'),1)
     1048%     maskname=get(handles.Mask,'String');
     1049%     if ~exist(maskname,'file')
     1050%         get_mask_fix2_Callback(hObject, eventdata, handles);
     1051%     end
     1052% end
     1053%
     1054% %% reinitialise status callback
     1055% if isfield(handles,'status')
     1056%     set(handles.status,'Value',0);%suppress status display
     1057%     status_Callback([], [], handles)
     1058% end
     1059%
     1060% %% read the PARAM.xml file to get the binaries (and batch_mode if batch)
     1061% % path_civ=fileparts(which('civ')); %path to the source directory of uvmat
     1062% % xmlfile=fullfile(path_civ,'PARAM.xml');
     1063% % s=[];
     1064% % if exist(xmlfile,'file')% search parameter xml file in the whole matlab path
     1065% %     t=xmltree(xmlfile);
     1066% %     s=convert(t);
     1067% % end% default configuration
     1068% % if ~isfield(s,'RunParam')
     1069% %     Param.xml.Civ1Bin=fullfile('bin','civ1');
     1070% %     Param.xml.Civ2Bin=fullfile('bin','civ2');
     1071% %     Param.xml.FixBin=fullfile('bin','fix_flag');
     1072% %     Param.xml.PatchBin=fullfile('bin','patch_up');
     1073% % end
     1074% % if strcmp(Param.RunMode,'cluster') %computation dispatched on a cluster
     1075% %     if isfield(s,'BatchParam')
     1076% %         Param.xml=s.BatchParam;
     1077% %         if isfield(Param.xml,'BatchMode')
     1078% %             batch_mode=Param.xml.BatchMode;
     1079% %             if ~ismember(batch_mode,{'sge','oar'})
     1080% %                 errormsg=['batch mode ' batch_mode ' not supported by UVMAT'];
     1081% %                 return
     1082% %             end
     1083% %         end
     1084% %     else
     1085% %         %default configuration
     1086% %         Param.xml.Civ1Bin=fullfile('bin','civ1');
     1087% %         Param.xml.Civ2Bin=fullfile('bin','civ2');
     1088% %         Param.xml.FixBin=fullfile('bin','fix_flag');
     1089% %         Param.xml.PatchBin=fullfile('bin','patch_up');
     1090% %    %     Param.xml.CivmBin=fullfile('bin','civ_matlab');
     1091% %         Param.xml.BatchMode='oar';% TODO : allow choice for sge
     1092% %     end
     1093% % else % run
     1094% %     if isfield(s,'RunParam')
     1095% %         Param.xml=s.RunParam;
     1096% %     else %default configuration
     1097% %         Param.xml.Civ1Bin=fullfile('bin','civ1');
     1098% %         Param.xml.Civ2Bin=fullfile('bin','civ2');
     1099% %         Param.xml.FixBin=fullfile('bin','fix_flag');
     1100% %         Param.xml.PatchBin=fullfile('bin','patch_up');
     1101% %     end
     1102% % end
     1103% % %Param.xml.CivmBin=fullfile('bin','civ_matlab');
     1104% %
     1105% % %% check if the binaries exist : to move in civ_opening
     1106% % binary_list={};
     1107% % switch Param.Program
     1108% %     case 'CivX'
     1109% %         binary_list={'Civ1Bin','Civ2Bin','PatchBin','FixBin'};
     1110% %     case 'CivAll'% desactivated option
     1111% %         binary_list={'Civ'};
     1112% % %     case 'civ_matlab.sh'% compiled version of civ_matlab
     1113% % %         binary_list={'CivmBin'};         
     1114% % end
     1115% % for bin_name=binary_list %loop on the list of binaries
     1116% %     if isfield(Param.xml,bin_name{1})% bin_name{1} =current name in the list
     1117% %         if ~isunix
     1118% %         Param.xml.(bin_name{1})=[regexprep(Param.xml.(bin_name{1}),'/','\') '.exe'];
     1119% %         end
     1120% %         if exist(Param.xml.(bin_name{1}),'file')
     1121% %             [path,name,ext]=fileparts(Param.xml.(bin_name{1}));
     1122% %             currentdir=pwd;
     1123% %             if isempty(path)
     1124% %                 path=fileparts(which('civ.m'));
     1125% %             end
     1126% %             if exist(path,'dir')
     1127% %                 cd(path);
     1128% %                 binpath=pwd;%path of the binary
     1129% %                 Param.xml.(bin_name{1})=fullfile(binpath,[name ext]);
     1130% %                 cd(currentdir);
     1131% %             else
     1132% %                 errormsg=['path ' path ' for binaries specified in PARAM.xml does not exist'];
     1133% %                 return
     1134% %             end         
     1135% %         else  %look for the full path if the file name has been defined with a relative path in PARAM.xm
     1136% %             fullname=fullfile(path_civ,Param.xml.(bin_name{1}));
     1137% %             if exist(fullname,'file')
     1138% %                 Param.xml.(bin_name{1})=fullname;
     1139% %             else
     1140% %                 errormsg=['Binary ' Param.xml.(bin_name{1}) ' specified in PARAM.xml does not exist'];
     1141% %                 return
     1142% %             end
     1143% %         end
     1144% %     end
     1145% % end
     1146% % if strcmp(Param.Program,'civ_matlab.sh')
     1147% %     if ~exist(fullfile(path_civ,'civ_matlab.sh'),'file')
     1148% %         errormsg=[{'no file civ_matlab.sh found'}; {'run compile_functions.m to create it by compiling civ_matlab.m'}];
     1149% %             return
     1150% %     end
     1151% % end
     1152% %
     1153% % %% set the list of files and check them
     1154% % display('checking the files...')
     1155% % [ref_i,ref_j,errormsg]=find_ref_indices(handles);
     1156% % if ~isempty(errormsg)
     1157% %     return
     1158% % end
     1159% % [filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,tild,tild,compare,errormsg]=...
     1160% %     set_civ_filenames(handles,ref_i,ref_j,box_test);
     1161% % if ~isempty(errormsg)
     1162% %     return
     1163% % end
     1164% % set(handles.civ_input,'UserData',filecell);%store for futur use of status callback
     1165% % display('files OK, processing...')
     1166% %
     1167% % %% create subfolders for log, cmx, nml, xml, bat
     1168% % RootBat=fileparts(filecell.nc.civ1{1,1});
     1169% % switch(Param.Program)
     1170% %     case {'CivX','CivAll'}
     1171% % dir_list={'0_BAT','0_CMX','0_LOG'};
     1172% %     case {'civ_matlab','civ_matlab.sh'}
     1173% %         dir_list={'0_BAT','0_XML'};
     1174% % end
     1175% % for k=1:length(dir_list)
     1176% %     if ~exist(fullfile(RootBat,dir_list{k}),'dir')
     1177% %         mkdir(fullfile(RootBat,dir_list{k}));
     1178% %     end
     1179% % end
     1180%
     1181% %% get information on input images or movies
     1182% nbfield=numel(i1_civ1);
     1183% nbslice=numel(j1_civ1);
     1184% % if strcmp(Param.Program,'civ_matlab')
     1185%     if Param.CheckCiv1
     1186%         [Param.Civ1.FileTypeA,ImageInfoA_civ1,Param.Civ1.ImageA]=get_file_type(filecell.ima1.civ1{1});
     1187%         [Param.Civ1.FileTypeB,ImageInfoB_civ1,Param.Civ1.ImageB]=get_file_type(filecell.ima2.civ1{1});
     1188%     end
     1189%     if Param.CheckCiv2
     1190%         [Param.Civ2.FileTypeA,ImageInfoA_civ2,Param.Civ2.ImageA]=get_file_type(filecell.ima1.civ2{1});
     1191%         [Param.Civ2.FileTypeB,ImageInfoB_civ2,Param.Civ2.ImageB]=get_file_type(filecell.ima2.civ2{1});
     1192%     end
     1193% % end
     1194%
     1195% %% MAIN LOOP
     1196% time=get(handles.ImaDoc,'UserData'); %get the set of times
     1197% TimeUnit=get(handles.TimeUnit,'String');
     1198% checkframe=strcmp(TimeUnit,'frame');
     1199% batch_file_list=[];%should be renamed file_list, can be used for xml or bash files
     1200% NomTypeIma=get(handles.NomType,'String');
     1201% for ifile=1:nbfield
     1202%     for j=1:nbslice
     1203%             
     1204%         % define output file name
     1205%         if Param.CheckCiv2==1 || Param.CheckFix2==1 || Param.CheckPatch2==1
     1206%             Param.OutputFile=filecell.nc.civ2{ifile,j};
     1207%         else
     1208%             Param.OutputFile=filecell.nc.civ1{ifile,j};
     1209%         end
     1210%         Param.OutputFile=regexprep(Param.OutputFile,'.nc','');
     1211%
     1212%         if Param.CheckCiv1
     1213%             % read image-dependent parameters         
     1214%             if ~checkframe% && size(time,1)>=i2_civ1(ifile) && size(time,2)>=j2_civ1(j)
     1215%                 Param.Civ1.Dt=(time(i2_civ1(ifile)+1,j2_civ1(j)+1)-time(i1_civ1(ifile)+1,j1_civ1(j)+1));
     1216%             else
     1217%                 Param.Civ1.Dt=1;
    14171218%             end
    1418             fprintf(fid, 'exit\nEND_MATLAB\n');
    1419             fclose(fid);
    1420             filename_bat=filename_bat2;
    1421         end
    1422        
    1423         switch computer
    1424             case {'GLNX86','GLNXA64','MACI64'}
    1425                 system(['chmod +x ' filename_bat]);
    1426         end
    1427         batch_file_list{length(batch_file_list)+1}=filename_bat;
    1428     end
    1429 end
    1430 
    1431 %% start calculation
    1432 %computation on cluster
    1433 %if batch ==3
    1434 switch Param.RunMode,
    1435     case 'cluster'
    1436         switch batch_mode
    1437             case 'sge' %at the moment only psmn ENS Lyon uses it
    1438                 for p=1:length(batch_file_list)
    1439                     %cmd=['!qsub -p ' pvalue ' -q civ_input.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
    1440                     cmd=['!qsub -q piv1,piv2,piv3 '...
    1441                         '-e ' regexprep(batch_file_list{p},'.bat','.errors') ' -o ' regexprep(batch_file_list{p},'.bat','.log ')...
    1442                         ' -v ' 'LD_LIBRARY_PATH=/home/sjoubaud/matlab_sylvain/civx/lib ' batch_file_list{p}];
    1443                     display(cmd);eval(cmd);
    1444                 end
    1445             case 'oar_old' % to remove
    1446                 for p=1:length(batch_file_list)
    1447                     oar_command=['!oarsub -n CIVX -q nicejob '...
    1448                         '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
    1449                         '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
    1450                     display(oar_command);eval(oar_command);
    1451                 end
    1452             case 'oar'
    1453                 max_walltime=3600*12; % 12h max
    1454                 oar_modes={'oar-parexec','oar-dispatch','mpilauncher'};
    1455                 text={'Batch processing on servcalcul3 LEGI';...
    1456                     'Please choose one of the followint modes';...
    1457                     '* oar-parexec : default and best choice';...
    1458                     '* oar-dispatch : jobs in a container of several cores';...
    1459                     '* mpilauncher : one single parallel mpi job using several cores';...
    1460                     '**********************************'...
    1461                     };
    1462                 [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
    1463                     'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
    1464                 switch oar_modes{S}
    1465                     case 'oar-parexec' %oar-dispatch.pl
    1466                         if strcmp(Param.Program,'civ_matlab')
    1467                             ncores=1;
    1468                             msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
    1469                         else
    1470                         answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
    1471                         ncores=str2double(answer{1});
    1472                         end
    1473 
    1474                         extra_oar=answer{2};
    1475                         walltime_onejob=600;%seconds
    1476                         filename_joblist=fullfile(RootBat,'job_list.txt');
    1477                         fid=fopen(filename_joblist,'w');
    1478                         for p=1:length(batch_file_list)
    1479                             fprintf(fid,[batch_file_list{p} '\n']);
    1480                         end
    1481                         fclose(fid);
    1482                         oar_command=['oarsub -n CIVX '...
    1483                             '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
    1484                             '-l /core=' num2str(ncores) ','...
    1485                             'walltime=' datestr(min(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,max_walltime/86400),13) ' '...
    1486                             '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
    1487                             '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
    1488                             extra_oar ' '...
    1489                             '"oar-parexec -s -f ' filename_joblist ' '...
    1490                             '-l ' filename_joblist '.log"\n'];
    1491                         filename_oarcommand=fullfile(RootBat,'oar_command');
    1492                         fid=fopen(filename_oarcommand,'w');
    1493                         fprintf(fid,oar_command);
    1494                         fclose(fid);
    1495                         fprintf(oar_command);% display in command line
    1496                         system(oar_command);
    1497 %                         eval(['! . ' filename
    1498 %                             _oarcommand])
    1499                     case 'oar-dispatch' %oar-dispatch.pl
    1500                         ncores=str2double(...
    1501                             inputdlg('Number of cores (max 36)','oarsub parameter',1,{'6'})...
    1502                             );
    1503                         walltime_onejob=600;%seconds
    1504                         filename_joblist=fullfile(RootBat,'job_list.txt');
    1505                         fid=fopen(filename_joblist,'w');
    1506                         for p=1:length(batch_file_list)
    1507                             oar_command=['oarsub -n CIVX '...
    1508                                 '-E ' regexprep(batch_file_list{p},'\.bat\>','.stderr') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.stdout ')...
    1509                                 '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
    1510                             fprintf(fid,[oar_command '\n']);
    1511                         end
    1512                         fclose(fid);
    1513                         oar_command=['oarsub -t container -n civx-container '...
    1514                             '-l /core=' num2str(ncores)...
    1515                             ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13) ' '...
    1516                             '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
    1517                             '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
    1518                             '"oar-dispatch -f ' filename_joblist '"'];
    1519                         filename_oarcommand=fullfile(RootBat,'oar_command');
    1520                         fid=fopen(filename_oarcommand,'w');
    1521                         fprintf(fid,[oar_command '\n']);
    1522                         fclose(fid);
    1523                         display(oar_command);
    1524                         eval(['! . ' filename_oarcommand])
    1525                     case 'mpilauncher'
    1526                         filename_joblist=fullfile(RootBat,'job_list.txt');
    1527                         fid=fopen(filename_joblist,'w');
    1528                        
    1529                         for p=1:length(batch_file_list)
    1530                             fprintf(fid,[batch_file_list{p} '\n']);
    1531                         end
    1532                         fclose(fid)
    1533                         text_oarscript=[...
    1534                             '#!/bin/bash \n'...
    1535                             '#OAR -n Mylauncher \n'...
    1536                             '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
    1537                             '#OAR -E ' fullfile(RootBat,'stderrfile.log') ' \n'...
    1538                             '#OAR -O ' fullfile(RootBat,'stdoutfile.log') ' \n'...
    1539                             '# ========================================================= \n'...
    1540                             '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
    1541                             '# application for coriolis PIV post-processing. \n'...
    1542                             '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
    1543                             '# This wrapper assert that the user has the same environment on all the \n'...
    1544                             '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
    1545                             '# \n'...
    1546                             '# REQUIREMENT: \n'...
    1547                             '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
    1548                             '# If a different location is used, change the line following the comment "Bidouille" \n'...
    1549                             '# ========================================================= \n'...
    1550                             '#   USER should only modify these 2 lines  \n'...
    1551                             'WORKDIR=' pwd ' \n'...
    1552                             'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
    1553                             '# ========================================================= \n'...
    1554                             '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
    1555                             'echo "job starting on: "`hostname` \n'...
    1556                             'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
    1557                             'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
    1558                             '#========== Bidouille ============== \n'...
    1559                             'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
    1560                             'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
    1561                             'echo "I run: $CMD"  \n'...
    1562                             '$CMD \n'...
    1563                             'echo "job ending" \n'...
    1564                             ];
    1565                         %                 oarsub -S ./oar.sub
    1566                         filename_oarscript=fullfile(RootBat,'oar_command');
    1567                         fid=fopen(filename_oarscript,'w');
    1568                         fprintf(fid,[text_oarscript]);
    1569                         fclose(fid);
    1570                         eval(['!chmod +x  ' filename_oarscript]);
    1571                         eval(['!oarsub -S ' filename_oarscript]);
    1572                 end
    1573         end
    1574     case {'background','local'}
    1575         switch Param.Program
    1576             case {'civ_matlab'}
    1577                 switch Param.RunMode
    1578                     case 'background'
    1579                         switch computer
    1580                             case {'PCWIN','PCWIN64'}
    1581                                 filename_superbat=fullfile(RootBat,'job_list.bat');
    1582                                 fid=fopen(filename_superbat,'w');
    1583                                 if fid==-1
    1584                                     msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
    1585                                     return
    1586                                 end
    1587                                  fprintf(fid,['matlab -automation '...
    1588                                      '-r "addpath(''' regexprep(path_civ,'\\','\\\\') ''');']);
    1589                                 for p=1:length(batch_file_list)
    1590                                     fprintf(fid,['run ' regexprep(batch_file_list{p},'\\','\\\\') ';']);
    1591                                 end
    1592                                  fprintf(fid, 'exit"');
    1593                                 fclose(fid);
    1594                                 dos([filename_superbat ' &']);
    1595                             case {'GLNX86','GLNXA64','MACI64'}
    1596                                 filename_superbat=fullfile(RootBat,'job_list.sh');
    1597                                 fid=fopen(filename_superbat,'w');
    1598                                 if fid==-1
    1599                                     msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
    1600                                     return
    1601                                 end
    1602                                 fprintf(fid,['#!/bin/bash \n' ...
    1603                                     '/etc/sysprofile \n'...
    1604                                     'matlab -nodisplay -nosplash -nojvm -logfile  <<END_MATLAB \n'...
    1605                                     'addpath(''' path_civ ''');\n']);
    1606                                 for p=1:length(batch_file_list)
    1607                                     fprintf(fid,['run ' batch_file_list{p} '\n']);
    1608                                 end
    1609                                 fprintf(fid, 'exit\nEND_MATLAB\n');
    1610                                 fclose(fid);
    1611                                 system(['chmod +x ' filename_superbat]);
    1612                                 system([filename_superbat ' &']);
    1613                         end
    1614                     case 'local'
    1615                         for p=1:length(batch_file_list)
    1616                             fid=fopen(batch_file_list{p});
    1617                             eval(fscanf(fid,'%s'));
    1618                             fclose(fid);
    1619                         end
    1620                 end
    1621             case {'CivX','CivAll','civ_matlab.sh'}
    1622                     switch computer
    1623                         case {'PCWIN','PCWIN64'}
    1624                             filename_superbat=fullfile(RootBat,'job_list.bat');
    1625                             fid=fopen(filename_superbat,'w');
    1626                             if fid==-1
    1627                                 msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
    1628                                 return
    1629                             end
    1630                             for p=1:length(batch_file_list)
    1631                                 fprintf(fid,['@call "' regexprep(batch_file_list{p},'\\','\\\\') '"' '\n']);
    1632                             end
    1633                             fclose(fid);
    1634                             system(['chmod +x ' filename_superbat]);
    1635                         case {'GLNX86','GLNXA64','MACI64'}
    1636                             filename_superbat=fullfile(RootBat,'job_list.bat');
    1637                             fid=fopen(filename_superbat,'w');
    1638                             if fid==-1
    1639                                 msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
    1640                                 return
    1641                             end
    1642                             for p=1:length(batch_file_list)
    1643                                 fprintf(fid,['sh ' batch_file_list{p} '\n']);
    1644                             end
    1645                             fclose(fid);
    1646                             system(['chmod +x ' filename_superbat]);
    1647                     end
    1648                 switch Param.RunMode
    1649                     case 'background'
    1650                         system([filename_superbat ' &']);% execute main commmand see what it does in dos ?
    1651                     case 'local'
    1652                         system(filename_superbat);
    1653                 end
    1654         end
    1655 end
    1656 
    1657 
    1658 %% save interface state
    1659 if isfield(filecell,'nc')
    1660     if isfield(filecell.nc,'civ2')
    1661         fileresu=filecell.nc.civ2{1,1};
    1662     else
    1663         fileresu=filecell.nc.civ1{1,1};
    1664     end
    1665 end
    1666 [RootPath,SubDir,RootFile]=fileparts_uvmat(fileresu);
    1667 namedoc=fullfile(RootPath,SubDir,RootFile);
    1668 detect=1;
    1669 while detect==1
    1670     namefigfull=[namedoc '.fig'];
    1671     hh=dir(namefigfull);
    1672     if ~isempty(hh)
    1673         detect=1;
    1674         namedoc=[namedoc '.0'];
    1675     else
    1676         detect=0;
    1677     end
    1678 end
    1679 Param=rmfield(Param,'status');
    1680 Param=rmfield(Param,'xml');
    1681 t=struct2xml(Param);
    1682 t=set(t,1,'name','Civ');% set the head label
    1683 save(t,[namedoc '.civ.xml']); %save GUI  parameters as xml file
    1684 % saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
    1685 
    1686 %Save info in personal profile (initiate browser next time) TODO
    1687 MenuFile={};
    1688 dir_perso=prefdir;
    1689 profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
    1690 if exist(profil_perso,'file')
    1691     hh=load (profil_perso);
    1692       if isfield(hh,'MenuFile')
    1693           MenuFile=hh.MenuFile;
    1694       end
    1695       if isfield(filecell.nc,'civ2')
    1696           MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
    1697       else
    1698            MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
    1699       end
    1700       save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
    1701 else
    1702     MenuFile=filecell.ima1.civ1(1,1);
    1703     save (profil_perso,'MenuFile')
    1704 end
    1705 
    1706 %------------------------------------------------------------------------
    1707 % --- determine the list of reference indices of processing file
    1708 function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
    1709 %------------------------------------------------------------------------
    1710 errormsg=''; %default error message
    1711 first_i=str2double(get(handles.first_i,'String'));%first index i
    1712 last_i=str2double(get(handles.last_i,'String'));%last index i
    1713 incr_i=str2double(get(handles.incr_i,'String'));% increment
    1714 if isequal(get(handles.first_j,'Visible'),'on')
    1715     first_j=str2double(get(handles.first_j,'String'));%first index j
    1716     last_j=str2double(get(handles.last_j,'String'));%last index j
    1717     incr_j=str2double(get(handles.incr_j,'String'));% increment
    1718 else
    1719     first_j=1;
    1720     last_j=1;
    1721     incr_j=1;
    1722 end
    1723 ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
    1724 ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
    1725 if isnan(first_i)||isnan(first_j)
    1726     errormsg='first field number not defined';
    1727 elseif isnan(last_i)||isnan(last_j)
    1728     errormsg='last field number not defined';
    1729 elseif isnan(incr_i)||isnan(incr_j)
    1730     errormsg='increment in field number not defined';
    1731 elseif last_i < first_i || last_j < first_j
    1732     errormsg='last field number must be larger than the first one';
    1733 end
     1219%             Param.Civ1.Time=((time(i2_civ1(ifile)+1,j2_civ1(j)+1)+time(i1_civ1(ifile)+1,j1_civ1(j)+1))/2);
     1220%             if strcmp(Param.Program,'CivX')
     1221%                 Param.Civ1.term_a=num2stra(j1_civ1(j),nom_type_nc);%UTILITE?
     1222%                 Param.Civ1.term_b=num2stra(j2_civ1(j),nom_type_nc);%
     1223%             end
     1224%             Param.Civ1.ImageA=filecell.ima1.civ1{ifile,j};
     1225%             Param.Civ1.ImageB=filecell.ima2.civ1{ifile,j};
     1226%             Param.Civ1.ImageBitDepth=ImageInfoA_civ1.BitDepth;
     1227%             Param.Civ1.ImageWidth=ImageInfoA_civ1.Width;
     1228%             Param.Civ1.ImageHeight=ImageInfoA_civ1.Height;
     1229%             if strcmp(NomTypeIma,'*')
     1230%                 Param.Civ1.FrameIndexA=i1_civ1(ifile);
     1231%                 Param.Civ1.FrameIndexB=i2_civ1(ifile);
     1232%             else% case of movies indexed with i, the frame index is then in j
     1233%                 Param.Civ1.FrameIndexA=j1_civ1(j);
     1234%                 Param.Civ1.FrameIndexB=j2_civ1(j);
     1235%             end
     1236%             % read mask )parameters
     1237%             if Param.Civ1.CheckMask % the lines below should be changed with the new gui
     1238%                 if ~exist(Param.Civ1.Mask,'file')
     1239%                     maskbase=[filecell.filebase '_' Param.Civ1.Mask]; %
     1240%                     nbslice_mask=str2double(Param.Civ1.Mask(1:end-4)); %
     1241%                     i1_mask=mod(i1_civ1(ifile)-1,nbslice_mask)+1;
     1242%                     [RootPathMask,RootFileMask]=fileparts(maskbase);
     1243%                     Param.Civ1.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
     1244%                 end
     1245%             end
     1246%             % read grid parameters
     1247%             if Param.Civ1.CheckGrid
     1248%                 if numel(Param.Civ1.Grid)>=4 && isequal(Param.Civ1.Grid(end-3:end),'grid')
     1249%                     nbslice_grid=str2double(Param.Civ1.Grid(1:end-4)); %
     1250%                     if ~isnan(nbslice_grid)
     1251%                         i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
     1252%                         Param.Civ1.Grid=[filecell.filebase '_' fullfile_uvmat('','',Param.Civ1.Grid,'.grid','_1',i1_grid)];
     1253%                         if ~exist(Param.Civ1.GridName,'file')
     1254%                             errormsg='grid file absent for civ1';
     1255%                             return
     1256%                         end
     1257%                     elseif ~exist(Param.Civ1.Grid,'file')
     1258%                         errormsg='grid file absent for civ1';
     1259%                         return
     1260%                     end
     1261%                 end
     1262%             end
     1263%             
     1264%         end
     1265%         
     1266%         if Param.CheckCiv2==1
     1267%             Param.Civ2.ImageA=filecell.ima1.civ2{ifile,j};
     1268%             Param.Civ2.ImageB=filecell.ima2.civ2{ifile,j};         
     1269%             if ~checkframe %&& size(time,1)>=i2_civ2(ifile) && size(time,2)>=j2_civ2(j)
     1270%                 Param.Civ2.Dt=time(i2_civ2(ifile)+1,j2_civ2(j)+1)-time(i1_civ2(ifile)+1,j1_civ2(j)+1);
     1271%             else
     1272%                 Param.Civ2.Dt=1;
     1273%             end
     1274%             Param.Civ2.Time=(time(i2_civ2(ifile)+1,j2_civ2(j)+1)+time(i1_civ2(ifile)+1,j1_civ2(j)+1))/2;
     1275%             if strcmp(Param.Program,'CivX')
     1276%                 Param.Civ2.term_a=num2stra(j1_civ2(j),nom_type_nc);
     1277%                 Param.Civ2.term_b=num2stra(j2_civ2(j),nom_type_nc);
     1278%             end
     1279%             Param.Civ2.filename_nc1=filecell.nc.civ1{ifile,j};
     1280%             Param.Civ2.filename_nc1(end-2:end)=[]; % remove '.nc'
     1281%             
     1282%             % mask
     1283%             if Param.Civ2.CheckMask
     1284%                 if ~exist(Param.Civ2.Mask,'file')
     1285%                     maskbase=[filecell.filebase '_' Param.Civ2.Mask]; %
     1286%                     nbslice_mask=str2double(Param.Civ2.Mask(1:end-4)); %
     1287%                     i1_mask=mod(i1_civ2(ifile)-1,nbslice_mask)+1;
     1288%                     [RootPathMask,RootFileMask]=fileparts(maskbase);
     1289%                     Param.Civ2.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
     1290%                     %                     Param.Civ2.Mask=name_generator(maskbase,i1_mask,1,'.png','_i');
     1291%                 end
     1292%             end
     1293%             %grid
     1294%             if Param.Civ2.CheckGrid
     1295%                 if numel(Param.Civ2.Grid)>=4 && isequal(Param.Civ2.Grid(end-3:end),'grid')
     1296%                     nbslice_grid=str2double(Param.Civ2.Grid(1:end-4)); %
     1297%                     if ~isnan(nbslice_grid)
     1298%                         i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
     1299%                         Param.Civ2.Grid=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
     1300%                         %                         Param.Civ2.Grid=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
     1301%                     end
     1302%                 end
     1303%             end
     1304%
     1305%             Param.Civ2.ImageBitDepth=ImageInfoA_civ2.BitDepth;
     1306%             Param.Civ2.ImageWidth=ImageInfoA_civ2.Width;
     1307%             Param.Civ2.ImageHeight=ImageInfoA_civ2.Height;
     1308%             if strcmp(NomTypeIma,'*')
     1309%                 Param.Civ2.FrameIndexA=i1_civ2(ifile);
     1310%                 Param.Civ2.FrameIndexB=i2_civ2(ifile);
     1311%             else% case of movies indexed with i, the frame index is then in j
     1312%                 Param.Civ2.FrameIndexA=j1_civ2(j);
     1313%                 Param.Civ2.FrameIndexB=j2_civ2(j);
     1314%             end
     1315%         end
     1316%       
     1317%         % write the command and eventually the cmx, xml or nml files
     1318%         cmd=write_cmd(Param);
     1319%         write_param(Param);
     1320%               
     1321%         % create the command file name .m, .bat or .sh depending on the ok option
     1322%         switch Param.Program
     1323%             case {'civ_matlab'}
     1324%                 filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.m');           
     1325%                 [BatRoot,BatFile]=fileparts(filename_bat);
     1326%                  BatFile=regexprep(BatFile,'-','__');%transform name to suppress'-' (not valid for .m files)
     1327%                  filename_bat=[fullfile(BatRoot,BatFile) '.m'];
     1328%             case {'CivX','CivAll','civ_matlab.sh'}
     1329%                 switch computer
     1330%                     case {'PCWIN','PCWIN64'}
     1331%                         filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.bat');
     1332%                     case {'GLNX86','GLNXA64','MACI64'}
     1333%                         filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
     1334%                 end
     1335%         end
     1336%         
     1337%         % print the command in the bat file
     1338%         [fid,message]=fopen(filename_bat,'w');
     1339%         if isequal(fid,-1)
     1340%             errormsg=['creation of .bat file: ' message];
     1341%             return
     1342%         end
     1343%         fprintf(fid,cmd);
     1344%         fclose(fid);
     1345%         
     1346%         % special case for civ_matlab on cluster
     1347%         if strcmp(Param.Program,'civ_matlab') && strcmp(Param.RunMode,'cluster')
     1348%             filename_bat2=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
     1349%             [fid,message]=fopen(filename_bat2,'w');
     1350%             if isequal(fid,-1)
     1351%                 errormsg=['creation of .bat file: ' message];
     1352%                 return
     1353%             end
     1354%             fprintf(fid,['#!/bin/bash \n' ...
     1355%                 '/etc/sysprofile \n'...
     1356%                 'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
     1357%                 'addpath(''' path_civ ''');\n']);
     1358% %             for p=1:length(batch_file_list)
     1359%                 fprintf(fid,['run ' filename_bat '\n']);
     1360% %             end
     1361%             fprintf(fid, 'exit\nEND_MATLAB\n');
     1362%             fclose(fid);
     1363%             filename_bat=filename_bat2;
     1364%         end
     1365%         
     1366%         switch computer
     1367%             case {'GLNX86','GLNXA64','MACI64'}
     1368%                 system(['chmod +x ' filename_bat]);
     1369%         end
     1370%         batch_file_list{length(batch_file_list)+1}=filename_bat;
     1371%     end
     1372% end
     1373%
     1374% %% start calculation
     1375% %computation on cluster
     1376% %if batch ==3
     1377% switch Param.RunMode,
     1378%     case 'cluster'
     1379%         switch batch_mode
     1380%             case 'sge' %at the moment only psmn ENS Lyon uses it
     1381%                 for p=1:length(batch_file_list)
     1382%                     %cmd=['!qsub -p ' pvalue ' -q civ_input.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
     1383%                     cmd=['!qsub -q piv1,piv2,piv3 '...
     1384%                         '-e ' regexprep(batch_file_list{p},'.bat','.errors') ' -o ' regexprep(batch_file_list{p},'.bat','.log ')...
     1385%                         ' -v ' 'LD_LIBRARY_PATH=/home/sjoubaud/matlab_sylvain/civx/lib ' batch_file_list{p}];
     1386%                     display(cmd);eval(cmd);
     1387%                 end
     1388%             case 'oar_old' % to remove
     1389%                 for p=1:length(batch_file_list)
     1390%                     oar_command=['!oarsub -n CIVX -q nicejob '...
     1391%                         '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
     1392%                         '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
     1393%                     display(oar_command);eval(oar_command);
     1394%                 end
     1395%             case 'oar'
     1396%                 max_walltime=3600*12; % 12h max
     1397%                 oar_modes={'oar-parexec','oar-dispatch','mpilauncher'};
     1398%                 text={'Batch processing on servcalcul3 LEGI';...
     1399%                     'Please choose one of the followint modes';...
     1400%                     '* oar-parexec : default and best choice';...
     1401%                     '* oar-dispatch : jobs in a container of several cores';...
     1402%                     '* mpilauncher : one single parallel mpi job using several cores';...
     1403%                     '**********************************'...
     1404%                     };
     1405%                 [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
     1406%                     'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
     1407%                 switch oar_modes{S}
     1408%                     case 'oar-parexec' %oar-dispatch.pl
     1409%                         if strcmp(Param.Program,'civ_matlab')
     1410%                             ncores=1;
     1411%                             msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
     1412%                         else
     1413%                         answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
     1414%                         ncores=str2double(answer{1});
     1415%                         end
     1416%
     1417%                         extra_oar=answer{2};
     1418%                         walltime_onejob=600;%seconds
     1419%                         filename_joblist=fullfile(RootBat,'job_list.txt');
     1420%                         fid=fopen(filename_joblist,'w');
     1421%                         for p=1:length(batch_file_list)
     1422%                             fprintf(fid,[batch_file_list{p} '\n']);
     1423%                         end
     1424%                         fclose(fid);
     1425%                         oar_command=['oarsub -n CIVX '...
     1426%                             '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
     1427%                             '-l /core=' num2str(ncores) ','...
     1428%                             'walltime=' datestr(min(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,max_walltime/86400),13) ' '...
     1429%                             '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
     1430%                             '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
     1431%                             extra_oar ' '...
     1432%                             '"oar-parexec -s -f ' filename_joblist ' '...
     1433%                             '-l ' filename_joblist '.log"\n'];
     1434%                         filename_oarcommand=fullfile(RootBat,'oar_command');
     1435%                         fid=fopen(filename_oarcommand,'w');
     1436%                         fprintf(fid,oar_command);
     1437%                         fclose(fid);
     1438%                         fprintf(oar_command);% display in command line
     1439%                         system(oar_command);
     1440% %                         eval(['! . ' filename
     1441% %                             _oarcommand])
     1442%                     case 'oar-dispatch' %oar-dispatch.pl
     1443%                         ncores=str2double(...
     1444%                             inputdlg('Number of cores (max 36)','oarsub parameter',1,{'6'})...
     1445%                             );
     1446%                         walltime_onejob=600;%seconds
     1447%                         filename_joblist=fullfile(RootBat,'job_list.txt');
     1448%                         fid=fopen(filename_joblist,'w');
     1449%                         for p=1:length(batch_file_list)
     1450%                             oar_command=['oarsub -n CIVX '...
     1451%                                 '-E ' regexprep(batch_file_list{p},'\.bat\>','.stderr') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.stdout ')...
     1452%                                 '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
     1453%                             fprintf(fid,[oar_command '\n']);
     1454%                         end
     1455%                         fclose(fid);
     1456%                         oar_command=['oarsub -t container -n civx-container '...
     1457%                             '-l /core=' num2str(ncores)...
     1458%                             ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13) ' '...
     1459%                             '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
     1460%                             '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
     1461%                             '"oar-dispatch -f ' filename_joblist '"'];
     1462%                         filename_oarcommand=fullfile(RootBat,'oar_command');
     1463%                         fid=fopen(filename_oarcommand,'w');
     1464%                         fprintf(fid,[oar_command '\n']);
     1465%                         fclose(fid);
     1466%                         display(oar_command);
     1467%                         eval(['! . ' filename_oarcommand])
     1468%                     case 'mpilauncher'
     1469%                         filename_joblist=fullfile(RootBat,'job_list.txt');
     1470%                         fid=fopen(filename_joblist,'w');
     1471%                         
     1472%                         for p=1:length(batch_file_list)
     1473%                             fprintf(fid,[batch_file_list{p} '\n']);
     1474%                         end
     1475%                         fclose(fid)
     1476%                         text_oarscript=[...
     1477%                             '#!/bin/bash \n'...
     1478%                             '#OAR -n Mylauncher \n'...
     1479%                             '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
     1480%                             '#OAR -E ' fullfile(RootBat,'stderrfile.log') ' \n'...
     1481%                             '#OAR -O ' fullfile(RootBat,'stdoutfile.log') ' \n'...
     1482%                             '# ========================================================= \n'...
     1483%                             '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
     1484%                             '# application for coriolis PIV post-processing. \n'...
     1485%                             '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
     1486%                             '# This wrapper assert that the user has the same environment on all the \n'...
     1487%                             '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
     1488%                             '# \n'...
     1489%                             '# REQUIREMENT: \n'...
     1490%                             '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
     1491%                             '# If a different location is used, change the line following the comment "Bidouille" \n'...
     1492%                             '# ========================================================= \n'...
     1493%                             '#   USER should only modify these 2 lines  \n'...
     1494%                             'WORKDIR=' pwd ' \n'...
     1495%                             'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
     1496%                             '# ========================================================= \n'...
     1497%                             '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
     1498%                             'echo "job starting on: "`hostname` \n'...
     1499%                             'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
     1500%                             'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
     1501%                             '#========== Bidouille ============== \n'...
     1502%                             'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
     1503%                             'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
     1504%                             'echo "I run: $CMD"  \n'...
     1505%                             '$CMD \n'...
     1506%                             'echo "job ending" \n'...
     1507%                             ];
     1508%                         %                 oarsub -S ./oar.sub
     1509%                         filename_oarscript=fullfile(RootBat,'oar_command');
     1510%                         fid=fopen(filename_oarscript,'w');
     1511%                         fprintf(fid,[text_oarscript]);
     1512%                         fclose(fid);
     1513%                         eval(['!chmod +x  ' filename_oarscript]);
     1514%                         eval(['!oarsub -S ' filename_oarscript]);
     1515%                 end
     1516%         end
     1517%     case {'background','local'}
     1518%         switch Param.Program
     1519%             case {'civ_matlab'}
     1520%                 switch Param.RunMode
     1521%                     case 'background'
     1522%                         switch computer
     1523%                             case {'PCWIN','PCWIN64'}
     1524%                                 filename_superbat=fullfile(RootBat,'job_list.bat');
     1525%                                 fid=fopen(filename_superbat,'w');
     1526%                                 if fid==-1
     1527%                                     msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
     1528%                                     return
     1529%                                 end
     1530%                                  fprintf(fid,['matlab -automation '...
     1531%                                      '-r "addpath(''' regexprep(path_civ,'\\','\\\\') ''');']);
     1532%                                 for p=1:length(batch_file_list)
     1533%                                     fprintf(fid,['run ' regexprep(batch_file_list{p},'\\','\\\\') ';']);
     1534%                                 end
     1535%                                  fprintf(fid, 'exit"');
     1536%                                 fclose(fid);
     1537%                                 dos([filename_superbat ' &']);
     1538%                             case {'GLNX86','GLNXA64','MACI64'}
     1539%                                 filename_superbat=fullfile(RootBat,'job_list.sh');
     1540%                                 fid=fopen(filename_superbat,'w');
     1541%                                 if fid==-1
     1542%                                     msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
     1543%                                     return
     1544%                                 end
     1545%                                 fprintf(fid,['#!/bin/bash \n' ...
     1546%                                     '/etc/sysprofile \n'...
     1547%                                     'matlab -nodisplay -nosplash -nojvm -logfile  <<END_MATLAB \n'...
     1548%                                     'addpath(''' path_civ ''');\n']);
     1549%                                 for p=1:length(batch_file_list)
     1550%                                     fprintf(fid,['run ' batch_file_list{p} '\n']);
     1551%                                 end
     1552%                                 fprintf(fid, 'exit\nEND_MATLAB\n');
     1553%                                 fclose(fid);
     1554%                                 system(['chmod +x ' filename_superbat]);
     1555%                                 system([filename_superbat ' &']);
     1556%                         end
     1557%                     case 'local'
     1558%                         for p=1:length(batch_file_list)
     1559%                             fid=fopen(batch_file_list{p});
     1560%                             eval(fscanf(fid,'%s'));
     1561%                             fclose(fid);
     1562%                         end
     1563%                 end
     1564%             case {'CivX','CivAll','civ_matlab.sh'}
     1565%                     switch computer
     1566%                         case {'PCWIN','PCWIN64'}
     1567%                             filename_superbat=fullfile(RootBat,'job_list.bat');
     1568%                             fid=fopen(filename_superbat,'w');
     1569%                             if fid==-1
     1570%                                 msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
     1571%                                 return
     1572%                             end
     1573%                             for p=1:length(batch_file_list)
     1574%                                 fprintf(fid,['@call "' regexprep(batch_file_list{p},'\\','\\\\') '"' '\n']);
     1575%                             end
     1576%                             fclose(fid);
     1577%                             system(['chmod +x ' filename_superbat]);
     1578%                         case {'GLNX86','GLNXA64','MACI64'}
     1579%                             filename_superbat=fullfile(RootBat,'job_list.bat');
     1580%                             fid=fopen(filename_superbat,'w');
     1581%                             if fid==-1
     1582%                                 msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
     1583%                                 return
     1584%                             end
     1585%                             for p=1:length(batch_file_list)
     1586%                                 fprintf(fid,['sh ' batch_file_list{p} '\n']);
     1587%                             end
     1588%                             fclose(fid);
     1589%                             system(['chmod +x ' filename_superbat]);
     1590%                     end
     1591%                 switch Param.RunMode
     1592%                     case 'background'
     1593%                         system([filename_superbat ' &']);% execute main commmand see what it does in dos ?
     1594%                     case 'local'
     1595%                         system(filename_superbat);
     1596%                 end
     1597%         end
     1598% end
     1599%
     1600%
     1601% %% save interface state
     1602% if isfield(filecell,'nc')
     1603%     if isfield(filecell.nc,'civ2')
     1604%         fileresu=filecell.nc.civ2{1,1};
     1605%     else
     1606%         fileresu=filecell.nc.civ1{1,1};
     1607%     end
     1608% end
     1609% [RootPath,SubDir,RootFile]=fileparts_uvmat(fileresu);
     1610% namedoc=fullfile(RootPath,SubDir,RootFile);
     1611% detect=1;
     1612% while detect==1
     1613%     namefigfull=[namedoc '.fig'];
     1614%     hh=dir(namefigfull);
     1615%     if ~isempty(hh)
     1616%         detect=1;
     1617%         namedoc=[namedoc '.0'];
     1618%     else
     1619%         detect=0;
     1620%     end
     1621% end
     1622% Param=rmfield(Param,'status');
     1623% Param=rmfield(Param,'xml');
     1624% t=struct2xml(Param);
     1625% t=set(t,1,'name','Civ');% set the head label
     1626% save(t,[namedoc '.civ.xml']); %save GUI  parameters as xml file
     1627% % saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
     1628%
     1629% %Save info in personal profile (initiate browser next time) TODO
     1630% MenuFile={};
     1631% dir_perso=prefdir;
     1632% profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
     1633% if exist(profil_perso,'file')
     1634%     hh=load (profil_perso);
     1635%       if isfield(hh,'MenuFile')
     1636%           MenuFile=hh.MenuFile;
     1637%       end
     1638%       if isfield(filecell.nc,'civ2')
     1639%           MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
     1640%       else
     1641%            MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
     1642%       end
     1643%       save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
     1644% else
     1645%     MenuFile=filecell.ima1.civ1(1,1);
     1646%     save (profil_perso,'MenuFile')
     1647% end
     1648
     1649% %------------------------------------------------------------------------
     1650% % --- determine the list of reference indices of processing file
     1651% function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
     1652% %------------------------------------------------------------------------
     1653% errormsg=''; %default error message
     1654% first_i=str2double(get(handles.first_i,'String'));%first index i
     1655% last_i=str2double(get(handles.last_i,'String'));%last index i
     1656% incr_i=str2double(get(handles.incr_i,'String'));% increment
     1657% if isequal(get(handles.first_j,'Visible'),'on')
     1658%     first_j=str2double(get(handles.first_j,'String'));%first index j
     1659%     last_j=str2double(get(handles.last_j,'String'));%last index j
     1660%     incr_j=str2double(get(handles.incr_j,'String'));% increment
     1661% else
     1662%     first_j=1;
     1663%     last_j=1;
     1664%     incr_j=1;
     1665% end
     1666% ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
     1667% ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
     1668% if isnan(first_i)||isnan(first_j)
     1669%     errormsg='first field number not defined';
     1670% elseif isnan(last_i)||isnan(last_j)
     1671%     errormsg='last field number not defined';
     1672% elseif isnan(incr_i)||isnan(incr_j)
     1673%     errormsg='increment in field number not defined';
     1674% elseif last_i < first_i || last_j < first_j
     1675%     errormsg='last field number must be larger than the first one';
     1676% end
    17341677
    17351678%------------------------------------------------------------------------
     
    38213764    set(hview_field,'CurrentAxes',hhview_field.PlotAxes)
    38223765    ViewData=get(hview_field,'UserData');
    3823     ViewData.CivHandle=handles.civ_series;% indicate the handle of the civ GUI in view_field
     3766    ViewData.CivHandle=handles.civ_input;% indicate the handle of the civ GUI in view_field
    38243767    ViewData.PlotAxes.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
    38253768    ViewData.PlotAxes.X=Grid.Civ1_X; %keep the set of points in memeory
     
    40093952% --- Executes on button press in TestCiv2.
    40103953function TestCiv2_Callback(hObject, eventdata, handles)
    4011 
    4012 function RootFile_Callback(hObject, eventdata, handles)
    4013 
    4014 function SubDirImages_Callback(hObject, eventdata, handles)
    4015 
    4016 
    4017 
    4018 function errormsg=write_param(Param)
    4019 %------------------------------------------------------------------------
    4020 %pixels per cm and matrix of the image times, read from the .civ_input file by uvmat
    4021 %changes : filename_cmx -> filename ( no extension )
    4022 errormsg='';
    4023 switch Param.Program
    4024     case 'CivX'
    4025         if Param.CheckCiv1
    4026             filename=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_CMX$2$3.civ1.cmx');
    4027             if isequal(Param.Civ1.Dt,0)
    4028                 Param.Civ1.Dt=1 ;%case of 'displacement' mode
    4029             end
    4030             Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'.png','');
    4031             Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'.png','');
    4032             [fid,errormsg]=fopen(filename,'w');
    4033             if isequal(fid,-1)
    4034                 errormsg=['cmd file ' filename ' cannot be created: ' errormsg];
    4035                 return
    4036             end
    4037             fprintf(fid,['##############   CMX file' '\n' ]);
    4038             fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
    4039             fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
    4040             fprintf(fid,  ['XX' '\n' ]);
    4041             if isfield(Param.Civ1,'Mask')
    4042                 fprintf(fid,  ['Mask ' 'y' '\n' ]);
    4043                 fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.Mask,'\\','\\\\') '\n' ]);
    4044             else
    4045                 fprintf(fid,  ['Mask ' 'n' '\n' ]);
    4046                 fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
    4047             end
    4048             fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageWidth) ' ' num2str(Param.Civ1.ImageHeight) '\n' ]);   %VERIFIER CAS GENERAL ?
    4049             fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.CorrBoxSize(1)) ' ' num2str(Param.Civ1.CorrBoxSize(2)) '\n' ]);
    4050             fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.SearchBoxSize(1)) ' ' num2str(Param.Civ1.SearchBoxSize(2)) '\n' ]);
    4051             fprintf(fid,   ['RO ' num2str(Param.Civ1.CorrSmooth) '\n' ]);
    4052             if isfield(Param.Civ1,'Grid')
    4053                 fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
    4054             else
    4055                 fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
    4056             end
    4057             fprintf(fid,   ['XX 1.0' '\n' ]);
    4058             fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.Time) '\n' ]);
    4059             fprintf(fid,  ['PixCmXY ' '1' ' ' '1' '\n' ]);
    4060             fprintf(fid,  ['XX 1' '\n' ]);
    4061             fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.SearchBoxShift(1)) ' '  num2str(Param.Civ1.SearchBoxShift(2)) '\n' ]);
    4062             if isfield(Param.Civ1,'Grid')
    4063                 fprintf(fid,  ['Grid ' 'y' '\n' ]);
    4064                 fprintf(fid,   ['GridName ' regexprep(Param.Civ1.Grid,'\\','\\\\') '\n' ]);
    4065             else
    4066                 fprintf(fid,  ['Grid ' 'n' '\n' ]);
    4067                 fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
    4068             end
    4069             fprintf(fid,   ['XX 85' '\n' ]);
    4070             fprintf(fid,   ['XX 1.0' '\n' ]);
    4071             fprintf(fid,   ['XX 1.0' '\n' ]);
    4072             fprintf(fid,   ['Hart 1' '\n' ]);
    4073             fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
    4074             fprintf(fid,   ['Deformation 0' '\n' ]);
    4075             fprintf(fid,  ['CorrelationMin 0' '\n' ]);
    4076             fprintf(fid,   ['IntensityMin 0' '\n' ]);
    4077             if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
    4078                 fprintf(fid,  ['SeuilImage n' '\n' ]);
    4079                 fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
    4080             else% Image threshold  activated
    4081                 if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
    4082                     Param.Civ1.MaxIma=2^Param.Civ1.ImageBitDepth;%take the max image value as upper bound by default
    4083                 end
    4084                 fprintf(fid,  ['SeuilImage y' '\n' ]);
    4085                 fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
    4086             end
    4087             fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
    4088             fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
    4089             fclose(fid);
    4090         end
    4091        
    4092         if Param.CheckCiv2
    4093             filename=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_CMX$2$3.civ2.cmx');
    4094 
    4095             if isequal(Param.Civ2.Dt,'0')
    4096                 Param.Civ2.Dt='1' ;%case of 'displacement' mode
    4097             end
    4098             Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'.png','');
    4099             Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'.png','');% bug : .png appears two times ?
    4100             [fid,errormsg]=fopen(filename,'w');
    4101             if isequal(fid,-1)
    4102                 return
    4103             end
    4104             fprintf(fid,['##############   CMX file' '\n' ]);
    4105             fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
    4106             fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
    4107             fprintf(fid,  ['XX' '\n' ]);
    4108             if isfield(Param.Civ2,'Mask')
    4109                 fprintf(fid,  ['Mask ' 'y' '\n' ]);
    4110                 fprintf(fid,  ['MaskName ' regexprep(Param.Civ2.Mask,'\\','\\\\') '\n' ]);
    4111             else
    4112                 fprintf(fid,  ['Mask ' 'n' '\n' ]);
    4113                 fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
    4114             end
    4115             % fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
    4116             % fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
    4117             fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageWidth) ' ' num2str(Param.Civ2.ImageHeight) '\n' ]);
    4118             % fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
    4119             fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n' ]);
    4120             fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n']);
    4121             fprintf(fid, ['RO ' num2str(Param.Civ2.CorrSmooth) '\n']);
    4122             if isfield(Param.Civ2,'Grid')
    4123                 fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
    4124             else
    4125                 fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
    4126             end
    4127             % fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
    4128             fprintf(fid, ['XX 1.0' '\n' ]);
    4129             fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.Time) '\n' ]);
    4130             fprintf(fid, ['PixCmXY ' '1' ' ' '1' '\n' ]);
    4131             fprintf(fid, ['XX 1' '\n' ]);
    4132             fprintf(fid, 'ShiftXY 0 0\n');
    4133             if isfield(Param.Civ2,'Grid')
    4134                 fprintf(fid,  ['Grid ' 'y' '\n' ]);
    4135                 fprintf(fid,   ['GridName ' regexprep(Param.Civ2.Grid,'\\','\\\\') '\n' ]);
    4136             else
    4137                 fprintf(fid,  ['Grid ' 'n' '\n' ]);
    4138                 fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
    4139             end
    4140             % fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
    4141             % fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
    4142             fprintf(fid, ['XX 85' '\n' ]);
    4143             fprintf(fid, ['XX 1.0' '\n' ]);
    4144             fprintf(fid, ['XX 1.0' '\n' ]);
    4145             fprintf(fid, ['Hart 1' '\n' ]);
    4146             fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
    4147             fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
    4148             fprintf(fid,  ['CorrelationMin 0' '\n' ]);
    4149             fprintf(fid,   ['IntensityMin 0' '\n' ]);
    4150            
    4151             if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
    4152                 fprintf(fid,  ['SeuilImage n' '\n' ]);
    4153                 fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
    4154             else% Image threshold  activated
    4155                 if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
    4156                     Param.Civ2.MaxIma=2^Param.Civ2.ImageBitDepth;%take the max image value as upper bound by default
    4157                 end
    4158                 fprintf(fid,  ['SeuilImage y' '\n' ]);
    4159                 fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
    4160             end
    4161             fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
    4162             fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
    4163             fclose(fid);
    4164         end
    4165     case {'civ_matlab','civ_matlab.sh'}
    4166         filename=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_XML$2$3.xml');
    4167         fileattrib(fileparts(filename),'+w +x','o g');% set writting access
    4168         save(struct2xml(Param),filename);
    4169 end
    4170 
    4171 
    4172 function cmd=write_cmd(Param)
    4173 
    4174 % initiate system command
    4175 cmd=[];
    4176 
    4177 switch Param.Program
    4178     case 'CivX'
    4179         if isunix % check: necessaire aussi en RUN?
    4180             cmd=[cmd '#!/bin/bash \n'...
    4181                 '#$ -cwd \n'...
    4182                 'hostname && date \n'...
    4183                 'umask 002 \n'];%allow writting access to created files for user group
    4184         end
    4185     case 'CivAll'
    4186         if isunix % check: necessaire aussi en RUN?
    4187             cmd=[cmd '#!/bin/bash \n'...
    4188                 '#$ -cwd \n'...
    4189                 'hostname && date \n'...
    4190                 'umask 002 \n'];%allow writting access to created files for user group
    4191         end
    4192 end
    4193 
    4194 filename=regexprep(Param.OutputFile,'.nc','');
    4195 
    4196 if Param.CheckCiv1
    4197     switch Param.Program
    4198         case 'CivX'
    4199             if(isunix) %unix (or Mac) system
    4200                 cmd=[cmd 'cp -f ' regexprep(filename,'(.+)/(.+$)','$1/0_CMX/$2.civ1.cmx ') regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')...% the cmx file gives the name to the nc file
    4201                     Param.xml.Civ1Bin ' -f ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx >') regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.civ1.log \n')... % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
    4202                     'rm ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')];
    4203             else %Windows system
    4204                 filename=regexprep(filename,'\\','\\\\');
    4205                 cmd=['copy /Y ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_CMX\\\\$2.civ1.cmx" ') regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')...
    4206                     '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\') '" -f ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" > ')...
    4207                     regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_LOG\\\\$2.civ1.log" \n')... % redirect standard output to the log file
    4208                     'del ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')];
    4209             end
    4210         case 'CivAll'
    4211             CivAllCmd=[CivAllCmd ' civ1 '];
    4212             str=CIV1_CMD_Unified(filecell.nc.civ1{ifile,j},'',Param.Civ1);
    4213             fieldnames=fields(str);
    4214             [CivAllxml,uid_civ1]=add(CivAllxml,1,'element','civ1');
    4215             for ilist=1:length(fieldnames)
    4216                 val=eval(['str.' fieldnames{ilist}]);
    4217                 if ischar(val)
    4218                     [CivAllxml,uid_t]=add(CivAllxml,uid_civ1,'element',fieldnames{ilist});
    4219                     [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
    4220                 end
    4221             end
    4222     end
    4223 end
    4224 
    4225 if Param.CheckFix1
    4226     switch Param.Program
    4227         case 'CivX'
    4228             cmd=[cmd...
    4229                 cmd_fix(Param,'Fix1') '\n'];
    4230         case 'CivAll'%to abandon
    4231             fix1.inputFileName=filecell.nc.civ1{ifile,j} ;
    4232             fix1.fi1=num2str(param.fix1.flagindex1(1));
    4233             fix1.fi2=num2str(param.fix1.flagindex1(2));
    4234             fix1.fi3=num2str(param.fix1.flagindex1(3));
    4235             fix1.threshC=num2str(param.fix1.thresh_vecC1);
    4236             fix1.threshV=num2str(param.fix1.thresh_vel1);
    4237             fieldnames=fields(fix1);
    4238             [CivAllxml,uid_fix1]=add(CivAllxml,1,'element','fix1');
    4239             for ilist=1:length(fieldnames)
    4240                 val=eval(['fix1.' fieldnames{ilist}]);
    4241                 if ischar(val)
    4242                     [CivAllxml,uid_t]=add(CivAllxml,uid_fix1,'element',fieldnames{ilist});
    4243                     [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
    4244                 end
    4245             end
    4246             CivAllCmd=[CivAllCmd ' fix1 '];
    4247     end
    4248 end
    4249 
    4250 
    4251 %CheckPatch1
    4252 if Param.CheckPatch1
    4253     switch Param.Program
    4254         case 'CivX'
    4255             cmd=[cmd...
    4256                 cmd_patch(Param,'Patch1') '\n'];
    4257         case 'CivAll'
    4258             patch1.inputFileName=filecell.nc.civ1{ifile,j} ;
    4259             patch1.nopt=subdomain_patch1;
    4260             patch1.maxdiff=thresh_patch1;
    4261             patch1.ro=rho_patch1;
    4262             test_grid=get(handles.get_gridpatch1,'Value');
    4263             if test_grid
    4264                 patch1.gridflag='y';
    4265                 gridname=get(handles.grid_patch1,'String');
    4266                 if isequal(gridname(end-3:end),'grid')
    4267                     nbslice_grid=str2double(gridname(1:end-4)); %
    4268                     if ~isnan(nbslice_grid)
    4269                         i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
    4270                         patch1.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
    4271                         %                                 patch1.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
    4272                         if ~exist(patch1.gridPatch,'file')
    4273                             errormsg='grid file absent for patch1';
    4274                             return
    4275                         end
    4276                     elseif exist(gridname,'file')
    4277                         patch1.gridPatch=gridname;
    4278                     else
    4279                         errormsg='grid file absent for patch1';
    4280                         return
    4281                     end
    4282                 end
    4283             else
    4284                 patch1.gridPatch='none';
    4285                 patch1.gridflag='n';
    4286                 patch1.m=nx_patch1;
    4287                 patch1.n=ny_patch1;
    4288             end
    4289             patch1.convectFlow='n';
    4290             fieldnames=fields(patch1);
    4291             [CivAllxml,uid_patch1]=add(CivAllxml,1,'element','patch1');
    4292             for ilist=1:length(fieldnames)
    4293                 val=eval(['patch1.' fieldnames{ilist}]);
    4294                 if ischar(val)
    4295                     [CivAllxml,uid_t]=add(CivAllxml,uid_patch1,'element',fieldnames{ilist});
    4296                     [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
    4297                 end
    4298             end
    4299             CivAllCmd=[CivAllCmd ' patch1 '];
    4300     end
    4301 end
    4302 
    4303 if Param.CheckCiv2
    4304     switch Param.Program
    4305         case 'CivX'
    4306             if(isunix)
    4307                 cmd=[cmd 'cp -f '  regexprep(filename,'(.+)/(.+$)','$1/0_CMX/$2.civ2.cmx ') regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')...
    4308                     Param.xml.Civ2Bin ' -f ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx >') regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.civ2.log \n')...% redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
    4309                     'rm ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
    4310             else
    4311                 filename=regexprep(Param.OutputFile,'.nc','');
    4312                 filename=regexprep(filename,'\\','\\\\');
    4313                 cmd=[cmd 'copy /Y ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_CMX\\\\$2.civ2.cmx" ') regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')...
    4314                     '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" > ')...
    4315                      regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_LOG\\\\$2.civ2.log" \n')... % redirect standard output to the log file
    4316                     'del ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')];                       
    4317             end
    4318                  
    4319         case 'CivAll'
    4320             CivAllCmd=[CivAllCmd ' civ2 '];
    4321             str=CIV2_CMD_Unified(filecell.nc.civ2{ifile,j},'',Param.Civ2);
    4322             fieldnames=fields(str);
    4323             [CivAllxml,uid_civ2]=add(CivAllxml,1,'element','civ2');
    4324             for ilist=1:length(fieldnames)
    4325                 val=eval(['str.' fieldnames{ilist}]);
    4326                 if ischar(val)
    4327                     [CivAllxml,uid_t]=add(CivAllxml,uid_civ2,'element',fieldnames{ilist});
    4328                     [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
    4329                 end
    4330             end
    4331     end
    4332 end
    4333 
    4334 % CheckFix2
    4335 if Param.CheckFix2==1
    4336     switch Param.Program
    4337         case 'CivX'
    4338             cmd=[cmd...
    4339                 cmd_fix(Param,'Fix2') '\n'];
    4340         case 'CivAll'
    4341             fix2.inputFileName=filecell.nc.civ2{ifile,j} ;
    4342             fix2.fi1=num2str(flagindex2(1));
    4343             fix2.fi2=num2str(flagindex2(2));
    4344             fix2.fi3=num2str(flagindex2(3));
    4345             fix2.threshC=num2str(thresh_vec2C);
    4346             fix2.threshV=num2str(thresh_vel2);
    4347             fieldnames=fields(fix2);
    4348             [CivAllxml,uid_fix2]=add(CivAllxml,1,'element','fix2');
    4349             for ilist=1:length(fieldnames)
    4350                 val=eval(['fix2.' fieldnames{ilist}]);
    4351                 if ischar(val)
    4352                     [CivAllxml,uid_t]=add(CivAllxml,uid_fix2,'element',fieldnames{ilist});
    4353                     [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
    4354                 end
    4355             end
    4356             CivAllCmd=[CivAllCmd ' fix2 '];
    4357     end
    4358 end
    4359 
    4360 %CheckPatch2
    4361 if Param.CheckPatch2==1
    4362    
    4363     switch Param.Program
    4364        
    4365         case 'CivX'
    4366             cmd=[cmd...
    4367                 cmd_patch(Param,'Patch2') '\n'];
    4368         case 'CivAll'
    4369             patch2.inputFileName=filecell.nc.civ1{ifile,j} ;
    4370             patch2.nopt=subdomain_patch2;
    4371             patch2.maxdiff=thresh_patch2;
    4372             patch2.ro=rho_patch2;
    4373             test_grid=get(handles.get_gridpatch2,'Value');
    4374             if test_grid
    4375                 patch2.gridflag='y';
    4376                 gridname=get(handles.grid_patch2,'String');
    4377                 if isequal(gridname(end-3:end),'grid')
    4378                     nbslice_grid=str2double(gridname(1:end-4)); %
    4379                     if ~isnan(nbslice_grid)
    4380                         i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
    4381                         patch2.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
    4382                         %                                 patch2.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
    4383                         if ~exist(patch2.gridPatch,'file')
    4384                             errormsg='grid file absent for patch2';
    4385                             return
    4386                         end
    4387                     elseif exist(gridname,'file')
    4388                         patch2.gridPatch=gridname;
    4389                     else
    4390                         errormsg='grid file absent for patch2';
    4391                         return
    4392                     end
    4393                 end
    4394             else
    4395                 patch2.gridPatch='none';
    4396                 patch2.gridflag='n';
    4397                 patch2.m=nx_patch2;
    4398                 patch2.n=ny_patch2;
    4399             end
    4400             patch2.convectFlow='n';
    4401             fieldnames=fields(patch2);
    4402             [CivAllxml,uid_patch2]=add(CivAllxml,1,'element','patch2');
    4403             for ilist=1:length(fieldnames)
    4404                 val=eval(['patch2.' fieldnames{ilist}]);
    4405                 if ischar(val)
    4406                     [CivAllxml,uid_t]=add(CivAllxml,uid_patch2,'element',fieldnames{ilist});
    4407                     [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
    4408                 end
    4409             end
    4410             CivAllCmd=[CivAllCmd ' patch2 '];
    4411     end
    4412 end
    4413 
    4414 switch Param.Program
    4415     case 'CivAll'
    4416         save(CivAllxml,[Param.OutputFile '.xml']);
    4417         cmd=[cmd sparam.CivBin ' -f ' Param.OutputFile '.xml '  CivAllCmd ' >' Param.OutputFile '.log' '\n'];
    4418     case 'civ_matlab'
    4419                     switch computer
    4420                         case {'PCWIN','PCWIN64'}                     
    4421                             filename=regexprep(filename,'\\','\\\\');% add '\' so that '\' are left as characters
    4422                                     cmd=['civ_matlab(''' regexprep(filename,'(.+)([/\\])(.+$)','$1$20_XML\\$2$3.xml') ''','''...
    4423             filename '.nc'');'];
    4424                         case {'GLNX86','GLNXA64','MACI64'}
    4425                                     cmd=['civ_matlab(''' regexprep(filename,'(.+)([/\\])(.+$)','$1$20_XML$2$3.xml') ''','''...
    4426             filename '.nc'');'];
    4427                     end
    4428 
    4429        
    4430     case 'civ_matlab.sh'
    4431         CivmBin=fullfile(fileparts(which('civ')),'civ_matlab.sh'); %path to the source directory of uvmat
    4432         switch computer
    4433             case {'PCWIN','PCWIN64'}
    4434                 filename=regexprep(filename,'\\','\\\\');% add '\' so that '\' are left as characters
    4435                 % TODO launch command in DOS
    4436             case {'GLNX86','GLNXA64','MACI64'}
    4437                 cmd=['#!/bin/bash \n '...
    4438                     '#$ -cwd \n '...
    4439                     'hostname && date \n '...
    4440                     'umask 002 \n'...
    4441                     CivmBin ' ' Param.xml.RunTime ' ' regexprep(filename,'(.+)([/\\])(.+$)','$1$20_XML$2$3.xml') ' ' Param.OutputFile '.nc'];%allow writting access to created files for user group
    4442         end
    4443 end   
    4444    
    4445 
    4446 function cmd=cmd_fix(Param,fixname)
    4447 %%
    4448 switch fixname
    4449     case 'Fix1'
    4450         fi2_value=num2str(Param.(fixname).CheckF2);
    4451         filename=regexprep(Param.OutputFile,'.nc','');
    4452     case 'Fix2'
    4453         fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
    4454         filename=regexprep(Param.OutputFile,'.nc','');       
    4455 end
    4456 
    4457 % filename=regexprep(Param.(fixname).OutFileName,'.nc','');
    4458 MaskName_string='';%default
    4459 MaxVel_string='';%default
    4460 if ~isempty(Param.(fixname).MinVel)
    4461     MaxVel_string=[' -threshV ' num2str(Param.(fixname).MinVel)];
    4462 end
    4463 if isunix
    4464     cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
    4465         ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
    4466         ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
    4467         ' >' regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.')  lower(fixname) '.log 2>&1'];
    4468 else
    4469     cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
    4470         ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
    4471         ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
    4472         ' > "' regexprep(filename,'(\w+)\\(\w+$)','$1\\0_LOG\\$2.') lower(fixname) '.log"'];
    4473     cmd=regexprep(cmd,'\\','\\\\');
    4474 end
    4475 
    4476 
    4477 function cmd=cmd_patch(Param,patchname)
    4478 %% ------------------------------------------------------------------------
    4479 switch patchname
    4480     case 'Patch1'
    4481         filename=regexprep(Param.OutputFile,'.nc','');
    4482     case 'Patch2'
    4483         filename=regexprep(Param.OutputFile,'.nc','');       
    4484 end
    4485 % filename=regexprep(Param.(patchname).OutFileName,'.nc','');
    4486 if isunix
    4487     cmd=[Param.xml.PatchBin...
    4488         ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
    4489         ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
    4490         ' -nopt ' num2str(Param.(patchname).SubDomainSize) ...
    4491         '  > ' regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.')  lower(patchname) '.log 2>&1']; % redirect standard output to the log file
    4492 else
    4493     cmd=['"' Param.xml.PatchBin...
    4494         '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
    4495         ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
    4496         ' -nopt ' num2str(Param.(patchname).SubDomainSize)...
    4497         '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
    4498     cmd=regexprep(cmd,'\\','\\\\');
    4499 end
    4500 
    4501 
    4502 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    4503 % USELESS FUNCTIONS BELOW HERE,  TO CLEAN
    4504 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    4505 
    4506 %------------------------------------------------------------------------
    4507 % --- CheckCiv1  Unified: TO ABADON
    4508 function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
    4509 %------------------------------------------------------------------------
    4510 %pixels per cm and matrix of the image times, read from the .civ_input file by uvmat
    4511 %global CivBin%name of the executable for checkciv1 calculation
    4512 
    4513 civ1.image1=par.ImageA;
    4514 civ1.image2=par.ImageB;
    4515 civ1.imageSize_X=par.npx;
    4516 civ1.imageSize_Y=par.npy;
    4517 civ1.outputFileName=[filename '.nc'];
    4518 civ1.correlationBoxesSize_X=par.ibx;
    4519 civ1.correlationBoxesSize_Y=par.iby;
    4520 civ1.searchBoxesSize_X=par.isx;
    4521 civ1.searchBoxesSize_Y=par.isy;
    4522 civ1.globalShift_X=par.shiftx;
    4523 civ1.globalShift_Y=par.shifty;
    4524 civ1.ro=par.rho;
    4525 civ1.hart='y';
    4526 if isequal(par.gridflag,'y')
    4527     civ1.grid=par.gridname;
    4528 else
    4529     civ1.grid='n';
    4530     civ1.gridSpacing_X=par.dx;
    4531     civ1.gridSpacing_Y=par.dy;
    4532 end
    4533 if isequal(par.maskflag,'y')
    4534     civ1.mask=par.maskname;
    4535 end
    4536 civ1.dt=par.Dt;
    4537 civ1.unit='pixel';
    4538 civ1.absolut_time_T0=par.Time;
    4539 civ1.pixcmx='1';
    4540 civ1.pixcmy='1';
    4541 civ1.convectFlow='n';
    4542 
    4543 xml_civ1_parameters=civ1;
    4544 
    4545 %------------------------------------------------------------------------
    4546 % --- CheckCiv2  Unified: TO ABADON
    4547 function civ2=CIV2_CMD_Unified(filename,namelog,par)
    4548 %------------------------------------------------------------------------
    4549 %pixels per cm and matrix of the image times, read from the .civ_input file by uvmat
    4550 %global CivBin%name of the executable for checkciv1 calculation
    4551 
    4552 filename=regexprep(filename,'.nc','');
    4553 
    4554 civ2.image1=par.ImageA;
    4555 civ2.image2=par.ImageB;
    4556 civ2.imageSize_X=par.npx;
    4557 civ2.imageSize_Y=par.npy;
    4558 civ2.inputFileName=[par.filename_nc1 '.nc'];
    4559 civ2.outputFileName=[filename '.nc'];
    4560 civ2.correlationBoxesSize_X=par.ibx;
    4561 civ2.correlationBoxesSize_Y=par.iby;
    4562 civ2.ro=par.rho;
    4563 %checkciv2.decimalShift=par.CheckDecimal;
    4564 %checkciv2.CheckDeformation=par.CheckDeformation;
    4565 if isequal(par.decimal,'1')
    4566     civ2.decimalShift='y';
    4567 else
    4568     civ2.decimalShift='n';
    4569 end
    4570 if isequal(par.deformation,'1')
    4571     civ2.deformation='y';
    4572 else
    4573     civ2.deformation='n';
    4574 end
    4575 if isequal(par.gridflag,'y')
    4576     civ2.grid=par.gridname;
    4577 else
    4578     civ2.grid='n';
    4579     civ2.gridSpacing_X=par.dx;
    4580     civ2.gridSpacing_Y=par.dy;
    4581 end
    4582 civ2.gridSpacing_X='10';
    4583 civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
    4584 if isequal(par.maskflag,'y')
    4585     civ2.mask=par.maskname;
    4586 else
    4587     civ2.mask='n';
    4588 end
    4589 civ2.dt=par.Dt;
    4590 civ2.unit='pixel';
    4591 civ2.absolut_time_T0=par.Time;
    4592 civ2.pixcmx='1';
    4593 civ2.pixcmy='1';
    4594 civ2.convectFlow='n';
    4595 
    4596 
    4597 % --- Executes on selection change in RunMode.
    4598 function RunMode_Callback(hObject, eventdata, handles)
    4599 
    4600 
    4601 function nb_field2_Callback(hObject, eventdata, handles)
    4602 
    4603 
    4604 function last_j_Callback(hObject, eventdata, handles)
    4605 
    4606 
    4607 function last_i_Callback(hObject, eventdata, handles)
  • trunk/src/series/civ_series.m

    r597 r598  
    1 %'merge_proj': concatene several fields from series, can project them on a regular grid in phys coordinates
     1%'civ_series': PIV function activated by the general GUI series
     2% --- call the sub-functions:
     3%   civ: PIV function itself
     4%   fix: removes false vectors after detection by various criteria
     5%   filter_tps: make interpolation-smoothing
    26%------------------------------------------------------------------------
    3 % function ParamOut=merge_proj(Param)
    4 %------------------------------------------------------------------------
    5 %%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
     7% function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
    68%
    79%OUTPUT
    8 % ParamOut: sets options in the GUI series.fig needed for the function
     10% Data=structure containing the PIV results and information on the processing parameters
     11% errormsg=error message char string, default=''
     12% resul_conv: image inter-correlation function for the last grid point (used for tests)
    913%
    1014%INPUT:
    11 % In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
    12 % In batch mode, Param is the name of the corresponding xml file containing the same information
    13 % when Param.Action.RUN=0 (as activated when the current Action is selected
    14 % in series), the function ouput paramOut set the activation of the needed GUI elements
     15% Param: input images and processing parameters
     16%     .Civ1: for civ1
     17%     .Fix1:
     18%     .Patch1:
     19%     .Civ2: for civ2
     20%     .Fix2:
     21%     .Patch2:
     22% ncfile: name of a netcdf file to be created for the result (extension .nc)
    1523%
    16 % Param contains the elements:(use the menu bar command 'export/GUI config' in series to
    17 % see the current structure Param)
    18 %    .InputTable: cell of input file names, (several lines for multiple input)
    19 %                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
    20 %    .OutputSubDir: name of the subdirectory for data outputs
    21 %    .OutputDirExt: directory extension for data outputs
    22 %    .Action: .ActionName: name of the current activated function
    23 %             .ActionPath:   path of the current activated function
    24 %             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
    25 %             .RUN =0 for GUI input, =1 for function activation
    26 %             .RunMode='local','background', 'cluster': type of function  use
    27 %             
    28 %    .IndexRange: set the file or frame indices on which the action must be performed
    29 %    .FieldTransform: .TransformName: name of the selected transform function
    30 %                     .TransformPath:   path  of the selected transform function
    31 %    .InputFields: sub structure describing the input fields withfields
    32 %              .FieldName: name(s) of the field
    33 %              .VelType: velocity type
    34 %              .FieldName_1: name of the second field in case of two input series
    35 %              .VelType_1: velocity type of the second field in case of two input series
    36 %              .Coord_y: name of y coordinate variable
    37 %              .Coord_x: name of x coordinate variable
    38 %    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
    39 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%civ_series
    40 
    41 function ParamOut=civ_series(Param)
    42 
     24%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
     25%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
     26%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
     27%     This is part of the toolbox UVMAT.
     28%
     29%     UVMAT is free software; you can redistribute it and/or modify
     30%     it under the terms of the GNU General Public License as published by
     31%     the Free Software Foundation; either version 2 of the License, or
     32%     (at your option) any later version.
     33%
     34%     UVMAT is distributed in the hope that it will be useful,
     35%     but WITHOUT ANY WARRANTY; without even the implied warranty of
     36%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     37%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
     38%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
     39
     40function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
     41errormsg='';
     42path_series=fileparts(which('series'));
     43addpath(fullfile(path_series,'series'))
    4344%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
    4445if isstruct(Param) && isequal(Param.Action.RUN,0)
    45     ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
    46     ParamOut.WholeIndexRange='off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
    47     ParamOut.NbSlice='off'; ...%nbre of slices ('off' by default)
    48     ParamOut.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
    49     ParamOut.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
    50     ParamOut.FieldTransform = 'off';...%can use a transform function
    51     ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
    52     ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
    53     ParamOut.OutputDirExt='.civ';%set the output dir extension
    54 return
     46    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
     47    Data.Program=mfilename;
     48    Data.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
     49        Data.WholeIndexRange='off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
     50        Data.NbSlice='off'; ...%nbre of slices ('off' by default)
     51        Data.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
     52        Data.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
     53        Data.FieldTransform = 'off';...%can use a transform function
     54        Data.ProjObject='off';...%can use projection object(option 'off'/'on',
     55        Data.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
     56        Data.OutputDirExt='.civ';%set the output dir extension
     57    return
    5558end
    5659
     
    6366    checkrun=0;
    6467end
    65 
    66 ParamOut=Param; %default output
    67 if ~isfield(Param,'InputFields')
    68     Param.InputFields.FieldName='';
    69 end
    70 OutputSubDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
    71 
    72 %% root input file type
    73 RootPath=Param.InputTable(:,1);
    74 RootFile=Param.InputTable(:,3);
    75 SubDir=Param.InputTable(:,2);
    76 NomType=Param.InputTable(:,4);
    77 FileExt=Param.InputTable(:,5);
    78 [filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
    79 %%%%%%%%%%%%
    80 % The cell array filecell is the list of input file names, while
    81 % filecell{iview,fileindex}:
    82 %        iview: line in the table corresponding to a given file series
    83 %        fileindex: file index within  the file series,
    84 % i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
    85 % i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
    86 %%%%%%%%%%%%
    87 NbSlice=1;%default
    88 if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
    89     NbSlice=Param.IndexRange.NbSlice;
    90 end
    91 nbview=numel(i1_series);%number of input file series (lines in InputTable)
    92 nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
    93 nbfield_i=size(i1_series{1},2); %nb of fields for the i index
    94 nbfield=nbfield_j*nbfield_i; %total number of fields
    95 nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
    96 nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
    97 
    98 %determine the file type on each line from the first input file
    99 ImageTypeOptions={'image','multimage','mmreader','video'};
    100 NcTypeOptions={'netcdf','civx','civdata'};
    101 for iview=1:nbview
    102     if ~exist(filecell{iview,1}','file')
    103         displ_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
    104         return
    105     end
    106     [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
    107     CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
    108     CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
    109     if ~isempty(j1_series{iview})
    110         frame_index{iview}=j1_series{iview};
     68OutputDir=[Param.OutputSubDir Param.OutputDirExt];
     69
     70Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
     71Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
     72Data.Program='civ_series';
     73Data.CivStage=0;%default
     74ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
     75ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
     76mask='';
     77maskname='';%default
     78check_civx=0;%default
     79check_civ1=0;%default
     80check_patch1=0;%default
     81
     82% case of input Param set by an xml file (batch mode)
     83if ischar(Param)
     84    Param=xml2struct(Param); %if Param is the name of an xml file, read this file as a Matlab structure
     85end
     86
     87RootPath=Param.InputTable{1,1};
     88RootFile=Param.InputTable{1,3};
     89SubDir=Param.InputTable{1,2};
     90NomType=Param.InputTable{1,4};
     91FileExt=Param.InputTable{1,5};
     92PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
     93PairCiv2='';
     94if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
     95    PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;
     96end
     97
     98% option use with GUI series
     99NbField=1;
     100MovieObject_A=[];
     101if isfield(Param,'InputTable')
     102    MaxIndex=cell2mat(Param.IndexRange.MaxIndex);
     103    MinIndex=cell2mat(Param.IndexRange.MinIndex);
     104    [filecell,i_series,tild,j_series]=get_file_series(Param);
     105    [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
     106        find_pair_indices(PairCiv1,i_series{1},j_series{1},MinIndex,MaxIndex);
     107    if ~isempty(PairCiv2)
     108        [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
     109            find_pair_indices(PairCiv2,i_series{1},j_series{1},MinIndex,MaxIndex);
     110        check_bounds=check_bounds | check_bounds_Civ2;
     111    end
     112    i1_series_Civ1=i1_series_Civ1(~check_bounds);
     113    i2_series_Civ1=i2_series_Civ1(~check_bounds);
     114    j1_series_Civ1=j1_series_Civ1(~check_bounds);
     115    j2_series_Civ1=j2_series_Civ1(~check_bounds);
     116    if ~isempty(j1_series_Civ1)
     117        FrameIndex_A_Civ1=j1_series_Civ1;
     118        FrameIndex_B_Civ1=j2_series_Civ1;
    111119    else
    112         frame_index{iview}=i1_series{iview};
    113     end
    114 end
    115 
    116 
    117 %% calibration data and timing: read the ImaDoc files
    118 [XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
    119 if size(time,1)>1
    120     diff_time=max(max(diff(time)));
    121     if diff_time>0
    122         displ_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)],checkrun)
    123     end   
    124 end
    125 
    126 %% coordinate transform or other user defined transform
    127 
    128 %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
    129  % EDIT FROM HERE
    130 
    131 %% check the validity of  input file types
    132 if CheckImage{1}
    133     FileExtOut='.png'; % write result as .png images for image inputs
    134 elseif CheckNc{1}
    135     FileExtOut='.nc';% write result as .nc files for netcdf inputs
    136 else
    137     displ_uvmat('ERROR',['invalid file type input ' FileType{1}],checkrun)
    138     return
    139 end
    140 for iview=1:nbview
    141         if ~isequal(CheckImage{iview},CheckImage{1})||~isequal(CheckNc{iview},CheckNc{1})
    142         displ_uvmat('ERROR','input set of input series: need  either netcdf either image series',checkrun)
    143     return
    144     end
    145 end
    146 NomTypeOut=NomType;% output file index will indicate the first and last ref index in the series
    147 % if checkrun==1
    148 %     ParamOut.Specific=[];%no specific parameter
    149 %     return %stop here for interactive input (option Param.Specific='?')
    150 % end
    151 
    152 %% Set field names and velocity types
    153 %use Param.InputFields for all views
    154 
    155 %% MAIN LOOP ON SLICES
    156 %%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
    157 
    158 index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
    159 nbfiles=0;
    160 nbmissing=0;
    161 
    162 %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
    163 %TODO: call civ_matlab
    164 for index=index_slice
    165     if checkrun
    166         stopstate=get(Param.RUNHandle,'BusyAction');
    167         update_waitbar(Param.WaitbarHandle,index/nbfield)
    168     else
    169         stopstate='queue';
    170     end
    171     if ~isequal(stopstate,'queue')% enable STOP command
    172         return
    173     end
    174     %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
    175     Data=cell(1,nbview);%initiate the set Data
    176     nbtime=0;
    177     for iview=1:nbview
    178         %% reading input file(s)
    179         [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
    180         if ~isempty(errormsg)
    181             errormsg=['merge_proj/read_field/' errormsg];
    182             display(errormsg)
    183             break
    184         end
    185         timeread(iview)=0;
    186         if isfield(Data{iview},'Time')
    187             timeread(iview)=Data{iview}.Time;
    188             nbtime=nbtime+1;
    189         end
    190         if ~isempty(NbSlice_calib)
    191             Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
    192         end
     120        FrameIndex_A_Civ1=i1_series_Civ1;
     121        FrameIndex_B_Civ1=i2_series_Civ1;
     122    end
     123    if ~isempty(PairCiv2)
     124        i1_series_Civ2=i1_series_Civ2(~check_bounds);
     125        i2_series_Civ2=i2_series_Civ2(~check_bounds);
     126        j1_series_Civ2=j1_series_Civ2(~check_bounds);
     127        j2_series_Civ2=j2_series_Civ2(~check_bounds);
     128        if ~isempty(j1_series_Civ2)
     129            FrameIndex_A_Civ2=j1_series_Civ2;
     130            FrameIndex_B_Civ2=j2_series_Civ2;
     131        else
     132            FrameIndex_A_Civ2=i1_series_Civ2;
     133            FrameIndex_B_Civ2=i2_series_Civ2;
     134        end
     135    end
     136   
     137    NbField=numel(i1_series_Civ1);
     138    ImageTypeOptions={'image','multimage','mmreader','video'};
     139    [FileType_A,FileInfo,MovieObject_A]=get_file_type(filecell{1,1});
     140    FileType_B=FileType_A;
     141    MovieObject_B=MovieObject_A;
     142    if size(filecell,1)>=2 && ~strcmp(filecell{1,1},filecell{2,1})
     143        [FileType_B,FileInfo,MovieObject_B]=get_file_type(filecell{2,1});
     144        CheckImage_B=~isempty(find(strcmp(FileType,ImageTypeOptions)));% =1 for images
     145    end
     146end
     147
     148%%%%% MAIN LOOP %%%%%%
     149
     150MovieObject_A=[];
     151for ifield=1:NbField
     152   
     153    %% Civ1
     154    if isfield (Param.ActionInput,'Civ1')
     155        par_civ1=Param.ActionInput.Civ1;
     156        if isfield(par_civ1,'reverse_pair')% A REVOIR
     157            if par_civ1.reverse_pair
     158                if ischar(par_civ1.ImageB)
     159                    temp=par_civ1.ImageA;
     160                    par_civ1.ImageA=imread(par_civ1.ImageB);
     161                end
     162                if ischar(temp)
     163                    par_civ1.ImageB=imread(temp);
     164                end
     165            end
     166        else
     167            %         if ~isfield(Param.Civ1,'ImageA')
     168            ImageName_A=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
     169            [par_civ1.ImageA,MovieObject_A] = read_image(ImageName_A,FileType_A,MovieObject_A,FrameIndex_A_Civ1);
     170            %         elseif ischar(Param.Civ1.ImageA)
     171            %             Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'''','\');
     172            %             [par_civ1.ImageA,VideoObject] = read_image(Param.Civ1.ImageA,par_civ1.FileTypeA,MovieObject_A,par_civ1.FrameIndexA);
     173            %         end
     174            %         if ~isfield(Param.Civ1,'ImageB')
     175            ImageName_B=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
     176            [par_civ1.ImageB,MovieObject_B] = read_image(ImageName_B,FileType_B,MovieObject_B,FrameIndex_B_Civ1);
     177            %         elseif isfield(Param.Civ1,'ImageB')&& ischar(Param.Civ1.ImageB)
     178            %              Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'''','\');
     179            %              if strcmp(Param.Civ1.ImageA,Param.Civ1.ImageB)% use the same movie object
     180            %                  [par_civ1.ImageB,VideoObject] = read_image(Param.Civ1.ImageB,par_civ1.FileTypeB,VideoObject,par_civ1.FrameIndexB);
     181            %              else
     182            %             [par_civ1.ImageB,VideoObject] = read_image(Param.Civ1.ImageB,par_civ1.FileTypeB,par_civ1.ImageB,par_civ1.FrameIndexB);
     183            %              end
     184            %         end
     185        end
     186        ncfile=fullfile_uvmat(RootPath,OutputDir,RootFile,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
     187            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
     188        par_civ1.ImageWidth=FileInfo.Width;
     189        par_civ1.ImageHeight=FileInfo.Height;
     190        list_param=(fieldnames(Param.ActionInput.Civ1))';
     191        Civ1_param=list_param;%default
    193192       
    194         %% transform the input field (e.g; phys) if requested
    195         if ~isempty(transform_fct)
    196             if nargin(transform_fct)>=2
    197                 Data{iview}=transform_fct(Data{iview},XmlData{iview});
    198             else
    199                 Data{iview}=transform_fct(Data{iview});
     193        %set the values of all the global attributes in list_param
     194        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
     195        for ilist=1:length(list_param)
     196            Civ1_param{ilist}=['Civ1_' list_param{ilist}];
     197            Data.(['Civ1_' list_param{ilist}])=Param.ActionInput.Civ1.(list_param{ilist});
     198        end
     199        Data.CivStage=1;
     200       
     201        % set the list of variables
     202        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
     203        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
     204        Data.VarAttribute{1}.Role='coord_x';
     205        Data.VarAttribute{2}.Role='coord_y';
     206        Data.VarAttribute{3}.Role='vector_x';
     207        Data.VarAttribute{4}.Role='vector_y';
     208        Data.VarAttribute{5}.Role='warnflag';
     209       
     210        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
     211            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
     212            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
     213            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
     214            for ivol=1:NbSlice
     215                % caluclate velocity data (y and v in indices, reverse to y component)
     216                [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
     217                if ~isempty(errormsg)
     218                    return
     219                end
     220                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
     221                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
     222                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
     223                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
     224                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
     225                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
     226                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
    200227            end
    201         end
    202        
    203         %% check whether tps is needed, then calculate tps coefficients if needed
    204         check_tps=0;
    205         if isfield(Param.InputFields,'FieldName')
    206             if ischar(Param.InputFields.FieldName)
    207                 Param.InputFields.FieldName={Param.InputFields.FieldName};
    208             end
    209         else
    210             Param.InputFields.FieldName={};
    211         end
    212         for ilist=1:numel(Param.InputFields.FieldName)
    213             switch Param.InputFields.FieldName{ilist}
    214                 case {'vort','div','strain'}
    215                     check_tps=1;
    216             end
    217         end
    218        
    219         %% calculate tps coeff if needed
    220         check_proj_tps= ~isempty(Param.ProjObject)&& strcmp(Param.ProjObject.ProjMode,'filter')&&~isfield(Data{iview},'Coord_tps');
    221         Data{iview}=tps_coeff_field(Data{iview},check_proj_tps);
    222        
    223         %% projection on object (gridded plane)
    224         if Param.CheckObject
    225             [Data{iview},errormsg]=proj_field(Data{iview},Param.ProjObject);
     228        else %usual PIV
     229            % caluclate velocity data (y and v in indices, reverse to y component)
     230            [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
    226231            if ~isempty(errormsg)
    227                 displ_uvmat('ERROR',['error in merge_proge/proj_field: ' errormsg],checkrun)
    228232                return
    229233            end
    230         end
    231     end
    232     %----------END LOOP ON VIEWS----------------------
     234            Data.Civ1_X=reshape(xtable,[],1);
     235            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
     236            Data.Civ1_U=reshape(utable,[],1);
     237            Data.Civ1_V=reshape(-vtable,[],1);
     238            Data.Civ1_C=reshape(ctable,[],1);
     239            Data.Civ1_F=reshape(F,[],1);
     240        end
     241    else
     242        if exist('ncfile','var')
     243            CivFile=ncfile;
     244        elseif isfield(Param.Patch1,'CivFile')
     245            CivFile=Param.Patch1.CivFile;
     246        end
     247        Data=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
     248        if isfield(Data,'Txt')
     249            errormsg=Data.Txt;
     250            return
     251        end
     252        if ~isempty(Data.absolut_time_T0')%read civx file
     253            check_civx=1;% test for old civx data format
     254            [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
     255        else
     256            Data=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
     257        end
     258    end
    233259   
    234     %% merge the nbview fields
    235     MergeData=merge_field(Data);
    236     if isfield(MergeData,'Txt')
    237         displ_uvmat('ERROR',MergeData.Txt,checkrun)
     260    %% Fix1
     261    if isfield (Param.ActionInput,'Fix1')
     262        ListFixParam=fieldnames(Param.ActionInput.Fix1);
     263        for ilist=1:length(ListFixParam)
     264            ParamName=ListFixParam{ilist};
     265            ListName=['Fix1_' ParamName];
     266            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
     267            eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
     268        end
     269        if check_civx
     270            if ~isfield(Data,'fix')
     271                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
     272                Data.fix=1;
     273                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
     274                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
     275            end
     276            Data.vec_FixFlag=fix(Param.ActionInput.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
     277        else
     278            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
     279            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
     280            nbvar=length(Data.ListVarName);
     281            Data.VarAttribute{nbvar}.Role='errorflag';
     282            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
     283            Data.CivStage=2;
     284        end
     285    end
     286    %% Patch1
     287    if isfield (Param.ActionInput,'Patch1')
     288        if check_civx
     289            errormsg='Civ Matlab input needed for patch';
     290            return
     291        end
     292       
     293        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
     294        Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
     295        Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
     296        Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
     297        nbvar=length(Data.ListVarName);
     298        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
     299        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
     300            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
     301        Data.VarAttribute{nbvar+1}.Role='vector_x';
     302        Data.VarAttribute{nbvar+2}.Role='vector_y';
     303        Data.VarAttribute{nbvar+5}.Role='coord_tps';
     304        Data.VarAttribute{nbvar+6}.Role='vector_x';
     305        Data.VarAttribute{nbvar+7}.Role='vector_y';
     306        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
     307        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
     308        if isfield(Data,'Civ1_FF')
     309            ind_good=find(Data.Civ1_FF==0);
     310        else
     311            ind_good=1:numel(Data.Civ1_X);
     312        end
     313        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
     314            filter_tps([Data.Civ1_X(ind_good) Data.Civ1_Y(ind_good)],Data.Civ1_U(ind_good),Data.Civ1_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
     315        Data.Civ1_U_smooth(ind_good)=Ures;
     316        Data.Civ1_V_smooth(ind_good)=Vres;
     317        Data.Civ1_FF(ind_good)=FFres;
     318        Data.CivStage=3;
     319    end
     320   
     321    %% Civ2
     322    if isfield (Param.ActionInput,'Civ2')
     323        par_civ2=Param.ActionInput.Civ2;
     324        par_civ2.ImageA=[];
     325        par_civ2.ImageB=[];
     326        %         if ~isfield(Param.Civ1,'ImageA')
     327        ImageName_A_Civ2=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i1_series_Civ2(ifield),[],j1_series_Civ2(ifield));
     328
     329        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1,FrameIndex_A_Civ2)
     330            par_civ2.ImageA=par_civ1.ImageA;
     331        else
     332            [par_civ2.ImageA,MovieObject_A] = read_image(ImageName_A,FileType_A,MovieObject_A,FrameIndex_A_Civ2);
     333        end
     334        ImageName_B_Civ2=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i2_series_Civ2(ifield),[],j2_series_Civ2(ifield));
     335        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1,FrameIndex_B_Civ2)
     336            par_civ2.ImageB=par_civ1.ImageB;
     337        else
     338            [par_civ2.ImageB,MovieObject_B] = read_image(ImageName_B,FileType_B,MovieObject_B,FrameIndex_B_Civ2);
     339        end     
     340       
     341        ncfile=fullfile_uvmat(RootPath,OutputDir,RootFile,'.nc',NomTypeNc,i1_series_Civ2(ifield),i2_series_Civ2(ifield),...
     342            j1_series_Civ2(ifield),j2_series_Civ2(ifield));
     343        par_civ2.ImageWidth=FileInfo.Width;
     344        par_civ2.ImageHeight=FileInfo.Height;
     345       
     346        if isfield(par_civ2,'Grid')% grid points set as input file
     347            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
     348                par_civ2.Grid=dlmread(par_civ2.Grid);
     349                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
     350            end
     351        else% automatic grid
     352            minix=floor(par_civ2.Dx/2)-0.5;
     353            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
     354            miniy=floor(par_civ2.Dy/2)-0.5;
     355            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
     356            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
     357            par_civ2.Grid(:,1)=reshape(GridX,[],1);
     358            par_civ2.Grid(:,2)=reshape(GridY,[],1);
     359        end
     360        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
     361        Shifty=zeros(size(par_civ2.Grid,1),1);
     362        nbval=zeros(size(par_civ2.Grid,1),1);
     363        if par_civ2.CheckDeformation
     364            DUDX=zeros(size(par_civ2.Grid,1),1);
     365            DUDY=zeros(size(par_civ2.Grid,1),1);
     366            DVDX=zeros(size(par_civ2.Grid,1),1);
     367            DVDY=zeros(size(par_civ2.Grid,1),1);
     368        end
     369        NbSubDomain=size(Data.Civ1_SubRange,3);
     370        % get the guess from patch1
     371        for isub=1:NbSubDomain
     372            nbvec_sub=Data.Civ1_NbCentres(isub);
     373            ind_sel=find(GridX>=Data.Civ1_SubRange(1,1,isub) & GridX<=Data.Civ1_SubRange(1,2,isub) & GridY>=Data.Civ1_SubRange(2,1,isub) & GridY<=Data.Civ1_SubRange(2,2,isub));
     374            epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
     375            ctrs=Data.Civ1_Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
     376            nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
     377            EM = tps_eval(epoints,ctrs);
     378            Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
     379            Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
     380            if par_civ2.CheckDeformation
     381                [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
     382                DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
     383                DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
     384                DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
     385                DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
     386            end
     387        end
     388        mask='';
     389        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
     390            mask=imread(par_civ2.Mask);
     391        end
     392        ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
     393        iby2=ceil(par_civ2.CorrBoxSize(2)/2);
     394        %     isx2=ibx2+4;% search ara +-4 pixels around the guess
     395        %     isy2=iby2+4;
     396        par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
     397        par_civ2.SearchBoxSize(2)=2*iby2+9;
     398        %par_civ2.SearchBoxSize(1)=2*isx2+1;
     399        %par_civ2.SearchBoxSize(2)=2*isy2+1;
     400        par_civ2.SearchBoxShift=[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
     401        par_civ2.Grid=[GridX(nbval>=1)-par_civ2.SearchBoxShift(:,1)/2 GridY(nbval>=1)-par_civ2.SearchBoxShift(:,2)/2];% grid taken at the extrapolated origin of the displacement vectors
     402        if par_civ2.CheckDeformation
     403            par_civ2.DUDX=DUDX./nbval;
     404            par_civ2.DUDY=DUDY./nbval;
     405            par_civ2.DVDX=DVDX./nbval;
     406            par_civ2.DVDY=DVDY./nbval;
     407        end
     408        % caluclate velocity data (y and v in indices, reverse to y component)
     409        [xtable ytable utable vtable ctable F] = civ (par_civ2);
     410
     411        list_param=(fieldnames(Param.ActionInput.Civ2))';
     412        list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
     413        for ilist=1:length(list_remove)
     414            index=strcmp(list_remove{ilist},list_param);
     415            if ~isempty(find(index,1))
     416                list_param(index)=[];
     417            end
     418        end
     419        for ilist=1:length(list_param)
     420            Civ2_param{ilist}=['Civ2_' list_param{ilist}];
     421            eval(['Data.Civ2_' list_param{ilist} '=Param.ActionInput.Civ2.' list_param{ilist} ';'])
     422        end
     423        if isfield(Data,'Civ2_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
     424            Data.Civ1_gridname='';
     425        end
     426        if isfield(Data,'Civ2_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
     427            Data.Civ2_maskname='';
     428        end
     429        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param {'Civ2_Time','Civ2_Dt'}];
     430        nbvar=numel(Data.ListVarName);
     431        Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_F','Civ2_C'}];%  cell array containing the names of the fields to record
     432        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
     433        Data.VarAttribute{nbvar+1}.Role='coord_x';
     434        Data.VarAttribute{nbvar+2}.Role='coord_y';
     435        Data.VarAttribute{nbvar+3}.Role='vector_x';
     436        Data.VarAttribute{nbvar+4}.Role='vector_y';
     437        Data.VarAttribute{nbvar+5}.Role='warnflag';
     438        Data.Civ2_X=reshape(xtable,[],1);
     439        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
     440        Data.Civ2_U=reshape(utable,[],1);
     441        Data.Civ2_V=reshape(-vtable,[],1);
     442        Data.Civ2_C=reshape(ctable,[],1);
     443        Data.Civ2_F=reshape(F,[],1);
     444        Data.CivStage=Data.CivStage+1;
     445    end
     446   
     447    %% Fix2
     448    if isfield (Param.ActionInput,'Fix2')
     449        ListFixParam=fieldnames(Param.ActionInput.Fix2);
     450        for ilist=1:length(ListFixParam)
     451            ParamName=ListFixParam{ilist};
     452            ListName=['Fix2_' ParamName];
     453            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
     454            eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
     455        end
     456        if check_civx
     457            if ~isfield(Data,'fix2')
     458                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
     459                Data.fix2=1;
     460                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
     461                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
     462            end
     463            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
     464        else
     465            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
     466            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
     467            nbvar=length(Data.ListVarName);
     468            Data.VarAttribute{nbvar}.Role='errorflag';
     469            Data.Civ2_FF=fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
     470            Data.CivStage=Data.CivStage+1;
     471        end
     472       
     473    end
     474   
     475    %% Patch2
     476    if isfield (Param.ActionInput,'Patch2')
     477        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
     478        Data.Patch2_FieldSmooth=Param.ActionInput.Patch2.FieldSmooth;
     479        Data.Patch2_MaxDiff=Param.ActionInput.Patch2.MaxDiff;
     480        Data.Patch2_SubDomainSize=Param.ActionInput.Patch2.SubDomainSize;
     481        nbvar=length(Data.ListVarName);
     482        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
     483        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
     484            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
     485       
     486        Data.VarAttribute{nbvar+1}.Role='vector_x';
     487        Data.VarAttribute{nbvar+2}.Role='vector_y';
     488        Data.VarAttribute{nbvar+5}.Role='coord_tps';
     489        Data.VarAttribute{nbvar+6}.Role='vector_x';
     490        Data.VarAttribute{nbvar+7}.Role='vector_y';
     491        Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
     492        Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
     493        if isfield(Data,'Civ2_FF')
     494            ind_good=find(Data.Civ2_FF==0);
     495        else
     496            ind_good=1:numel(Data.Civ2_X);
     497        end
     498        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
     499            filter_tps([Data.Civ2_X(ind_good) Data.Civ2_Y(ind_good)],Data.Civ2_U(ind_good),Data.Civ2_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
     500        Data.Civ2_U_smooth(ind_good)=Ures;
     501        Data.Civ2_V_smooth(ind_good)=Vres;
     502        Data.Civ2_FF(ind_good)=FFres;
     503        Data.CivStage=Data.CivStage+1;
     504    end
     505   
     506    %% write result in a netcdf file if requested
     507    if exist('ncfile','var')
     508        errormsg=struct2nc(ncfile,Data);
     509        if isempty(errormsg)
     510            disp([ncfile ' written'])
     511        else
     512            disp(errormsg)
     513        end
     514    end
     515end
     516
     517% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
     518%--------------------------------------------------------------------------
     519% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
     520%
     521% OUTPUT:
     522% xtable: set of x coordinates
     523% ytable: set of y coordiantes
     524% utable: set of u displacements (along x)
     525% vtable: set of v displacements (along y)
     526% ctable: max image correlation for each vector
     527% typevector: set of flags, =1 for good, =0 for NaN vectors
     528%
     529%INPUT:
     530% par_civ: structure of input parameters, with fields:
     531%  .CorrBoxSize
     532%  .SearchBoxSize
     533%  .SearchBoxShift
     534%  .ImageHeight
     535%  .ImageWidth
     536%  .Dx, Dy
     537%  .Grid
     538%  .Mask
     539%  .MinIma
     540%  .MaxIma
     541%  .image1:first image (matrix)
     542% image2: second image (matrix)
     543% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
     544% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
     545% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
     546% step: mesh of the measurement points (in px)
     547% subpixfinder=1 or 2 controls the curve fitting of the image correlation
     548% mask: =[] for no mask
     549% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
     550function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
     551%this funtion performs the DCC PIV analysis. Recent window-deformation
     552%methods perform better and will maybe be implemented in the future.
     553
     554%% prepare measurement grid
     555if isfield(par_civ,'Grid')% grid points set as input
     556    if ischar(par_civ.Grid)%read the drid file if the input is a file name
     557        par_civ.Grid=dlmread(par_civ.Grid);
     558        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
     559    end
     560else% automatic grid
     561    minix=floor(par_civ.Dx/2)-0.5;
     562    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
     563    miniy=floor(par_civ.Dy/2)-0.5;
     564    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
     565    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
     566    par_civ.Grid(:,1)=reshape(GridX,[],1);
     567    par_civ.Grid(:,2)=reshape(GridY,[],1);
     568end
     569nbvec=size(par_civ.Grid,1);
     570
     571%% prepare correlation and search boxes
     572ibx2=ceil(par_civ.CorrBoxSize(1)/2);
     573iby2=ceil(par_civ.CorrBoxSize(2)/2);
     574isx2=ceil(par_civ.SearchBoxSize(1)/2);
     575isy2=ceil(par_civ.SearchBoxSize(2)/2);
     576shiftx=round(par_civ.SearchBoxShift(:,1));
     577shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
     578if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
     579    shiftx=shiftx*ones(nbvec,1);
     580    shifty=shifty*ones(nbvec,1);
     581end
     582
     583%% Default output
     584xtable=par_civ.Grid(:,1);
     585ytable=par_civ.Grid(:,2);
     586utable=zeros(nbvec,1);
     587vtable=zeros(nbvec,1);
     588ctable=zeros(nbvec,1);
     589F=zeros(nbvec,1);
     590result_conv=[];
     591errormsg='';
     592
     593%% prepare mask
     594if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
     595    if strcmp(par_civ.Mask,'all')
     596        return    % get the grid only, no civ calculation
     597    elseif ischar(par_civ.Mask)
     598        par_civ.Mask=imread(par_civ.Mask);
     599    end
     600end
     601check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
     602check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
     603
     604% %% prepare images
     605% if isfield(par_civ,'reverse_pair')
     606%     if par_civ.reverse_pair
     607%         if ischar(par_civ.ImageB)
     608%             temp=par_civ.ImageA;
     609%             par_civ.ImageA=imread(par_civ.ImageB);
     610%         end
     611%         if ischar(temp)
     612%             par_civ.ImageB=imread(temp);
     613%         end
     614%     end
     615% else
     616%     if ischar(par_civ.ImageA)
     617%         par_civ.ImageA=imread(par_civ.ImageA);
     618%     end
     619%     if ischar(par_civ.ImageB)
     620%         par_civ.ImageB=imread(par_civ.ImageB);
     621%     end
     622% end
     623par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
     624par_civ.ImageB=sum(double(par_civ.ImageB),3);
     625[npy_ima npx_ima]=size(par_civ.ImageA);
     626if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
     627    errormsg='image pair with unequal size';
     628    return
     629end
     630
     631%% Apply mask
     632    % Convention for mask IDEAS TO IMPLEMENT ?
     633    % mask >200 : velocity calculated
     634    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
     635    % 150>=mask >100: velocity not calculated, nor interpolated
     636    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
     637    %  20>=mask: velocity=0
     638checkmask=0;
     639MinA=min(min(par_civ.ImageA));
     640MinB=min(min(par_civ.ImageB));
     641if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
     642   checkmask=1;
     643   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
     644        errormsg='mask must be an image with the same size as the images';
    238645        return
    239     end
     646   end
     647  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
     648    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
     649    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
     650    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
     651end
     652
     653%% compute image correlations: MAINLOOP on velocity vectors
     654corrmax=0;
     655sum_square=1;% default
     656mesh=1;% default
     657CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
     658if CheckDecimal
     659    mesh=0.2;%mesh in pixels for subpixel image interpolation
     660    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
     661end
     662% vector=[0 0];%default
     663for ivec=1:nbvec
     664    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
     665    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
     666    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
     667    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
     668    %               jref+shifty(ivec)-isy2<1||jref+shifty(ivec)+isy2>par_civ.ImageHeight|| iref+shiftx(ivec)-isx2<1 || iref+shiftx(ivec)+isx2>par_civ.ImageWidth  % we are outside the image
     669    %             F(ivec)=3;
     670    %         else
     671    F(ivec)=0;
     672    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
     673    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
     674    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
     675    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
     676    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
     677    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
     678    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
     679    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
     680    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
     681    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
    240682   
    241     % time of the merged field:
    242     if ~isempty(time)% time defined from ImaDoc
    243         timeread=time(:,index);
    244     end
    245     timeread=mean(timeread);
    246    
    247     % generating the name of the merged field
    248     i1=i1_series{iview}(index);
    249     if ~isempty(i2_series{iview})
    250         i2=i2_series{iview}(index);
     683    image1_crop(check1_y,check1_x)=par_civ.ImageA(subrange1_y(check1_y),subrange1_x(check1_x));%extract a subimage (correlation box) from image A
     684    image2_crop(check2_y,check2_x)=par_civ.ImageB(subrange2_y(check2_y),subrange2_x(check2_x));%extract a larger subimage (search box) from image B
     685    image1_mean=mean(mean(image1_crop));
     686    image2_mean=mean(mean(image2_crop));
     687    %threshold on image minimum
     688    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
     689        F(ivec)=3;
     690    end
     691    %threshold on image maximum
     692    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
     693        F(ivec)=3;
     694    end
     695    %         end
     696    if F(ivec)~=3
     697        image1_crop=image1_crop-image1_mean;%substract the mean
     698        image2_crop=image2_crop-image2_mean;
     699        if CheckDecimal
     700            xi=(1:mesh:size(image1_crop,2));
     701            yi=(1:mesh:size(image1_crop,1))';
     702            if CheckDeformation
     703                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
     704                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
     705                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
     706                image1_crop=interp2(image1_crop,XIant,YIant);
     707            else
     708                image1_crop=interp2(image1_crop,xi,yi);
     709            end
     710            xi=(1:mesh:size(image2_crop,2));
     711            yi=(1:mesh:size(image2_crop,1))';
     712            image2_crop=interp2(image2_crop,xi,yi);
     713        end
     714        sum_square=sum(sum(image1_crop.*image1_crop));
     715        %reference: Oliver Pust, PIV: Direct Cross-Correlation
     716        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
     717        corrmax= max(max(result_conv));
     718        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
     719        %Find the correlation max, at 255
     720        [y,x] = find(result_conv==255,1);
     721        if ~isempty(y) && ~isempty(x)
     722            try
     723                if par_civ.CorrSmooth==1
     724                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
     725                elseif par_civ.CorrSmooth==2
     726                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
     727                end
     728                utable(ivec)=vector(1)*mesh+shiftx(ivec);
     729                vtable(ivec)=vector(2)*mesh+shifty(ivec);
     730                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
     731                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
     732                iref=round(xtable(ivec));% image index for the middle of the vector
     733                jref=round(ytable(ivec));
     734                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
     735                    utable(ivec)=0;
     736                    vtable(ivec)=0;
     737                    F(ivec)=3;
     738                end
     739                ctable(ivec)=corrmax/sum_square;% correlation value
     740            catch ME
     741                F(ivec)=3;
     742            end
     743        else
     744            F(ivec)=3;
     745        end
     746    end
     747end
     748result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
     749
     750%------------------------------------------------------------------------
     751% --- Find the maximum of the correlation function after interpolation
     752function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
     753%------------------------------------------------------------------------
     754vector=[0 0]; %default
     755F=0;
     756[npy,npx]=size(result_conv);
     757
     758% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
     759    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
     760    %http://urapiv.wordpress.com
     761    peaky = y;
     762    if y <= npy-1 && y >= 1
     763        f0 = log(result_conv(y,x));
     764        f1 = real(log(result_conv(y-1,x)));
     765        f2 = real(log(result_conv(y+1,x)));
     766        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
    251767    else
    252         i2=i1;
    253     end
    254     j1=1;
    255     j2=1;
    256     if ~isempty(j1_series{iview})
    257         j1=j1_series{iview}(index);
    258         if ~isempty(j2_series{iview})
    259             j2=j2_series{iview}(index);
    260         else
    261             j2=j1;
    262         end
    263     end
    264     OutputFile=fullfile_uvmat(RootPath{1},OutputSubDir,RootFile{1},FileExtOut,NomType{1},i1,i2,j1,j2);
    265    
    266     % recording the merged field
    267     if CheckImage{1}    %in case of input images an image is produced
    268         if isa(MergeData.A,'uint8')
    269             bitdepth=8;
    270         elseif isa(MergeData.A,'uint16')
    271             bitdepth=16;
    272         end
    273         imwrite(MergeData.A,OutputFile,'BitDepth',bitdepth);
    274         %write xml calibration file
    275         siz=size(MergeData.A);
    276         npy=siz(1);
    277         npx=siz(2);
    278         if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
    279             Rangx=MergeData.VarAttribute{1}.Coord_2;
    280             Rangy=MergeData.VarAttribute{1}.Coord_1;
    281         elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
    282             Rangx=[MergeData.AX(1) MergeData.AX(end)];
    283             Rangy=[MergeData.AY(1) MergeData.AY(end)];
    284         else
    285             Rangx=[0.5 npx-0.5];
    286             Rangy=[npy-0.5 0.5];%default
    287         end
    288         pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
    289         pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
    290         T_x=-pxcmx*Rangx(1)+0.5;
    291         T_y=-pxcmy*Rangy(2)+0.5;
    292         GeometryCal.focal=1;
    293         GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
    294         GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
    295         ImaDoc.GeometryCalib=GeometryCal;
    296         %             t=struct2xml(ImaDoc);
    297         %             t=set(t,1,'name','ImaDoc');
    298         %             save(t,[filebase_merge '.xml'])
    299         %             display([filebase_merge '.xml saved'])
     768        F=-2; % warning flag for vector truncated by the limited search box
     769    end
     770    peakx=x;
     771    if x <= npx-1 && x >= 1
     772        f0 = log(result_conv(y,x));
     773        f1 = real(log(result_conv(y,x-1)));
     774        f2 = real(log(result_conv(y,x+1)));
     775        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
    300776    else
    301         MergeData.ListGlobalAttribute={'Conventions','Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};
    302         MergeData.Conventions='uvmat';
    303         MergeData.nb_coord=2;
    304         MergeData.nb_dim=2;
    305         dt=[];
    306         if isfield(Data{1},'dt')&& isnumeric(Data{1}.dt)
    307             dt=Data{1}.dt;
    308         end
    309         for iview =2:numel(Data)
    310             if ~(isfield(Data{iview},'dt')&& isequal(Data{iview}.dt,dt))
    311                 dt=[];%dt not the same for all fields
    312             end
    313         end
    314         if isempty(dt)
    315             MergeData.ListGlobalAttribute(6)=[];
    316         else
    317             MergeData.dt=dt;
    318         end
    319         MergeData.Time=timeread;
    320         error=struct2nc(OutputFile,MergeData);%save result file
    321         if isempty(error)
    322             display(['output file ' OutputFile ' written'])
    323         else
    324             display(error)
    325         end
    326     end
    327 end
    328 
    329 %'merge_field': concatene fields
     777        F=-2; % warning flag for vector truncated by the limited search box
     778    end
     779    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
     780
    330781%------------------------------------------------------------------------
    331 function MergeData=merge_field(Data)
    332 %% default output
    333 if isempty(Data)||~iscell(Data)
    334     MergeData=[];
    335     return
    336 end
    337 MergeData=Data{1};%default
    338 error=0;
    339 nbview=length(Data);
    340 if nbview==1
    341     return
    342 end
    343 
    344 %% group the variables (fields of 'Data') in cells of variables with the same dimensions
    345 [CellVarIndex,NbDim,VarTypeCell]=find_field_cells(Data{1});
    346 %LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
    347 % CellVarIndex=cells of variable index arrays
    348 for icell=1:length(CellVarIndex)
    349     if NbDim(icell)==1
    350         continue
    351     end
    352     VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
    353     VarType=VarTypeCell{icell};
    354     ivar_X=VarType.coord_x;
    355     ivar_Y=VarType.coord_y;
    356     ivar_FF=VarType.errorflag;
    357     if isempty(ivar_X)
    358         test_grid=1;%test for input data on regular grid (e.g. image)coordinates
     782% --- Find the maximum of the correlation function after interpolation
     783function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
     784%------------------------------------------------------------------------
     785vector=[0 0]; %default
     786F=-2;
     787peaky=y;
     788peakx=x;
     789[npy,npx]=size(result_conv);
     790if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
     791    F=0;
     792    for i=-1:1
     793        for j=-1:1
     794            %following 15 lines based on
     795            %H. Nobach ï¿œ M. Honkanen (2005)
     796            %Two-dimensional Gaussian regression for sub-pixel displacement
     797            %estimation in particle image velocimetry or particle position
     798            %estimation in particle tracking velocimetry
     799            %Experiments in Fluids (2005) 38: 511ï¿œ515
     800            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
     801            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
     802            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
     803            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
     804            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
     805        end
     806    end
     807    c10=(1/6)*sum(sum(c10));
     808    c01=(1/6)*sum(sum(c01));
     809    c11=(1/4)*sum(sum(c11));
     810    c20=(1/6)*sum(sum(c20));
     811    c02=(1/6)*sum(sum(c02));
     812    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
     813    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
     814    if abs(deltax)<1
     815        peakx=x+deltax;
     816    end
     817    if abs(deltay)<1
     818        peaky=y+deltay;
     819    end
     820end
     821vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
     822
     823%'RUN_FIX': function for fixing velocity fields:
     824%-----------------------------------------------
     825% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
     826%
     827%filename: name of the netcdf file (used as input and output)
     828%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
     829    %.vel_type='civ1' or 'civ2';
     830    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
     831    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
     832%flagindex: flag specifying which values of vec_f are removed:
     833        % if flagindex(1)=1: vec_f=-2 vectors are removed
     834        % if flagindex(2)=1: vec_f=3 vectors are removed
     835        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
     836%iter=1 for civ1 fields and iter=2 for civ2 fields
     837%thresh_vecC: threshold in the image correlation vec_C
     838%flag_mask: =1 mask used to remove vectors (0 else)
     839%maskname: name of the mask image file for fix
     840%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
     841%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
     842%fileref: .nc file name for a reference velocity (='': refrence 0 used)
     843%fieldref: 'civ1','filter1'...feld used in fileref
     844
     845function FF=fix(Param,F,C,U,V,X,Y)
     846FF=zeros(size(F));%default
     847
     848%criterium on warn flags
     849FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
     850FlagVal=[-2 2 3 4];
     851for iflag=1:numel(FlagName)
     852    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
     853        FF=(FF==1| F==FlagVal(iflag));
     854    end
     855end
     856%criterium on correlation values
     857if isfield (Param,'MinCorr')
     858    FF=FF==1 | C<Param.MinCorr;
     859end
     860if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
     861    Umod= U.*U+V.*V;
     862    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
     863        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
     864    end
     865    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
     866        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
     867    end
     868end
     869
     870
     871%------------------------------------------------------------------------
     872% --- determine the list of index pairs of processing file
     873function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
     874    find_pair_indices(str_civ,i_series,j_series,MinIndex,MaxIndex)
     875%------------------------------------------------------------------------
     876i1_series=i_series;% set of first image numbers
     877i2_series=i_series;
     878j1_series=ones(size(i_series));% set of first image numbers
     879j2_series=ones(size(i_series));
     880check_bounds=false(size(i_series));
     881r=regexp(str_civ,'^\D(?<ind>[i|j])= (?<num1>\d+)\|(?<num2>\d+)','names');
     882if ~isempty(r)
     883    mode=['D' r.ind];
     884    ind1=str2num(r.num1);
     885    ind2=str2num(r.num2);
     886else
     887    mode='burst';
     888    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
     889    if ~isempty(r)
     890        NomTypeNc='_1ab';
    359891    else
    360         if length(ivar_Y)~=1
    361                 displ_uvmat('ERROR','y coordinate missing in proj_field.m',checkrun)
    362                 return
    363         end
    364         test_grid=0;
    365     end
    366     %case of input fields with unstructured coordinates
    367     if ~test_grid
    368         for ivar=VarIndex
    369             VarName=MergeData.ListVarName{ivar};
    370             for iview=1:nbview
    371                 MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
    372             end
    373         end
    374     %case of fields defined on a structured  grid
    375     else 
    376         testFF=0;
    377         for iview=2:nbview
    378             for ivar=VarIndex
    379                 VarName=MergeData.ListVarName{ivar};
    380                 if isfield(MergeData,'VarAttribute')
    381                     if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
    382                         testFF=1;
    383                     end
    384                 end
    385                 MergeData.(VarName)=MergeData.(VarName) + Data{iview}.(VarName);
    386             end
    387         end
    388         if testFF
    389             nbaver=nbview-MergeData.FF;
    390             indgood=find(nbaver>0);
    391             for ivar=VarIndex
    392                 VarName=MergeData.ListVarName{ivar};
    393                 MergeData.(VarName)(indgood)=double(MergeData.(VarName)(indgood))./nbaver(indgood);
    394             end
    395         else
    396             for ivar=VarIndex
    397                 VarName=MergeData.ListVarName{ivar};
    398                 MergeData.(VarName)=double(MergeData.(VarName))./nbview;
    399             end   
    400         end
    401     end
    402 end
    403 
    404    
     892        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
     893        if ~isempty(r)
     894            NomTypeNc='_1AB';
     895        else
     896            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
     897            if ~isempty(r)
     898                NomTypeNc='_1_1-2';
     899            end           
     900        end
     901    end
     902    if isempty(r)
     903        display('wrong pair mode input option')
     904    else
     905    ind1=stra2num(r.num1);
     906    ind2=stra2num(r.num2);
     907    end
     908end
     909if strcmp (mode,'Di')
     910    i1_series=i_series-ind1;% set of first image numbers
     911    i2_series=i_series+ind2;
     912    check_bounds=i1_series<MinIndex(1,1) | i2_series>MaxIndex(1,1);
     913    if isempty(j_series)
     914        NomTypeNc='_1-2';
     915    else
     916        NomTypeNc='_1-2_1';
     917    end
     918elseif strcmp (mode,'Dj')
     919    j1_series=j_series-ind1;
     920    j2_series=j_series+ind2;
     921    check_bounds=j1_series<MinIndex(1,2) | j2_series>MaxIndex(1,2);
     922    NomTypeNc='_1_1-2';
     923else  %bursts
     924    j1_series=ind1*ones(size(i_series));
     925    j2_series=ind2*ones(size(i_series));
     926end
     927
     928%     if length(indsel)>=1
     929%         firstind=indsel(1);
     930%         lastind=indsel(end);
     931%         set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
     932%         set(handles.last_j,'String',num2str(ref_j(lastind)))
     933%         ref_j=ref_j(indsel);
     934%         j1_civ1=j1_civ1(indsel);
     935%         j2_civ1=j2_civ1(indsel);
     936%         j1_civ2=j1_civ2(indsel);
     937%         j2_civ2=j2_civ2(indsel);
     938%     end
     939% elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
     940%     displ_num=get(handles.ListPairCiv1,'UserData');
     941%     i1_civ1=ref_i;
     942%     i2_civ1=ref_i;
     943%     j1_civ1=displ_num(1,index_civ1);
     944%     j2_civ1=displ_num(2,index_civ1);
     945%     i1_civ2=ref_i;
     946%     i2_civ2=ref_i;
     947%     j1_civ2=displ_num(1,index_civ2);
     948%     j2_civ2=displ_num(2,index_civ2);
     949% elseif isequal(mode,'displacement')
     950%     i1_civ1=ref_i;
     951%     i2_civ1=ref_i;
     952%     j1_civ1=ref_j;
     953%     j2_civ1=ref_j;
     954%     i1_civ2=ref_i;
     955%     i2_civ2=ref_i;
     956%     j1_civ2=ref_j;
     957%     j2_civ2=ref_j;
     958% end
     959
     960
     961
     962
Note: See TracChangeset for help on using the changeset viewer.