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

Last change on this file since 264 was 255, checked in by sommeria, 14 years ago

acver_stat corrected for multi slice case

File size: 19.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
164%% get the velocity type
165testcivx=0;
166FileExt=get(hseries.FileExt,'String');
167if ~isequal(FieldName,{'get_field...'})
168    testcivx=isequal(FileType{1},'netcdf');
169end
170if testcivx
171    VelType_str=get(hseries.VelTypeMenu,'String');
172    VelType_val=get(hseries.VelTypeMenu,'Value');
173    VelType{1}=VelType_str{VelType_val};
174    if nbview==2
175        VelType_str=get(hseries.VelTypeMenu_1,'String');
176        VelType_val=get(hseries.VelTypeMenu_1,'Value');
177        VelType{2}=VelType_str{VelType_val};
178    end
179end
180
181%% Calibration data and timing: read the ImaDoc files
182mode=''; %default
183timecell={};
184itime=0;
185NbSlice_calib={};
186for iview=1:nbview%Loop on views
187    XmlData{iview}=[];%default
188    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
189    if exist([filebase{iview} '.xml'],'file')
190        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
191        if isfield(XmlData{iview},'Time')
192            itime=itime+1;
193            timecell{itime}=XmlData{iview}.Time;
194        end
195        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
196            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
197            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
198                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
199            end
200        end
201    elseif exist([filebase{iview} '.civ'],'file')
202        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
203        itime=itime+1;
204        timecell{itime}=time;
205        XmlData{iview}.Time=time;
206        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
207        GeometryCalib.Tx=0;
208        GeometryCalib.Ty=0;
209        GeometryCalib.Tz=1;
210        GeometryCalib.dpx=1;
211        GeometryCalib.dpy=1;
212        GeometryCalib.sx=1;
213        GeometryCalib.Cx=0;
214        GeometryCalib.Cy=0;
215        GeometryCalib.f=1;
216        GeometryCalib.kappa1=0;
217        GeometryCalib.CoordUnit='cm';
218        XmlData{iview}.GeometryCalib=GeometryCalib;
219        if error==1
220            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
221        end
222    end
223end
224
225%% check coincidence in time
226multitime=0;
227if isempty(timecell)
228    time=[];
229elseif length(timecell)==1
230    time=timecell{1};
231elseif length(timecell)>1
232    multitime=1;
233    for icell=1:length(timecell)
234        if ~isequal(size(timecell{icell}),size(timecell{1}))
235            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
236            time=timecell{1};
237            multitime=0;
238            break
239        end
240    end
241end
242if multitime
243    for icell=1:length(timecell)
244        time(icell,:,:)=timecell{icell};
245    end
246    diff_time=max(max(diff(time)));
247    if diff_time>0
248        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
249    end   
250end
251if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
252    time=[];
253end
254
255%% Name(s) of output file(s)
256filebase_out=filebase{1};% the result file has the same root name as the input file series (and the first one is chosen in case of two input series)
257%file extension of the result 
258if testima %case of images
259    ext_out='.png';
260else
261    ext_out='.nc';
262end
263subdir_result='aver_stat';%subdirectory for the results
264pathdir=fullfile(RootPath{1},subdir_result);% full subdirectory name, including path
265testexist=1;
266while testexist
267    pathdir=fullfile(RootPath{1},subdir_result);% full subdirectory name, including path
268    if NbSlice==1% keep track of the first and lsat indices of the input files
269        NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
270        fileresult{1}=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),ext_out,NomTypeOut,1,num_i2{end}(end),num_j2{end}(end),subdir_result);
271        testexist=exist(fileresult{1},'file');
272    else % simplified indexing with i_slice for multiple slices
273        testexist=0;
274        for i_slice=1:NbSlice
275            fileresult{i_slice}=name_generator(filebase_out,i_slice,[],ext_out,'_1',1,i_slice,[],subdir_result);
276            if exist(fileresult{i_slice},'file')
277                testexist=1;
278                break
279            end
280        end
281    end
282    if testexist
283        subdir_result=[subdir_result '.0'];
284    end
285end
286% create result directory if needed
287if ~exist(pathdir,'dir')
288    [m1,m2,m3]=mkdir(pathdir);
289    if ~isequal(m2,'')
290        msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
291    end
292end
293[xx,msg2] = fileattrib(pathdir,'+w','g'); %yield writing access (+w) to user group (g)
294if ~strcmp(msg2,'')
295    msgbox_uvmat('ERROR',['pb of permission for ' pathdir ': ' msg2])%error message for writting access
296    return
297end
298
299%% coordinate transform or other user defined transform
300transform_fct=[];%default
301if isfield(Series,'transform_fct')
302    transform_fct=Series.transform_fct;
303end
304
305%% main loop
306siz=size(num_i1{1});
307nbfield2=siz(1); %nb of consecutive fields at each level(burst
308nbfield=siz(1)*siz(2);
309nbfield=floor(nbfield/(nbfield2*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
310
311% loop on slices
312for i_slice=1:NbSlice
313    for ifield=1:nbfield
314         indselect(:,ifield)=((ifield-1)*NbSlice+(i_slice-1))*nbfield2+[1:nbfield2]';%selected indices on the list of files of a slice
315    end
316    S=0; %initiate the image sum S
317    nbfiles=0;
318    nbmissing=0;
319    % averaging loop
320    for index=1:nbfield*nbfield2
321        stopstate=get(hseries.RUN,'BusyAction');
322        if isequal(stopstate,'queue') % enable STOP command
323            update_waitbar(hseries.waitbar,WaitbarPos,index/(nbfield*nbfield2))
324            ifile=indselect(index);
325            % reading input file(s)
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           
371            % coordinate transform (or other user defined transform)
372            if ~isempty(transform_fct)
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           
386            % field calculation (vort, div...)
387            if testcivx
388                Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
389            end
390           
391            % field substration (for two input file series)
392            if length(Data)==2
393                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
394                if ~isempty(errormsg)
395                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
396                    return
397                end
398            else
399                Field=Data{1};
400            end
401            if test_object
402                [Field,errormsg]=proj_field(Field,ProjObject);
403                if ~isempty(errormsg)
404                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
405                    return
406                end
407            end
408            nbfiles=nbfiles+1;
409            if nbfiles==1 %first field
410                time_1=[];
411                if isfield(Field,'Time')
412                    time_1=Field.Time(1);
413                end
414                DataMean=Field;%default
415            else
416                for ivar=1:length(Field.ListVarName)
417                    VarName=Field.ListVarName{ivar};
418                    eval(['sizmean=size(DataMean.' VarName ');']);
419                    eval(['siz=size(Field.' VarName ');']);
420                    if ~isequal(siz,sizmean)
421                        msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
422                        return
423                    else
424                        eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
425                    end
426                end
427            end
428        end
429    end
430    %end averaging loop
431    for ivar=1:length(Field.ListVarName)
432        VarName=Field.ListVarName{ivar};
433        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
434    end
435    if nbmissing~=0
436        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
437    end
438    if isempty(time) % time read from files  prevails
439        time_end=[];
440        if isfield(Field,'Time')
441            time_end=Field.Time(1);%last time read
442            if ~isempty(time_1)
443                DataMean.Time=time_1;
444                DataMean.Time_end=time_end;
445            end
446        end
447    else  % time from ImaDoc prevails
448        DataMean.Time=time(1,num_i1{1}(1),num_j1{1}(1));
449        DataMean.Time_end=time(end,num_i1{end}(end),num_j1{end}(end));
450    end
451   
452    %writing the result file
453    if testima %case of images
454        if isequal(Atype{1},'uint16')
455            imwrite(uint16(DataMean.A),fileresult{i_slice},'BitDepth',16); % case of 16 bit images
456        else
457            imwrite(uint8(DataMean.A),fileresult{i_slice},'BitDepth',8); % case of 8 bit images
458        end
459        display([fileresult{i_slice} ' written']);
460    else %case of netcdf input file , determine global attributes
461        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Series.Action}];
462        ActionKey='Action';
463        while isfield(DataMean,ActionKey)
464            ActionKey=[ActionKey '_1'];
465        end
466        eval(['DataMean.' ActionKey '=Series.Action;'])
467        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
468        if isfield(DataMean,'Time')
469            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
470        end
471        errormsg=struct2nc(fileresult{i_slice},DataMean); %save result file
472        if isempty(errormsg)
473            display([fileresult{i_slice} ' written']);
474        else
475            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
476            display(errormsg)
477        end
478    end  % end averaging  loop
479end % end loop on slices
480
481%% reproduce ImaDoc/GeometryCalib for image series
482if isfield(XmlData{1},'GeometryCalib') && ~isempty(XmlData{1}.GeometryCalib)
483    [pp,RootFile]=fileparts(filebase_out);
484    outputxml=fullfile(pathdir,[RootFile '.xml'])
485    errormsg=update_imadoc(XmlData{1}.GeometryCalib,outputxml);% introduce the calibration data in the xml file
486    if strcmp(errormsg,'')
487        display(['GeometryCalib transferred to ' outputxml])
488    else
489        msgbox_uvmat('ERROR',errormsg);
490    end
491end
492
493%% open the result file with uvmat
494hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
495delete(hget_field)
496uvmat(fileresult{end})
Note: See TracBrowser for help on using the repository browser.