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

Last change on this file since 148 was 128, checked in by sommeria, 14 years ago

series: give writting access to the group for all subdirectories produced
uvmat.fig: change of vect and scalar frames (to be consistent with view_field)
uvmat: various cleaning
plot_field: various cleaning to improve axes definition and avoid blinking
geometry_calib: improved dispay of point coordiantes, improved link with dataview for REPLICATE.
struct2nc: repair bug , file was not closed.
cell2tab: cleaning
dataview: improve the browser
civ: solve pb of image naming

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