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

Last change on this file since 29 was 29, checked in by sommeria, 11 years ago

read_imadoc suppressed (obsolete, replaced by imadoc2struct)
update_imadoc: bug repaired: existing xml file was erased
various cleaning (deals with non existing input file for series and uvmat)

File size: 18.3 KB
Line 
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%root input file and type
35if ~iscell(Series.RootPath)% case of a single input field series
36    num_i1={num_i1};num_j1={num_j1};num_i2={num_i2};num_j2={num_j2};
37    RootPath={Series.RootPath};
38    RootFile={Series.RootFile};
39    SubDir={Series.SubDir};
40    FileExt={Series.FileExt};
41    NomType={Series.NomType};
42else
43    RootPath=Series.RootPath;
44    RootFile=Series.RootFile;
45    SubDir=Series.SubDir;
46    NomType=Series.NomType;
47    FileExt=Series.FileExt;
48end   
49ext=FileExt{1};
50form=imformats(ext([2:end]));%test valid Matlab image formats
51testima=0;
52if ~isempty(form)||isequal(lower(ext),'.avi')||isequal(lower(ext),'.vol')
53    testima(1)=1;
54end
55if length(FileExt)>=2
56    ext_1=FileExt{2};
57    form=imformats(ext_1([2:end]));%test valid Matlab image formats
58    if ~isempty(form)||isequal(lower(ext_1),'.avi')||isequal(lower(ext_1),'.vol')
59        testima(2)=1;
60    end
61    if testima(2)~=testima(1)
62        msgbox_uvmat('ERROR','images and netcdf files cannot be compared')
63        return
64    end
65end
66
67%Number of input series: this function  accepts two input file series at most (then it operates on the difference of fields)
68nbview=length(RootPath);
69if nbview>2 
70    RootPath=RootPath(1:2);
71    set(hseries.RootPath,'String',RootPath)
72    SubDir=SubDir(1:2);
73    set(hseries.SubDir,'String',SubDir)
74    RootFile=RootFile(1:2);
75    set(hseries.RootFile,'String',RootFile)
76    NomType=NomType(1:2);
77    FileExt=FileExt(1:2);
78    set(hseries.FileExt,'String',FileExt)
79    nbview=2;
80end
81hhh=which('mmreader');
82for iview=1:nbview
83    test_movie(iview)=0;
84    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
85        if isequal(lower(FileExt{iview}),'.avi')
86            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
87            test_movie(iview)=1;
88        end
89    end
90end
91
92% number of slices
93NbSlice=str2num(get(hseries.NbSlice,'String'));
94if isempty(NbSlice)
95    NbSlice=1;
96end
97NbSlice_name=num2str(NbSlice);
98
99% Field and velocity type (the same for the two views)
100Field_str=get(hseries.FieldMenu,'String');
101FieldName=[]; %default
102testfield=get(hseries.FieldMenu,'Visible');
103if isequal(testfield,'on')
104    val=get(hseries.FieldMenu,'Value');
105    FieldName=Field_str(val);%the same set of fields for all views
106    if isequal(FieldName,{'get_field...'})
107        hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
108        if length(hget_field)>1
109            delete(hget_field(2:end))
110        elseif isempty(hget_field)
111           filename=...
112                 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});
113           get_field(filename);
114           return
115        end
116        %hhget_field=guidata(hget_field);%handles of GUI elements in get_field
117        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
118    end
119end
120%detect whether the two files are 'images' or 'netcdf'
121testima=0;
122testvol=0;
123testcivx=0;
124testnc=0;
125FileExt=get(hseries.FileExt,'String');
126% test_movie=0;
127for iview=1:nbview
128     ext=FileExt{iview};
129     form=imformats(ext([2:end]));
130     if isequal(lower(ext),'.vol')
131         testvol=testvol+1;
132     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
133         testima=testima+1;
134     elseif isequal(ext,'.nc')
135         testnc=testnc+1;
136     end
137end
138if testvol
139    msgbox_uvmat('ERROR','volume images not implemented yet')
140    return
141end
142if testnc~=nbview && testima~=nbview && testvol~=nbview
143    msgbox_uvmat('ERROR','compare two image series or two netcdf files with the same fields as input')
144    return
145end
146if ~isequal(FieldName,{'get_field...'})
147    testcivx=testnc;
148end
149
150if testcivx
151    VelType_str=get(hseries.VelTypeMenu,'String');
152    VelType_val=get(hseries.VelTypeMenu,'Value');
153    VelType{1}=VelType_str{VelType_val};
154    if nbview==2
155        VelType_str=get(hseries.VelTypeMenu_1,'String');
156        VelType_val=get(hseries.VelTypeMenu_1,'Value');
157        VelType{2}=VelType_str{VelType_val};
158    end
159end
160
161%Calibration data and timing: read the ImaDoc files
162mode=''; %default
163timecell={};
164itime=0;
165NbSlice_calib={};
166for iview=1:nbview%Loop on views
167    XmlData{iview}=[];%default
168    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
169    if exist([filebase{iview} '.xml'],'file')
170        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
171        if isfield(XmlData{iview},'Time')
172            itime=itime+1;
173            timecell{itime}=XmlData{iview}.Time;
174        end
175        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
176            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
177            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
178                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
179            end
180        end
181    elseif exist([filebase{iview} '.civ'],'file')
182        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
183        itime=itime+1;
184        timecell{itime}=time;
185        XmlData{iview}.Time=time;
186        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
187        GeometryCalib.Tx=0;
188        GeometryCalib.Ty=0;
189        GeometryCalib.Tz=1;
190        GeometryCalib.dpx=1;
191        GeometryCalib.dpy=1;
192        GeometryCalib.sx=1;
193        GeometryCalib.Cx=0;
194        GeometryCalib.Cy=0;
195        GeometryCalib.f=1;
196        GeometryCalib.kappa1=0;
197        GeometryCalib.CoordUnit='cm';
198        XmlData{iview}.GeometryCalib=GeometryCalib;
199        if error==1
200            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
201        end
202    end
203end
204
205%check coincidence in time
206multitime=0;
207if length(timecell)==0
208    time=[];
209elseif length(timecell)==1
210    time=timecell{1};
211elseif length(timecell)>1
212    multitime=1;
213    for icell=1:length(timecell)
214        if ~isequal(size(timecell{icell}),size(timecell{1}))
215            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
216            time=timecell{1};
217            multitime=0;
218            break
219        end
220    end
221end
222if multitime
223    for icell=1:length(timecell)
224        time(icell,:,:)=timecell{icell};
225    end
226    diff_time=max(max(diff(time)));
227    if diff_time>0
228        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
229    end   
230end
231if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
232    time=[];
233end
234
235% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
236subdir_result='aver_stat';
237% filebasesub=fullfile(RootPath{1},subdir_result,RootFile{1});
238% if isempty(SubDir{1}) % create a subdirectory '/aver_stat'
239%     subdir_result='aver_stat';
240%     filebasemean=fullfile(RootPath{1},subdir_result);
241if ~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
249end
250filebase_out=filebase{1};
251% else
252%    subdir_result=SubDir{1};
253%    filebase_out=[filebase{1} '_mean'];% output root name obtained by adding the suffix _mean to the input
254% end
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   
258% if NbSlice==1 
259%     filebase_out=[filebasesub '_mean'];
260% else
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
266% end
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),subdir_result);
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),subdir_result);
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)
461uvmat(filemean)
Note: See TracBrowser for help on using the repository browser.