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

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

fill_GUI debugged: civ can open the xml file of a previous operation (instead of opening the saved GUI figure)

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