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

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

aver_stat, ima_levels , sub_background now adapted to the new settings
merge_proj, time_series still need to be modified

File size: 16.9 KB
Line 
1%'aver_stat': calculate field average, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=aver_stat(Param)
4%
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
6%OUTPUT
7% GUI_input=list of options in the GUI series.fig needed for the function
8%
9%INPUT:
10% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
11% In batch mode, Param is the name of the corresponding xml file containing the same information
12% In the absence of input (as activated when the current Action is selected
13% in series), the function ouput GUI_input set the activation of the needed GUI elements
14%
15% Param contains the elements:(use the menu bar command 'export/GUI config' in series to see the current structure Param)
16%    .InputTable: cell of input file names, (several lines for multiple input)
17%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
18%    .OutputSubDir: name of the subdirectory for data outputs
19%    .OutputDir: directory for data outputs, including path
20%    .Action: .ActionName: name of the current activated function
21%             .ActionPath:   path of the current activated function
22%    .IndexRange: set the file or frame indices on which the action must be performed
23%    .FieldTransform: .TransformName: name of the selected transform function
24%                     .TransformPath:   path  of the selected transform function
25%                     .TransformHandle: corresponding function handle
26%    .InputFields: sub structure describing the input fields withfields
27%              .FieldName: name of the field
28%              .VelType: velocity type
29%              .FieldName_1: name of the second field in case of two input series
30%              .VelType_1: velocity type of the second field in case of two input series
31%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
32%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
33
34function GUI_input=aver_stat(Param)
35
36%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
37if ~exist('Param','var') % case with no input parameter
38    GUI_input={'NbViewMax';2;...% max nbre of input file series (default='' , no limitation)
39        'AllowInputSort';'off';...% allow alphabetic sorting of the list of input files (options 'off'/'on', 'off' by default)
40        'NbSlice';'on'; ...%nbre of slices ('off' by default)
41        'VelType';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
42        'FieldName';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
43        'FieldTransform'; 'on';...%can use a transform function
44        'ProjObject';'on';...%can use projection object(option 'off'/'on',
45        'Mask';'off';...%can use mask option   (option 'off'/'on', 'off' by default)
46        'OutputDirExt';'.stat';...%set the output dir extension
47               ''};
48        return
49end
50
51%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
52%% get input parameters, file names and indices
53% BATCH  case: read the xml file for batch case
54if ischar(Param) && ~isempty(find(regexp(Param,'.xml$')))
55    Param=xml2struct(Param);
56    checkrun=0;
57% RUN case: parameters introduced as the input structure Param 
58else
59    hseries=guidata(Param.hseries);%handles of the GUI series
60    WaitbarPos=get(hseries.waitbar_frame,'Position');%position of the waitbar on the GUI series
61    checkrun=1; % indicate the RUN option is used
62end
63% get the set of input file names (cell array filecell), and the lists of
64% input file or frame indices i1_series,i2_series,j1_series,j2_series
65
66[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
67
68% filecell{iview,fileindex}: cell array representing the list of file names
69%        iview: line in the table corresponding to a given file series
70%        fileindex: file index within  the file series,
71% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
72% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
73% set of frame indices used for movie or multimage input
74
75
76%% root input file(s) and type
77RootPath=Param.InputTable(:,1);
78RootFile=Param.InputTable(:,3);
79SubDir=Param.InputTable(:,2);
80NomType=Param.InputTable(:,4);
81FileExt=Param.InputTable(:,5);
82
83% numbers of slices and file indices
84NbSlice=1;%default
85if isfield(Param.IndexRange,'NbSlice')
86    NbSlice=Param.IndexRange.NbSlice;
87end
88nbview=numel(i1_series);%number of input file series (lines in InputTable)
89nbfield_j=size(i1_series{1},1); %nb of consecutive fields for the j index (bursts or volume slices)
90nbfield_i=size(i1_series{1},2); %nb of consecutive fields for the i index
91nbfield=nbfield_j*nbfield_i; %total number of files or frames
92nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
93nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
94
95%determine the file type on each line from the first input file
96ImageTypeOptions={'image','multimage','mmreader','video'};
97NcTypeOptions={'netcdf','civx','civdata'};
98   
99for iview=1:nbview
100    if ~exist(filecell{iview,1}','file')
101        msgbox_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'])
102        return
103    end
104    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
105    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
106    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
107    if ~isempty(j1_series{iview})
108        frame_index{iview}=j1_series{iview};
109    else
110        frame_index{iview}=i1_series{iview};
111    end
112end
113
114%% calibration data and timing: read the ImaDoc files
115mode=''; %default
116timecell={};
117itime=0;
118NbSlice_calib={};
119for iview=1:nbview%Loop on views
120    XmlData{iview}=[];%default
121    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
122    if exist([filebase{iview} '.xml'],'file')
123        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
124        if isfield(XmlData{iview},'Time')
125            itime=itime+1;
126            timecell{itime}=XmlData{iview}.Time;
127        end
128        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
129            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
130            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
131                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
132            end
133        end
134    elseif exist([filebase{iview} '.civ'],'file')
135        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
136        itime=itime+1;
137        timecell{itime}=time;
138        XmlData{iview}.Time=time;
139        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
140        GeometryCalib.Tx=0;
141        GeometryCalib.Ty=0;
142        GeometryCalib.Tz=1;
143        GeometryCalib.dpx=1;
144        GeometryCalib.dpy=1;
145        GeometryCalib.sx=1;
146        GeometryCalib.Cx=0;
147        GeometryCalib.Cy=0;
148        GeometryCalib.f=1;
149        GeometryCalib.kappa1=0;
150        GeometryCalib.CoordUnit='cm';
151        XmlData{iview}.GeometryCalib=GeometryCalib;
152        if error==1
153            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
154        end
155    end
156end
157
158%% check coincidence in time for several input file series
159multitime=0;
160if isempty(timecell)
161    time=[];
162elseif length(timecell)==1
163    time=timecell{1};
164elseif length(timecell)>1
165    multitime=1;
166    for icell=1:length(timecell)
167        if ~isequal(size(timecell{icell}),size(timecell{1}))
168            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
169            time=timecell{1};
170            multitime=0;
171            break
172        end
173    end
174end
175if multitime
176    for icell=1:length(timecell)
177        time(icell,:,:)=timecell{icell};
178    end
179    diff_time=max(max(diff(time)));
180    if diff_time>0
181        msgbox_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)])
182    end   
183end
184if size(time,2) < i2_series{1}(end) || size(time,3) < j2_series{1}(end)% time array absent or too short in ImaDoc xml file'
185    time=[];
186end
187
188%% coordinate transform or other user defined transform
189transform_fct='';%default
190if isfield(Param,'FieldTransform')&&isfield(Param.FieldTransform,'TransformHandle')
191    transform_fct=Param.FieldTransform.TransformHandle;
192end
193%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
194 % EDIT FROM HERE
195
196%% check the validity of  input file types
197if CheckImage{1}
198    FileExtOut='.png'; % write result as .png images for image inputs
199elseif CheckNc{1}
200    FileExtOut='.nc';% write result as .nc files for netcdf inputs
201else
202    msgbox_uvmat('ERROR',['invalid file type input ' FileType{1}])
203    return
204end
205if nbview==2 && ~isequal(CheckImage{1},CheckImage{2})
206        msgbox_uvmat('ERROR','input must be two image series or two netcdf file series')
207    return
208end
209NomTypeOut='_1-2_1';% output file index will indicate the first and last ref index in the series
210if NbSlice~=nbfield_j
211    answer=msgbox_uvmat('INPUT_Y-N',['will not average slice by slice: for so cancel and set NbSlice= ' num2str(nbfield_j)]);
212    if ~strcmp(answer,'Yes')
213        return
214    end
215end
216
217%% Set field names and velocity types
218InputFields{1}=[];%default (case of images)
219if isfield(Param,'InputFields')
220    InputFields{1}=Param.InputFields;
221end
222if nbview==2
223    InputFields{2}=[];%default (case of images)
224    if isfield(Param,'InputFields')
225        InputFields{2}=Param.InputFields{1};%default
226        if isfield(Param.InputFields,'FieldName_1')
227            InputFields{2}.FieldName=Param.InputFields.FieldName_1;
228            if isfield(Param.InputFields,'VelType_1')
229                InputFields{2}.VelType=Param.InputFields.VelType_1;
230            end
231        end
232    end
233end
234
235%% Initiate output fields
236%initiate the output structure as a copy of the first input one (reproduce fields)
237[DataOut,ParamOut,errormsg] = read_field(filecell{1,1},FileType{1},InputFields{1},1);
238if ~isempty(errormsg)
239    msgbox_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg])
240    return
241end
242time_1=[];
243if isfield(DataOut,'Time')
244    time_1=DataOut.Time(1);
245end
246if CheckNc{iview}
247    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
248        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
249    end
250    DataOut.Conventions='uvmat';
251    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
252    ActionKey='Action';
253    while isfield(DataOut,ActionKey)
254        ActionKey=[ActionKey '_1'];
255    end
256    DataOut.(ActionKey)=Param.Action;
257    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
258    if isfield(DataOut,'Time')
259        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
260    end
261end
262
263%% MAIN LOOP ON SLICES
264%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
265for i_slice=1:NbSlice
266    index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
267    nbfiles=0;
268    nbmissing=0;
269   
270   %initiate result fields
271   for ivar=1:length(DataOut.ListVarName)
272       DataOut.(DataOut.ListVarName{ivar})=0; % initialise all fields to zero
273   end
274
275    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
276    for index=index_slice
277        if checkrun
278            update_waitbar(hseries.waitbar_frame,WaitbarPos,index/(nbfield))
279            stopstate=get(hseries.RUN,'BusyAction');
280        else
281            stopstate='queue';
282        end
283       
284        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
285        index
286        for iview=1:nbview
287            % reading input file(s)
288            [Data{iview},ParamOut,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
289            if ~isempty(errormsg)
290                errormsg=['error of input reading: ' errormsg];
291                break
292            end
293            if ~isempty(NbSlice_calib)
294                Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
295            end
296        end
297        Field=[]; % initiate the current input field structure
298        %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
299        %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
300        % EDIT FROM HERE
301
302        if isempty(errormsg)     
303            % coordinate transform (or other user defined transform)
304            if ~isempty(transform_fct)
305                if nbview==2
306                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
307                    if isempty(Data{2})
308                        Data(2)=[];
309                    end
310                else
311                    Data{1}=transform_fct(Data{1},XmlData{1});
312                end
313            end
314           
315            % field calculation (vort, div...)
316            if strcmp(FileType{1},'civx')||strcmp(FileType{1},'civ')
317                Data{1}=calc_field(InputFields{1}.FieldName,Data{1});%calculate field (vort..)
318            end
319           
320            % field substration (for two input file series)
321            if length(Data)==2
322                if strcmp(FileType{2},'civx')||strcmp(FileType{2},'civ')
323                    Data{2}=calc_field(InputFields{2}.FieldName,Data{2});%calculate field (vort..)
324                end
325                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
326                if ~isempty(errormsg)
327                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
328                    return
329                end
330            else
331                Field=Data{1};
332            end
333           
334            %field projection on an object
335            if Param.CheckObject
336                [Field,errormsg]=proj_field(Field,ProjObject);
337                if ~isempty(errormsg)
338                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
339                    return
340                end
341            end
342            nbfiles=nbfiles+1;
343           
344            %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
345            %update sum
346            for ivar=1:length(Field.ListVarName)
347                VarName=Field.ListVarName{ivar};
348                sizmean=size(DataOut.(VarName));
349                siz=size(Field.(VarName));
350                if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
351                    msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
352                    return
353                else
354                    DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
355                end
356            end
357            %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
358        else
359            display(errormsg) 
360        end
361    end
362    %%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
363   
364    for ivar=1:length(Field.ListVarName)
365        VarName=Field.ListVarName{ivar};
366        DataOut.(VarName)=DataOut.(VarName)/nbfiles; % normalize the mean
367    end
368    if nbmissing~=0
369        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
370    end
371    if isempty(time) % time read from files  prevails
372        if isfield(Field,'Time')
373            time_end=Field.Time(1);%last time read
374            if ~isempty(time_1)
375                DataOut.Time=time_1;
376                DataOut.Time_end=time_end;
377            end
378        end
379    else  % time from ImaDoc prevails
380        DataOut.Time=time(1,i1_series{1}(1),j1_series{1}(1));
381        DataOut.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
382    end
383   
384    %writing the result file
385    OutputFile=fullfile_uvmat(RootPath{1},Param.OutputSubDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),i_slice,[]);
386    if CheckImage{1} %case of images
387        if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
388            DataOut.A=uint16(DataOut.A);
389            imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
390        else
391            DataOut.A=uint8(DataOut.A);
392            imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
393        end
394        display([OutputFile ' written']);
395    else %case of netcdf input file , determine global attributes
396        errormsg=struct2nc(OutputFile,DataOut); %save result file
397        if isempty(errormsg)
398            display([OutputFile ' written']);
399        else
400            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
401            display(errormsg)
402        end
403    end  % end averaging  loop
404end
405%%%%%%%%%%%%%%%% end loop on slices %%%%%%%%%%%%%%%%
406
407%% open the result file with uvmat (in RUN mode)
408if checkrun
409    hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
410    delete(hget_field)
411    uvmat(OutputFile)% open the last result file with uvmat
412end
Note: See TracBrowser for help on using the repository browser.