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

Last change on this file since 169 was 169, checked in by sommeria, 13 years ago

comments added at the head of functions

File size: 20.7 KB
Line 
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%
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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48
49%projection object
50test_object=get(hseries.GetObject,'Value');
51if test_object%isfield(Series,'sethandles')
52    hset_object=findobj(allchild(0),'tag','set_object');
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
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
108
109%determine image type
110hhh=which('mmreader');
111for iview=1:nbview
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()
116            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
117            FileType{iview}='movie';
118        else
119            FileType{iview}='avi';
120        end
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
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'
164% testima=0;
165% testvol=0;
166testcivx=0;
167% testnc=0;
168FileExt=get(hseries.FileExt,'String');
169% test_movie=0;
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
189if ~isequal(FieldName,{'get_field...'})
190    testcivx=isequal(FileType{1},'netcdf');
191end
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
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;
257if isempty(timecell)
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
285% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
286subdir_result='aver_stat';
287if ~exist(fullfile(RootPath{1},subdir_result),'dir')
288    dircur=pwd; %record current working directory
289    cd(RootPath{1})% goes to the iamge directory
290    [m1,m2,m3]=mkdir(subdir_result);
291    if ~isequal(m2,'')
292         msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
293    end
294    [xx,msg2] = fileattrib(subdir_result,'+w','g'); %yield writing access (+w) to user group (g)
295    if ~strcmp(msg2,'')
296        msgbox_uvmat('ERROR',['pb of permission for ' subdir_result ': ' msg2])%error message for directory creation
297        cd(curdir)
298        return
299    end
300    cd(dircur) %back to the initial working directory
301end
302filebase_out=filebase{1};
303NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
304
305% coordinate transform or other user defined transform
306transform_fct=[];%default
307if isfield(Series,'transform_fct')
308    transform_fct=Series.transform_fct;
309end
310
311%slice loop
312siz=size(num_i1{1});
313lengthtot=siz(1)*siz(2);
314nbfield=floor(lengthtot/(siz(1)*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
315nbfield_slice=nbfield*siz(1);% number of fields per slice
316
317for i_slice=1:NbSlice
318   S=0; %initiate the image sum S
319   nbfiles=0;
320   nbmissing=0;
321    %averaging loop
322   for ifile=i_slice:NbSlice:lengthtot
323        stopstate=get(hseries.RUN,'BusyAction');
324        if isequal(stopstate,'queue') % enable STOP command
325             update_waitbar(hseries.waitbar,WaitbarPos,ifile/lengthtot)
326             for iview=1:nbview
327                [filename]=...
328                           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});
329                if ~isequal(FileType{iview},'netcdf')               
330                    Data{iview}.ListVarName={'A'};
331                    Data{iview}.AName='image';
332                    switch FileType{iview}
333                        case 'movie'
334                            A=read(MovieObject{iview},num_i1{iview}(ifile));
335                        case 'avi'
336                            mov=aviread(filename,num_i1{iview}(ifile));
337                            A=frame2im(mov(1));
338                        case 'vol'
339                            A=imread(filename);
340                        case 'multimage'
341                            A=imread(filename,num_i1{iview}(ifile));
342                        case 'image'
343                            A=imread(filename);
344                    end
345                    Data{iview}.ListVarName={'AY','AX','A'}; %
346                    Atype{iview}=class(A);
347                    npy=size(A,1);
348                    npx=size(A,2);
349                    nbcolor=size(A,3);
350                    if nbcolor==3
351                         Data{iview}.VarDimName={'AY','AX',{'AY','AX','rgb'}};
352                    else
353                         Data{iview}.VarDimName={'AY','AX',{'AY','AX'}};
354                    end 
355                    Data{iview}.AY=[npy-0.5 0.5];
356                    Data{iview}.AX=[0.5 npx-0.5];
357                    Data{iview}.A=double(A);
358                    Data{iview}.CoordUnit='pixel';
359                elseif testcivx
360                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
361                else
362                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
363                    Data{iview}.VarAttribute=SubField.VarAttribute;
364                end
365                if isfield(Data{iview},'Txt')
366                    msgbox_uvmat('ERROR',['error of input reading: ' Data{iview}.Txt])
367                    return
368                end
369             end   
370             % coordinate transform (or other user defined transform)
371             if ~isempty(transform_fct)
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
377                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
378                    if isempty(Data{2})
379                        Data(2)=[];
380                    end
381                else
382                    Data{1}=transform_fct(Data{1},XmlData{1});
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
397            if test_object
398                [Field,errormsg]=proj_field(Field,ProjObject);
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)
417                           msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to interpolate on a grid'])
418                           return
419                        else
420                            eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
421                        end
422                    end
423                end
424%             else
425%                 nbmissing=nbmissing+1;
426%             end
427        end
428    end %end averaging loop
429    for ivar=1:length(Field.ListVarName)
430        VarName=Field.ListVarName{ivar};
431        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
432    end
433    if nbmissing~=0
434        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
435    end
436    if isempty(time) % time read from files  prevails
437        time_end=[];
438        if isfield(Field,'Time')
439            time_end=Field.Time(1);%last time read
440            if ~isempty(time_1)
441                DataMean.Time=time_1;
442                DataMean.Time_end=time_end;
443            end
444        end
445    else  % time from ImaDoc prevails
446        DataMean.Time=time(1,num_i1{1}(1),num_j1{1}(1));
447        DataMean.Time_end=time(end,num_i1{end}(end),num_j1{end}(end));
448    end
449   
450    %writing the result file
451   if testima   
452%        if NbSlice==1
453        [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);
454%        else % label the file number by the slice # for simplicity
455%           [filemean]=name_generator(filebase_out,i_slice,1,'.png','_i');
456%        end
457        if exist(filemean,'file')
458            backupfile=filemean;
459            testexist=2;
460            while testexist==2
461                backupfile=[backupfile(1:end-4) '~.png'];
462                testexist=exist(backupfile,'file');
463            end
464            [success,message]=copyfile(filemean,backupfile);%make backup
465            if ~isequal(success,1)
466                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
467                return
468            end
469        end
470        if isequal(Atype{1},'uint16')
471            imwrite(uint16(DataMean.A),filemean,'BitDepth',16);
472        else
473            imwrite(uint8(DataMean.A),filemean,'BitDepth',8);
474        end
475        display([filemean ' written']);
476    else %case of netcdf input file , determine global attributes
477        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Series.Action}];
478        ActionKey='Action';
479        while isfield(DataMean,ActionKey)
480            ActionKey=[ActionKey '_1'];
481        end
482        eval(['DataMean.' ActionKey '=Series.Action;'])
483        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
484        if isfield(DataMean,'Time')
485            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
486        end 
487%         if NbSlice==1
488          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);
489%         else % label the file number by the slice # for simplicity
490%           [filemean]=name_generator(filebase_out,i_slice,1,'.nc','_i');
491%         end
492        if exist(filemean,'file')
493            backupfile=filemean;
494            testexist=2;
495            while testexist==2
496                backupfile=[backupfile(1:end-3) '~.nc'];
497                testexist=exist(backupfile,'file');
498            end
499            [success,message]=copyfile(filemean,backupfile);%make backup
500            if ~isequal(success,1)
501                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
502                display(['previous file result ' filemean ' already exists, problem in backup'])
503                return
504            end
505        end
506        errormsg=struct2nc(filemean,DataMean); %save result file
507        if isempty(errormsg)
508            display([filemean ' written']);
509        else
510            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
511            display(errormsg)
512        end
513   end
514end
515
516hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
517delete(hget_field)
518uvmat(filemean)
Note: See TracBrowser for help on using the repository browser.