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

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

bugs corrected in series fct taking into account new conventions

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