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

Last change on this file since 466 was 464, checked in by sommeria, 13 years ago

a few bug repairs and update in the series fcts

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