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

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

bugs corrected for phys ort other transform functions

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