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

Last change on this file since 381 was 381, checked in by sommeria, 12 years ago

read_get_field suppressed, replaced by read_GUI

File size: 20.2 KB
Line 
1%'aver_stat': calculate field average, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=aver_stat(Param)
4%
5%OUTPUT
6% GUI_input=list of options in the GUI series.fig needed for the function
7%
8%INPUT:
9% Param: structure containing all the parameters read on the GUI series
10%  or name of the xml file containing these parameters (BATCH case)
11%
12function GUI_input=aver_stat(Param)
13%----------------------------------------------------------------------
14% --- make average on a series of files
15%----------------------------------------------------------------------
16%INPUT:
17%i1_series: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
18%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
19%j1_series: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
20%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
21%OTHER INPUTS given by the structure Series
22%  Series.Time:
23%  Series.GeometryCalib:%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
24if ~exist('Param','var')
25    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
26        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
27        'RootFile';'on';... %root input file name ('on' by default)
28        'FileExt';'on';... %input file extension ('on' by default)
29        'NomType';'on';...%type of file indexing ('on' by default)
30        'NbSlice';'on'; ...%nbre of slices ('off' by default)
31        'VelTypeMenu';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
32        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
33        'CoordType'; 'on';...%can use a transform function
34        'GetObject';'on';...%can use projection object(option 'off'/'one'/'two',
35        %'GetMask';'on'...%can use mask option   
36        %'PARAMETER'; %options: name of the user defined parameter',repeat a line for each parameter
37               ''};
38        return
39end
40
41%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42
43%% input parameters
44% read the xml file for batch case
45if ischar(Param) && ~isempty(find(regexp('Param','.xml$')))
46    Param=xml2struct(Param);
47else %  RUN case: parameters introduced as the input structure Param
48    hseries=guidata(Param.hseries);%handles of the GUI series
49    WaitbarPos=get(hseries.waitbar_frame,'Position');
50end
51[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
52
53%% coordinate transform or other user defined transform (TODO: case BATCH ?)
54transform_fct='';%default
55if isfield(Param,'transform_fct') % transform function handle
56    transform_fct=Param.transform_fct;
57end
58
59%% projection object
60test_object=get(hseries.GetObject,'Value');
61if test_object%isfield(Series,'sethandles')
62    hset_object=findobj(allchild(0),'tag','set_object');
63    %ProjObject=read_set_object(guidata(hset_object));
64    ProjObject=read_GUI(hset_object);
65    %answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
66    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' ProjObject.Style ' before averaging']);
67    if ~isequal(answeryes,'Yes')
68        return
69    end
70end
71
72%% root input file and 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);
78ext=FileExt{1};
79form=imformats(ext([2:end]));%test valid Matlab image formats
80testima=0;
81if ~isempty(form)||isequal(lower(ext),'.avi')||isequal(lower(ext),'.vol')
82    testima(1)=1;
83end
84if length(FileExt)>=2
85    ext_1=FileExt{2};
86    form=imformats(ext_1([2:end]));%test valid Matlab image formats
87    if ~isempty(form)||isequal(lower(ext_1),'.avi')||isequal(lower(ext_1),'.vol')
88        testima(2)=1;
89    end
90    if testima(2)~=testima(1)
91        msgbox_uvmat('ERROR','images and netcdf files cannot be compared')
92        return
93    end
94end
95
96
97%% Number of input series: this function  accepts two input file series at most (then it operates on the difference of fields)
98nbview=length(RootPath);
99if nbview>2 
100    RootPath=RootPath(1:2);
101    set(hseries.RootPath,'String',RootPath)
102    SubDir=SubDir(1:2);
103    set(hseries.SubDir,'String',SubDir)
104    RootFile=RootFile(1:2);
105    set(hseries.RootFile,'String',RootFile)
106    NomType=NomType(1:2);
107    FileExt=FileExt(1:2);
108    set(hseries.FileExt,'String',FileExt)
109    nbview=2;
110end
111
112%% determine image type
113hhh=which('mmreader');
114for iview=1:nbview
115    if isequal(FileExt{iview},'.nc')||isequal(FileExt{iview},'.cdf')
116        FileType{iview}='netcdf';
117    elseif isequal(lower(FileExt{iview}),'.avi')
118        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
119            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
120            FileType{iview}='movie';
121        else
122            FileType{iview}='avi';
123        end
124    elseif isequal(lower(FileExt{iview}),'.vol')
125        FileType{iview}='vol';
126    else
127       form=imformats(FileExt{iview}(2:end));
128       if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
129           if isequal(NomType{iview},'*');
130               FileType{iview}='multimage';
131           else
132               FileType{iview}='image';
133           end
134       end
135    end
136end
137
138%% number of slices
139NbSlice=Param.IndexRange.NbSlice;
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}),i1_series{1}(1),j1_series{1}(1),FileExt{1},NomType{1},1,i2_series{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;
166% FileExt=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) < i2_series{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(Param.InputTable{1,4},i2_series{end}(end)-i1_series{1}(1),j2_series{end}(end)-j1_series{1}(1));
270        NomTypeOut='_1-2';
271%         RootPath,SubDir,RootFile,FileExt,NomType,i1,i2,j1,j2)
272        fileresult{1}=fullfile_uvmat(RootPath{1},subdir_result,RootFile{1},ext_out,NomTypeOut,i1_series{1}(1),[],[],[]);
273%         fileresult{1}=name_generator(filebase_out,i1_series{1}(1),j1_series{1}(1),ext_out,NomTypeOut,1,i2_series{end}(end),j2_series{end}(end),subdir_result);
274        testexist=exist(fileresult{1},'file');
275    else % simplified indexing with i_slice for multiple slices
276        testexist=0;
277        for i_slice=1:NbSlice
278            fileresult{1}=fullfile_uvmat(RootPath{1},subdir_result,RootFile{1},ext_out,NomTypeOut,i_slice,[],[],[]);
279            %fileresult{i_slice}=name_generator(filebase_out,i_slice,[],ext_out,'_1',1,i_slice,[],subdir_result);
280            if exist(fileresult{i_slice},'file')
281                testexist=1;
282                break
283            end
284        end
285    end
286    if testexist
287        subdir_result=[subdir_result '.0'];
288    end
289end
290% create result directory if needed
291if ~exist(pathdir,'dir')
292    [m1,m2,m3]=mkdir(pathdir);
293    if ~isequal(m2,'')
294        msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
295    end
296end
297[xx,msg2] = fileattrib(pathdir,'+w','g'); %yield writing access (+w) to user group (g)
298if ~strcmp(msg2,'')
299    msgbox_uvmat('ERROR',['pb of permission for ' pathdir ': ' msg2])%error message for writting access
300    return
301end
302
303%% coordinate transform or other user defined transform
304transform_fct='';%default
305if isfield(Param,'FieldTransform')&&isfield(Param.FieldTransform,'transform_fct')
306    transform_fct=Param.FieldTransform.transform_fct;
307end
308
309%% main loop
310siz=size(i1_series{1});
311nbfield2=siz(1); %nb of consecutive fields at each level(burst
312nbfield=siz(1)*siz(2);
313nbfield=floor(nbfield/(nbfield2*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
314
315% loop on slices
316for i_slice=1:NbSlice
317    for ifield=1:nbfield
318         indselect(:,ifield)=((ifield-1)*NbSlice+(i_slice-1))*nbfield2+[1:nbfield2]';%selected indices on the list of files of a slice
319    end
320    S=0; %initiate the image sum S
321    nbfiles=0;
322    nbmissing=0;
323    % averaging loop
324    for index=1:nbfield*nbfield2
325 %       stopstate=get(hseries.RUN,'BusyAction');
326 %       if isequal(stopstate,'queue') % enable STOP command
327         %   update_waitbar(hseries.waitbar,WaitbarPos,index/(nbfield*nbfield2))
328            ifile=indselect(index);
329            % reading input file(s)
330            for iview=1:nbview
331%                 [filename]=...
332%                     name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),FileExt{iview},NomType{iview},1,num_i2{iview}(ifile),j2_series{iview}(ifile),SubDir{iview});
333                    filename=filecell{iview,index};
334                    if ~isequal(FileType{iview},'netcdf')
335                    Data{iview}.ListVarName={'A'};
336                    Data{iview}.AName='image';
337                    switch FileType{iview}
338                        case 'movie'
339                            A=read(MovieObject{iview},i1_series{iview}(ifile));
340                        case 'avi'
341                            mov=aviread(filename,i1_series{iview}(ifile));
342                            A=frame2im(mov(1));
343                        case 'vol'
344                            A=imread(filename);
345                        case 'multimage'
346                            A=imread(filename,i1_series{iview}(ifile));
347                        case 'image'
348                            A=imread(filename);
349                    end
350                    Data{iview}.ListVarName={'AY','AX','A'}; %
351                    Atype{iview}=class(A);
352                    npy=size(A,1);
353                    npx=size(A,2);
354                    nbcolor=size(A,3);
355                    if nbcolor==3
356                        Data{iview}.VarDimName={'AY','AX',{'AY','AX','rgb'}};
357                    else
358                        Data{iview}.VarDimName={'AY','AX',{'AY','AX'}};
359                    end
360                    Data{iview}.AY=[npy-0.5 0.5];
361                    Data{iview}.AX=[0.5 npx-0.5];
362                    Data{iview}.A=double(A);
363                    Data{iview}.CoordUnit='pixel';
364                elseif testcivx
365                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
366                else
367                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data
368                    Data{iview}.VarAttribute=SubField.VarAttribute;
369                end
370                if isfield(Data{iview},'Txt')
371                    msgbox_uvmat('ERROR',['error of input reading: ' Data{iview}.Txt])
372                    return
373                end
374            end
375           
376            % coordinate transform (or other user defined transform)
377            if ~isempty(transform_fct)
378                if ~isempty(NbSlice_calib)
379                    Data{iview}.ZIndex=mod(i1_series{iview}(ifile)-1,NbSlice_calib{1})+1;%Zindex for phys transform
380                end
381                if nbview==2
382                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
383                    if isempty(Data{2})
384                        Data(2)=[];
385                    end
386                else
387                    Data{1}=transform_fct(Data{1},XmlData{1});
388                end
389            end
390           
391            % field calculation (vort, div...)
392            if testcivx
393                Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
394            end
395           
396            % field substration (for two input file series)
397            if length(Data)==2
398                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
399                if ~isempty(errormsg)
400                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
401                    return
402                end
403            else
404                Field=Data{1};
405            end
406            if test_object
407                [Field,errormsg]=proj_field(Field,ProjObject);
408                if ~isempty(errormsg)
409                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
410                    return
411                end
412            end
413            nbfiles=nbfiles+1;
414            if nbfiles==1 %first field
415                time_1=[];
416                if isfield(Field,'Time')
417                    time_1=Field.Time(1);
418                end
419                DataMean=Field;%default
420            else
421                for ivar=1:length(Field.ListVarName)
422                    VarName=Field.ListVarName{ivar};
423                    eval(['sizmean=size(DataMean.' VarName ');']);
424                    eval(['siz=size(Field.' VarName ');']);
425                    if ~isequal(siz,sizmean)
426                        msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
427                        return
428                    else
429                        eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
430                    end
431                end
432            end
433%         end
434    end
435    %end averaging loop
436    for ivar=1:length(Field.ListVarName)
437        VarName=Field.ListVarName{ivar};
438        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
439    end
440    if nbmissing~=0
441        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
442    end
443    if isempty(time) % time read from files  prevails
444        time_end=[];
445        if isfield(Field,'Time')
446            time_end=Field.Time(1);%last time read
447            if ~isempty(time_1)
448                DataMean.Time=time_1;
449                DataMean.Time_end=time_end;
450            end
451        end
452    else  % time from ImaDoc prevails
453        DataMean.Time=time(1,i1_series{1}(1),j1_series{1}(1));
454        DataMean.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
455    end
456   
457    %writing the result file
458    if testima %case of images
459        if isequal(Atype{1},'uint16')
460            imwrite(uint16(DataMean.A),fileresult{i_slice},'BitDepth',16); % case of 16 bit images
461        else
462            imwrite(uint8(DataMean.A),fileresult{i_slice},'BitDepth',8); % case of 8 bit images
463        end
464        display([fileresult{i_slice} ' written']);
465    else %case of netcdf input file , determine global attributes
466        if isempty(strcmp('Conventions',DataMean.ListGlobalAttribute))
467            DataMean.ListGlobalAttribute=['Conventions' DataMean.ListGlobalAttribute];
468        end
469        DataMean.Conventions='uvmat';
470        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Param.Action}];
471        ActionKey='Action';
472        while isfield(DataMean,ActionKey)
473            ActionKey=[ActionKey '_1'];
474        end
475        DataMean.(ActionKey)=Param.Action;
476        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
477        if isfield(DataMean,'Time')
478            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
479        end
480        errormsg=struct2nc(fileresult{i_slice},DataMean); %save result file
481        if isempty(errormsg)
482            display([fileresult{i_slice} ' written']);
483        else
484            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
485            display(errormsg)
486        end
487    end  % end averaging  loop
488end % end loop on slices
489
490%% reproduce ImaDoc/GeometryCalib for image series
491if isfield(XmlData{1},'GeometryCalib') && ~isempty(XmlData{1}.GeometryCalib)
492    [pp,RootFile]=fileparts(filebase_out);
493    outputxml=fullfile(pathdir,[RootFile '.xml'])
494    errormsg=update_imadoc(XmlData{1}.GeometryCalib,outputxml);% introduce the calibration data in the xml file
495    if strcmp(errormsg,'')
496        display(['GeometryCalib transferred to ' outputxml])
497    else
498        msgbox_uvmat('ERROR',errormsg);
499    end
500end
501
502%% open the result file with uvmat
503hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
504delete(hget_field)
505uvmat(fileresult{end})
Note: See TracBrowser for help on using the repository browser.