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

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

small corrections to fit with the new GUI series;fig

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