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

Last change on this file since 27 was 27, checked in by gostiaux, 14 years ago

files separated from series.m

File size: 18.2 KB
RevLine 
[27]1function GUI_input=aver_stat(num_i1,num_i2,num_j1,num_j2,Series)
2%----------------------------------------------------------------------
3% --- make average on a series of files
4%----------------------------------------------------------------------
5%INPUT:
6%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
7%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
8%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
9%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
10%OTHER INPUTS given by the structure Series
11%  Series.Time:
12%  Series.GeometryCalib:%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
13if ~exist('num_i1','var')
14    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
15        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
16        'RootFile';'on';... %root input file name ('on' by default)
17        'FileExt';'on';... %input file extension ('on' by default)
18        'NomType';'on';...%type of file indexing ('on' by default)
19        'NbSlice';'on'; ...%nbre of slices ('off' by default)
20        'VelTypeMenu';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
21        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
22        'CoordType'; 'on';...%can use a transform function
23        'GetObject';'on';...%can use projection object(option 'off'/'one'/'two',
24        %'GetMask';'on'...%can use mask option   
25        %'PARAMETER'; %options: name of the user defined parameter',repeat a line for each parameter
26               ''};
27        return
28end
29
30%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31hseries=guidata(Series.hseries);%handles of the GUI series
32WaitbarPos=get(hseries.waitbar_frame,'Position');
33%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
34
35%root input file and type
36if ~iscell(Series.RootPath)% case of a single input field series
37    num_i1={num_i1};num_j1={num_j1};num_i2={num_i2};num_j2={num_j2};
38    RootPath={Series.RootPath};
39    RootFile={Series.RootFile};
40    SubDir={Series.SubDir};
41    FileExt={Series.FileExt};
42    NomType={Series.NomType};
43else
44    RootPath=Series.RootPath;
45    RootFile=Series.RootFile;
46    SubDir=Series.SubDir;
47    NomType=Series.NomType;
48    FileExt=Series.FileExt;
49end   
50ext=FileExt{1};
51form=imformats(ext([2:end]));%test valid Matlab image formats
52testima=0;
53if ~isempty(form)||isequal(lower(ext),'.avi')||isequal(lower(ext),'.vol')
54    testima(1)=1;
55end
56if length(FileExt)>=2
57    ext_1=FileExt{2};
58    form=imformats(ext_1([2:end]));%test valid Matlab image formats
59    if ~isempty(form)||isequal(lower(ext_1),'.avi')||isequal(lower(ext_1),'.vol')
60        testima(2)=1;
61    end
62    if testima(2)~=testima(1)
63        msgbox_uvmat('ERROR','images and netcdf files cannot be compared')
64        return
65    end
66end
67
68%Number of input series: this function  accepts two input file series at most (then it operates on the difference of fields)
69nbview=length(RootPath);
70if nbview>2 
71    RootPath=RootPath(1:2);
72    set(hseries.RootPath,'String',RootPath)
73    SubDir=SubDir(1:2);
74    set(hseries.SubDir,'String',SubDir)
75    RootFile=RootFile(1:2);
76    set(hseries.RootFile,'String',RootFile)
77    NomType=NomType(1:2);
78    FileExt=FileExt(1:2);
79    set(hseries.FileExt,'String',FileExt)
80    nbview=2;
81end
82hhh=which('mmreader');
83for iview=1:nbview
84    test_movie(iview)=0;
85    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
86        if isequal(lower(FileExt{iview}),'.avi')
87            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
88            test_movie(iview)=1;
89        end
90    end
91end
92
93% number of slices
94NbSlice=str2num(get(hseries.NbSlice,'String'));
95if isempty(NbSlice)
96    NbSlice=1;
97end
98NbSlice_name=num2str(NbSlice);
99
100% Field and velocity type (the same for the two views)
101Field_str=get(hseries.FieldMenu,'String');
102FieldName=[]; %default
103testfield=get(hseries.FieldMenu,'Visible');
104if isequal(testfield,'on')
105    val=get(hseries.FieldMenu,'Value');
106    FieldName=Field_str(val);%the same set of fields for all views
107    if isequal(FieldName,{'get_field...'})
108        hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
109        if length(hget_field)>1
110            delete(hget_field(2:end))
111        elseif isempty(hget_field)
112           filename=...
113                 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});
114           get_field(filename);
115           return
116        end
117        %hhget_field=guidata(hget_field);%handles of GUI elements in get_field
118        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
119    end
120end
121%detect whether the two files are 'images' or 'netcdf'
122testima=0;
123testvol=0;
124testcivx=0;
125testnc=0;
126FileExt=get(hseries.FileExt,'String');
127% test_movie=0;
128for iview=1:nbview
129     ext=FileExt{iview};
130     form=imformats(ext([2:end]));
131     if isequal(lower(ext),'.vol')
132         testvol=testvol+1;
133     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
134         testima=testima+1;
135     elseif isequal(ext,'.nc')
136         testnc=testnc+1;
137     end
138end
139if testvol
140    msgbox_uvmat('ERROR','volume images not implemented yet')
141    return
142end
143if testnc~=nbview && testima~=nbview && testvol~=nbview
144    msgbox_uvmat('ERROR','compare two image series or two netcdf files with the same fields as input')
145    return
146end
147if ~isequal(FieldName,{'get_field...'})
148    testcivx=testnc;
149end
150
151if testcivx
152    VelType_str=get(hseries.VelTypeMenu,'String');
153    VelType_val=get(hseries.VelTypeMenu,'Value');
154    VelType{1}=VelType_str{VelType_val};
155    if nbview==2
156        VelType_str=get(hseries.VelTypeMenu_1,'String');
157        VelType_val=get(hseries.VelTypeMenu_1,'Value');
158        VelType{2}=VelType_str{VelType_val};
159    end
160end
161
162%Calibration data and timing: read the ImaDoc files
163mode=''; %default
164timecell={};
165itime=0;
166NbSlice_calib={};
167for iview=1:nbview%Loop on views
168    XmlData{iview}=[];%default
169    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
170    if exist([filebase{iview} '.xml'],'file')
171        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
172        if isfield(XmlData{iview},'Time')
173            itime=itime+1;
174            timecell{itime}=XmlData{iview}.Time;
175        end
176        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
177            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
178            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
179                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
180            end
181        end
182    elseif exist([filebase{iview} '.civ'],'file')
183        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
184        itime=itime+1;
185        timecell{itime}=time;
186        XmlData{iview}.Time=time;
187        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
188        GeometryCalib.Tx=0;
189        GeometryCalib.Ty=0;
190        GeometryCalib.Tz=1;
191        GeometryCalib.dpx=1;
192        GeometryCalib.dpy=1;
193        GeometryCalib.sx=1;
194        GeometryCalib.Cx=0;
195        GeometryCalib.Cy=0;
196        GeometryCalib.f=1;
197        GeometryCalib.kappa1=0;
198        GeometryCalib.CoordUnit='cm';
199        XmlData{iview}.GeometryCalib=GeometryCalib;
200        if error==1
201            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
202        end
203    end
204end
205
206%check coincidence in time
207multitime=0;
208if length(timecell)==0
209    time=[];
210elseif length(timecell)==1
211    time=timecell{1};
212elseif length(timecell)>1
213    multitime=1;
214    for icell=1:length(timecell)
215        if ~isequal(size(timecell{icell}),size(timecell{1}))
216            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
217            time=timecell{1};
218            multitime=0;
219            break
220        end
221    end
222end
223if multitime
224    for icell=1:length(timecell)
225        time(icell,:,:)=timecell{icell};
226    end
227    diff_time=max(max(diff(time)));
228    if diff_time>0
229        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
230    end   
231end
232if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
233    time=[];
234end
235
236% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
237filebasesub=fullfile(RootPath{1},SubDir{1},RootFile{1});
238if isempty(SubDir{1}) % create a subdirectory '/mean'
239    subdir_result='mean';
240%     filebasemean=fullfile(RootPath{1},subdir_result);
241    if ~exist(fullfile(RootPath{1},subdir_result),'dir')
242        dircur=pwd; %record current working directory
243        cd(RootPath{1})% goes to the iamge directory
244        [m1,m2,m3]=mkdir(subdir_result);
245        if ~isequal(m2,'')
246             msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
247        end
248        cd(dircur) %back to the initial working directory
249    end
250    filebase_out=filebase{1};
251else
252   subdir_result=SubDir{1};
253   filebase_out=[filebase{1} '_mean'];% output root name obtained by adding the suffix _mean to the input
254end
255%output nomtype (to generalise)
256NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
257   
258if NbSlice==1 
259    filebase_out=[filebasesub '_mean'];
260else
261    filebase_out=[filebasesub '_' NbSlice_name 'mean'];
262    answeryes=questdlg({['will make average in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_out ' ...']});
263    if ~isequal(answeryes,'Yes')
264        return
265    end
266end
267
268% coordinate transform or other user defined transform
269Coord_menu=get(hseries.CoordType,'String');
270menu_val=get(hseries.CoordType,'Value');
271usrfct=Coord_menu{menu_val};
272testfct=~isequal(usrfct,'');
273
274%slice loop
275siz=size(num_i1{1});
276lengthtot=siz(1)*siz(2);
277nbfield=floor(lengthtot/(siz(1)*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
278nbfield_slice=nbfield*siz(1);% number of fields per slice
279
280for i_slice=1:NbSlice
281   S=0; %initiate the image sum S
282   nbfiles=0;
283   nbmissing=0;
284    %averaging loop
285   for ifile=i_slice:NbSlice:lengthtot
286        stopstate=get(hseries.RUN,'BusyAction');
287        if isequal(stopstate,'queue') % enable STOP command
288             update_waitbar(hseries.waitbar,WaitbarPos,ifile/lengthtot)
289             for iview=1:nbview
290                [filename]=...
291                           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});
292                if testima
293                    Data{iview}.ListVarName={'A'};
294                    Data{iview}.AName='image';
295                    if test_movie(iview)
296                        Data{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
297                    else
298                        Data{iview}.A=read_image(filename,NomType{iview},num_i1{iview}(ifile));% read the image, num2 is the counter for avi files
299                    end
300                    Atype{iview}=class(Data{iview}.A);
301                    Data{iview}.A=double(Data{iview}.A);
302                elseif testcivx
303                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
304                else
305                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
306                    Data{iview}.VarAttribute=SubField.VarAttribute;
307                end
308                if isfield(Data{iview},'Txt')
309                    msgbox_uvmat('ERROR',['error of input reading: ' Data{iview}.Txt])
310                    return
311                end
312             end   
313             % coordinate transform (or other user defined transform)
314             if ~isequal(Series.CoordType,'')
315                 % z index
316                if ~isempty(NbSlice_calib)
317                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;%Zindex for phys transform
318                end
319                if nbview==2
320                    [Data{1},Data{2}]=feval(Series.CoordType,Data{1},XmlData{1},Data{2},XmlData{2});
321                    if isempty(Data{2})
322                        Data(2)=[];
323                    end
324                else
325                    Data{1}=feval(Series.CoordType,Data{1},XmlData);
326                end
327             end     
328            if testcivx
329                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
330            end
331            if length(Data)==2
332                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
333                if ~isempty(errormsg)
334                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
335                    return
336                end
337            else
338                Field=Data{1};
339            end
340            if isfield(Series,'ProjObject')
341                [Field,errormsg]=proj_field(Field,Series.ProjObject);
342                 if ~isempty(errormsg)
343                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
344                    return
345                end
346             end                                                       
347                nbfiles=nbfiles+1;
348                if nbfiles==1 %first field
349                    time_1=[];
350                    if isfield(Field,'Time')
351                        time_1=Field.Time(1);
352                    end
353                    DataMean=Field;%default
354                else
355                    for ivar=1:length(Field.ListVarName)
356                        VarName=Field.ListVarName{ivar};
357                        eval(['sizmean=size(DataMean.' VarName ');']);
358                        eval(['siz=size(Field.' VarName ');']);
359                        if ~isequal(siz,sizmean)
360                            warndlg_uvmat(['unequal size of input field ' VarName ', need to interpolate on a grid'],'WARNING')
361                            nbmissing=nbmissing+1;
362                            break
363                        else
364                            eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
365                        end
366                    end
367                end
368%             else
369%                 nbmissing=nbmissing+1;
370%             end
371        end
372    end %end averaging loop
373    for ivar=1:length(Field.ListVarName)
374        VarName=Field.ListVarName{ivar};
375        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
376    end
377    if nbmissing~=0
378        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
379    end
380    if isempty(time) % time read from files  prevails
381        time_end=[];
382        if isfield(Field,'Time')
383            time_end=Field.Time(1);%last time read
384            if ~isempty(time_1)
385                DataMean.Time=time_1;
386                DataMean.Time_end=time_end;
387            end
388        end
389    else  % time from ImaDoc prevails
390        DataMean.Time=time(1,num_i1{1}(1),num_j1{1}(1));
391        DataMean.Time_end=time(end,num_i1{end}(end),num_j1{end}(end));
392    end
393   
394    %writing the result file
395   if testima   
396       if NbSlice==1
397        [filemean]=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.png',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end));
398       else % label the file number by the slice # for simplicity
399          [filemean]=name_generator(filebase_out,i_slice,1,'.png','_i');
400       end
401        if exist(filemean,'file')
402            backupfile=filemean;
403            testexist=2;
404            while testexist==2
405                backupfile=[backupfile(1:end-4) '~.png'];
406                testexist=exist(backupfile,'file');
407            end
408            [success,message]=copyfile(filemean,backupfile);%make backup
409            if ~isequal(success,1)
410                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
411                return
412            end
413        end
414        if isequal(Atype{1},'uint16')
415            imwrite(uint16(DataMean.A),filemean,'BitDepth',16);
416        else
417            imwrite(uint8(DataMean.A),filemean,'BitDepth',8);
418        end
419        display([filemean ' written']);
420    else %determine global attributes
421        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Series.Action}];
422        ActionKey='Action';
423        while isfield(DataMean,ActionKey)
424            ActionKey=[ActionKey '_1'];
425        end
426        eval(['DataMean.' ActionKey '=Series.Action;'])
427        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
428        if isfield(DataMean,'Time')
429            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
430        end 
431        if NbSlice==1
432          filemean=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.nc',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end));
433        else % label the file number by the slice # for simplicity
434          [filemean]=name_generator(filebase_out,i_slice,1,'.nc','_i');
435        end
436        if exist(filemean,'file')
437            backupfile=filemean;
438            testexist=2;
439            while testexist==2
440                backupfile=[backupfile(1:end-3) '~.nc'];
441                testexist=exist(backupfile,'file');
442            end
443            [success,message]=copyfile(filemean,backupfile);%make backup
444            if ~isequal(success,1)
445                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
446                display(['previous file result ' filemean ' already exists, problem in backup'])
447                return
448            end
449        end
450        errormsg=struct2nc(filemean,DataMean); %save result file
451        if isempty(errormsg)
452            display([filemean ' written']);
453        else
454            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
455            display(errormsg)
456        end
457   end
458end
459hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
460delete(hget_field)
461'TEST'
462uvmat(filemean)
Note: See TracBrowser for help on using the repository browser.