source: trunk/src/series/aver_stat.m @ 237

Last change on this file since 237 was 218, checked in by sommeria, 14 years ago

write data in a new directory .0 if the selected output directory exists

File size: 20.2 KB
RevLine 
[169]1%'aver_stat': calculate field average, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=aver_stat(num_i1,num_i2,num_j1,num_j2,Series)
4%
5%OUTPUT
6% GUI_input=list of options in the GUI series.fig needed for the function
7%
8%INPUT:
9%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
10%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
11%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
12%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
13%Series: Matlab structure containing information set by the series interface
14%
[27]15function GUI_input=aver_stat(num_i1,num_i2,num_j1,num_j2,Series)
16%----------------------------------------------------------------------
17% --- make average on a series of files
18%----------------------------------------------------------------------
19%INPUT:
20%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
21%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
22%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
23%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
24%OTHER INPUTS given by the structure Series
25%  Series.Time:
26%  Series.GeometryCalib:%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
27if ~exist('num_i1','var')
28    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
29        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
30        'RootFile';'on';... %root input file name ('on' by default)
31        'FileExt';'on';... %input file extension ('on' by default)
32        'NomType';'on';...%type of file indexing ('on' by default)
33        'NbSlice';'on'; ...%nbre of slices ('off' by default)
34        'VelTypeMenu';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
35        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
36        'CoordType'; 'on';...%can use a transform function
37        'GetObject';'on';...%can use projection object(option 'off'/'one'/'two',
38        %'GetMask';'on'...%can use mask option   
39        %'PARAMETER'; %options: name of the user defined parameter',repeat a line for each parameter
40               ''};
41        return
42end
43
44%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
45hseries=guidata(Series.hseries);%handles of the GUI series
46WaitbarPos=get(hseries.waitbar_frame,'Position');
47%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[41]48
49%projection object
50test_object=get(hseries.GetObject,'Value');
51if test_object%isfield(Series,'sethandles')
[76]52    hset_object=findobj(allchild(0),'tag','set_object');
[41]53    ProjObject=read_set_object(guidata(hset_object));
54    %answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
55    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' ProjObject.Style ' before averaging']);
56    if ~isequal(answeryes,'Yes')
57        return
58    end
59end
60
[27]61%root input file and type
62if ~iscell(Series.RootPath)% case of a single input field series
63    num_i1={num_i1};num_j1={num_j1};num_i2={num_i2};num_j2={num_j2};
64    RootPath={Series.RootPath};
65    RootFile={Series.RootFile};
66    SubDir={Series.SubDir};
67    FileExt={Series.FileExt};
68    NomType={Series.NomType};
69else
70    RootPath=Series.RootPath;
71    RootFile=Series.RootFile;
72    SubDir=Series.SubDir;
73    NomType=Series.NomType;
74    FileExt=Series.FileExt;
75end   
76ext=FileExt{1};
77form=imformats(ext([2:end]));%test valid Matlab image formats
78testima=0;
79if ~isempty(form)||isequal(lower(ext),'.avi')||isequal(lower(ext),'.vol')
80    testima(1)=1;
81end
82if length(FileExt)>=2
83    ext_1=FileExt{2};
84    form=imformats(ext_1([2:end]));%test valid Matlab image formats
85    if ~isempty(form)||isequal(lower(ext_1),'.avi')||isequal(lower(ext_1),'.vol')
86        testima(2)=1;
87    end
88    if testima(2)~=testima(1)
89        msgbox_uvmat('ERROR','images and netcdf files cannot be compared')
90        return
91    end
92end
93
94%Number of input series: this function  accepts two input file series at most (then it operates on the difference of fields)
95nbview=length(RootPath);
96if nbview>2 
97    RootPath=RootPath(1:2);
98    set(hseries.RootPath,'String',RootPath)
99    SubDir=SubDir(1:2);
100    set(hseries.SubDir,'String',SubDir)
101    RootFile=RootFile(1:2);
102    set(hseries.RootFile,'String',RootFile)
103    NomType=NomType(1:2);
104    FileExt=FileExt(1:2);
105    set(hseries.FileExt,'String',FileExt)
106    nbview=2;
107end
[43]108
109%determine image type
[27]110hhh=which('mmreader');
111for iview=1:nbview
[43]112    if isequal(FileExt{iview},'.nc')||isequal(FileExt{iview},'.cdf')
113        FileType{iview}='netcdf';
114    elseif isequal(lower(FileExt{iview}),'.avi')
115        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
[27]116            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
[43]117            FileType{iview}='movie';
118        else
119            FileType{iview}='avi';
[27]120        end
[43]121    elseif isequal(lower(FileExt{iview}),'.vol')
122        FileType{iview}='vol';
123    else
124       form=imformats(FileExt{iview}(2:end));
125       if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
126           if isequal(NomType{iview},'*');
127               FileType{iview}='multimage';
128           else
129               FileType{iview}='image';
130           end
131       end
132    end
[27]133end
134
135% number of slices
136NbSlice=str2num(get(hseries.NbSlice,'String'));
137if isempty(NbSlice)
138    NbSlice=1;
139end
140NbSlice_name=num2str(NbSlice);
141
142% Field and velocity type (the same for the two views)
143Field_str=get(hseries.FieldMenu,'String');
144FieldName=[]; %default
145testfield=get(hseries.FieldMenu,'Visible');
146if isequal(testfield,'on')
147    val=get(hseries.FieldMenu,'Value');
148    FieldName=Field_str(val);%the same set of fields for all views
149    if isequal(FieldName,{'get_field...'})
150        hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
151        if length(hget_field)>1
152            delete(hget_field(2:end))
153        elseif isempty(hget_field)
154           filename=...
155                 name_generator(fullfile(RootPath{1},RootFile{1}),num_i1{1}(1),num_j1{1}(1),FileExt{1},NomType{1},1,num_i2{1}(1),num_j2{1}(1),SubDir{1});
156           get_field(filename);
157           return
158        end
159        %hhget_field=guidata(hget_field);%handles of GUI elements in get_field
160        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
161    end
162end
163%detect whether the two files are 'images' or 'netcdf'
[43]164% testima=0;
165% testvol=0;
[27]166testcivx=0;
[43]167% testnc=0;
[27]168FileExt=get(hseries.FileExt,'String');
169% test_movie=0;
[43]170% for iview=1:nbview
171%      ext=FileExt{iview};
172%      form=imformats(ext([2:end]));
173%      if isequal(lower(ext),'.vol')
174%          testvol=testvol+1;
175%      elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
176%          testima=testima+1;
177%      elseif isequal(ext,'.nc')
178%          testnc=testnc+1;
179%      end
180% end
181% if testvol
182%     msgbox_uvmat('ERROR','volume images not implemented yet')
183%     return
184% end
185% if testnc~=nbview && testima~=nbview && testvol~=nbview
186%     msgbox_uvmat('ERROR','compare two image series or two netcdf files with the same fields as input')
187%     return
188% end
[27]189if ~isequal(FieldName,{'get_field...'})
[43]190    testcivx=isequal(FileType{1},'netcdf');
[27]191end
[43]192% if ~isequal(FieldName,{'get_field...'})
193%     if isequal(FieldName,{''}) && ~testima
194%         msgbox_uvmat('ERROR','an input field needs to be selected')
195%         return
196%     end
197%     testcivx=testnc;
198% end
[27]199
200if testcivx
201    VelType_str=get(hseries.VelTypeMenu,'String');
202    VelType_val=get(hseries.VelTypeMenu,'Value');
203    VelType{1}=VelType_str{VelType_val};
204    if nbview==2
205        VelType_str=get(hseries.VelTypeMenu_1,'String');
206        VelType_val=get(hseries.VelTypeMenu_1,'Value');
207        VelType{2}=VelType_str{VelType_val};
208    end
209end
210
211%Calibration data and timing: read the ImaDoc files
212mode=''; %default
213timecell={};
214itime=0;
215NbSlice_calib={};
216for iview=1:nbview%Loop on views
217    XmlData{iview}=[];%default
218    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
219    if exist([filebase{iview} '.xml'],'file')
220        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
221        if isfield(XmlData{iview},'Time')
222            itime=itime+1;
223            timecell{itime}=XmlData{iview}.Time;
224        end
225        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
226            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
227            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
228                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
229            end
230        end
231    elseif exist([filebase{iview} '.civ'],'file')
232        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
233        itime=itime+1;
234        timecell{itime}=time;
235        XmlData{iview}.Time=time;
236        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
237        GeometryCalib.Tx=0;
238        GeometryCalib.Ty=0;
239        GeometryCalib.Tz=1;
240        GeometryCalib.dpx=1;
241        GeometryCalib.dpy=1;
242        GeometryCalib.sx=1;
243        GeometryCalib.Cx=0;
244        GeometryCalib.Cy=0;
245        GeometryCalib.f=1;
246        GeometryCalib.kappa1=0;
247        GeometryCalib.CoordUnit='cm';
248        XmlData{iview}.GeometryCalib=GeometryCalib;
249        if error==1
250            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
251        end
252    end
253end
254
255%check coincidence in time
256multitime=0;
[55]257if isempty(timecell)
[27]258    time=[];
259elseif length(timecell)==1
260    time=timecell{1};
261elseif length(timecell)>1
262    multitime=1;
263    for icell=1:length(timecell)
264        if ~isequal(size(timecell{icell}),size(timecell{1}))
265            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
266            time=timecell{1};
267            multitime=0;
268            break
269        end
270    end
271end
272if multitime
273    for icell=1:length(timecell)
274        time(icell,:,:)=timecell{icell};
275    end
276    diff_time=max(max(diff(time)));
277    if diff_time>0
278        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
279    end   
280end
281if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
282    time=[];
283end
284
[218]285%% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
[29]286subdir_result='aver_stat';
[218]287pathdir=fullfile(RootPath{1},subdir_result);
288while exist(pathdir,'dir')
289    subdir_result=[subdir_result '.0'];
290    pathdir=fullfile(RootPath{1},subdir_result);
[27]291end
[218]292[m1,m2,m3]=mkdir(pathdir);
293if ~isequal(m2,'')
294     msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
295end
296[xx,msg2] = fileattrib(pathdir,'+w','g'); %yield writing access (+w) to user group (g)
297if ~strcmp(msg2,'')
298    msgbox_uvmat('ERROR',['pb of permission for ' pathdir ': ' msg2])%error message for directory creation
299    return
300end
[29]301filebase_out=filebase{1};
[27]302NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
303
304% coordinate transform or other user defined transform
[41]305transform_fct=[];%default
306if isfield(Series,'transform_fct')
307    transform_fct=Series.transform_fct;
308end
[27]309
[218]310%% slice loop
[27]311siz=size(num_i1{1});
312lengthtot=siz(1)*siz(2);
313nbfield=floor(lengthtot/(siz(1)*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
314nbfield_slice=nbfield*siz(1);% number of fields per slice
315
316for i_slice=1:NbSlice
317   S=0; %initiate the image sum S
318   nbfiles=0;
319   nbmissing=0;
320    %averaging loop
321   for ifile=i_slice:NbSlice:lengthtot
322        stopstate=get(hseries.RUN,'BusyAction');
323        if isequal(stopstate,'queue') % enable STOP command
324             update_waitbar(hseries.waitbar,WaitbarPos,ifile/lengthtot)
325             for iview=1:nbview
326                [filename]=...
327                           name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),FileExt{iview},NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile),SubDir{iview});
[43]328                if ~isequal(FileType{iview},'netcdf')               
[27]329                    Data{iview}.ListVarName={'A'};
330                    Data{iview}.AName='image';
[43]331                    switch FileType{iview}
332                        case 'movie'
333                            A=read(MovieObject{iview},num_i1{iview}(ifile));
334                        case 'avi'
335                            mov=aviread(filename,num_i1{iview}(ifile));
336                            A=frame2im(mov(1));
337                        case 'vol'
338                            A=imread(filename);
339                        case 'multimage'
340                            A=imread(filename,num_i1{iview}(ifile));
341                        case 'image'
342                            A=imread(filename);
343                    end
[107]344                    Data{iview}.ListVarName={'AY','AX','A'}; %
[43]345                    Atype{iview}=class(A);
346                    npy=size(A,1);
347                    npx=size(A,2);
348                    nbcolor=size(A,3);
349                    if nbcolor==3
[107]350                         Data{iview}.VarDimName={'AY','AX',{'AY','AX','rgb'}};
[27]351                    else
[107]352                         Data{iview}.VarDimName={'AY','AX',{'AY','AX'}};
[43]353                    end 
[107]354                    Data{iview}.AY=[npy-0.5 0.5];
355                    Data{iview}.AX=[0.5 npx-0.5];
[43]356                    Data{iview}.A=double(A);
[158]357                    Data{iview}.CoordUnit='pixel';
[27]358                elseif testcivx
359                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
360                else
361                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
362                    Data{iview}.VarAttribute=SubField.VarAttribute;
363                end
364                if isfield(Data{iview},'Txt')
365                    msgbox_uvmat('ERROR',['error of input reading: ' Data{iview}.Txt])
366                    return
367                end
368             end   
[190]369
[27]370             % coordinate transform (or other user defined transform)
[41]371             if ~isempty(transform_fct)
[27]372                 % z index
373                if ~isempty(NbSlice_calib)
374                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;%Zindex for phys transform
375                end
376                if nbview==2
[41]377                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
[27]378                    if isempty(Data{2})
379                        Data(2)=[];
380                    end
381                else
[80]382                    Data{1}=transform_fct(Data{1},XmlData{1});
[27]383                end
384             end     
385            if testcivx
386                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
387            end
388            if length(Data)==2
389                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
390                if ~isempty(errormsg)
391                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
392                    return
393                end
394            else
395                Field=Data{1};
396            end
[41]397            if test_object
398                [Field,errormsg]=proj_field(Field,ProjObject);
[27]399                 if ~isempty(errormsg)
400                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
401                    return
402                end
403             end                                                       
404                nbfiles=nbfiles+1;
405                if nbfiles==1 %first field
406                    time_1=[];
407                    if isfield(Field,'Time')
408                        time_1=Field.Time(1);
409                    end
410                    DataMean=Field;%default
411                else
412                    for ivar=1:length(Field.ListVarName)
413                        VarName=Field.ListVarName{ivar};
414                        eval(['sizmean=size(DataMean.' VarName ');']);
415                        eval(['siz=size(Field.' VarName ');']);
416                        if ~isequal(siz,sizmean)
[43]417                           msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to interpolate on a grid'])
418                           return
[27]419                        else
420                            eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
421                        end
422                    end
423                end
424        end
425    end %end averaging loop
426    for ivar=1:length(Field.ListVarName)
427        VarName=Field.ListVarName{ivar};
428        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
429    end
430    if nbmissing~=0
431        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
432    end
433    if isempty(time) % time read from files  prevails
434        time_end=[];
435        if isfield(Field,'Time')
436            time_end=Field.Time(1);%last time read
437            if ~isempty(time_1)
438                DataMean.Time=time_1;
439                DataMean.Time_end=time_end;
440            end
441        end
442    else  % time from ImaDoc prevails
443        DataMean.Time=time(1,num_i1{1}(1),num_j1{1}(1));
444        DataMean.Time_end=time(end,num_i1{end}(end),num_j1{end}(end));
445    end
[190]446
[27]447    %writing the result file
448   if testima   
[29]449        [filemean]=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.png',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end),subdir_result);
[27]450        if exist(filemean,'file')
451            backupfile=filemean;
452            testexist=2;
453            while testexist==2
454                backupfile=[backupfile(1:end-4) '~.png'];
455                testexist=exist(backupfile,'file');
456            end
457            [success,message]=copyfile(filemean,backupfile);%make backup
458            if ~isequal(success,1)
459                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
460                return
461            end
462        end
463        if isequal(Atype{1},'uint16')
464            imwrite(uint16(DataMean.A),filemean,'BitDepth',16);
465        else
466            imwrite(uint8(DataMean.A),filemean,'BitDepth',8);
467        end
468        display([filemean ' written']);
[55]469    else %case of netcdf input file , determine global attributes
[27]470        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Series.Action}];
471        ActionKey='Action';
472        while isfield(DataMean,ActionKey)
473            ActionKey=[ActionKey '_1'];
474        end
475        eval(['DataMean.' ActionKey '=Series.Action;'])
476        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
477        if isfield(DataMean,'Time')
478            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
479        end 
[190]480        filemean=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.nc',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end),subdir_result);
[27]481        if exist(filemean,'file')
482            backupfile=filemean;
483            testexist=2;
484            while testexist==2
485                backupfile=[backupfile(1:end-3) '~.nc'];
486                testexist=exist(backupfile,'file');
487            end
488            [success,message]=copyfile(filemean,backupfile);%make backup
489            if ~isequal(success,1)
490                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
491                display(['previous file result ' filemean ' already exists, problem in backup'])
492                return
493            end
494        end
495        errormsg=struct2nc(filemean,DataMean); %save result file
496        if isempty(errormsg)
497            display([filemean ' written']);
498        else
499            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
500            display(errormsg)
501        end
502   end
503end
[55]504
[27]505hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
506delete(hget_field)
507uvmat(filemean)
Note: See TracBrowser for help on using the repository browser.