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

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

functions upadated in series

File size: 16.7 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
132[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
133if size(time,1)>1
134    diff_time=max(max(diff(time)));
135    if diff_time>0
136        msgbox_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)])
137    end   
138end
139
140%% coordinate transform or other user defined transform
141transform_fct='';%default
142if isfield(Param,'FieldTransform')&&isfield(Param.FieldTransform,'TransformHandle')
143    transform_fct=Param.FieldTransform.TransformHandle;
144end
145%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
146 % EDIT FROM HERE
147
148%% check the validity of  input file types
149if CheckImage{1}
150    FileExtOut='.png'; % write result as .png images for image inputs
151elseif CheckNc{1}
152    FileExtOut='.nc';% write result as .nc files for netcdf inputs
153else
154    msgbox_uvmat('ERROR',['invalid file type input ' FileType{1}])
155    return
156end
157if nbview==2 && ~isequal(CheckImage{1},CheckImage{2})
158        msgbox_uvmat('ERROR','input must be two image series or two netcdf file series')
159    return
160end
161NomTypeOut='_1-2_1';% output file index will indicate the first and last ref index in the series
162if NbSlice~=nbfield_j
163    answer=msgbox_uvmat('INPUT_Y-N',['will not average slice by slice: for so cancel and set NbSlice= ' num2str(nbfield_j)]);
164    if ~strcmp(answer,'Yes')
165        return
166    end
167end
168
169%% Set field names and velocity types
170InputFields{1}=[];%default (case of images)
171if isfield(Param,'InputFields')
172    InputFields{1}=Param.InputFields;
173end
174if nbview==2
175    InputFields{2}=[];%default (case of images)
176    if isfield(Param,'InputFields')
177        InputFields{2}=Param.InputFields{1};%default
178        if isfield(Param.InputFields,'FieldName_1')
179            InputFields{2}.FieldName=Param.InputFields.FieldName_1;
180            if isfield(Param.InputFields,'VelType_1')
181                InputFields{2}.VelType=Param.InputFields.VelType_1;
182            end
183        end
184    end
185end
186
187%% Initiate output fields
188% %initiate the output structure as a copy of the first input one (reproduce fields)
189% [DataOut,ParamOut,errormsg] = read_field(filecell{1,1},FileType{1},InputFields{1},1);
190% if ~isempty(errormsg)
191%     msgbox_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg])
192%     return
193% end
194% time_1=[];
195% if isfield(DataOut,'Time')
196%     time_1=DataOut.Time(1);
197% end
198% if CheckNc{iview}
199%     if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
200%         DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
201%     end
202%     DataOut.Conventions='uvmat';
203%     DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
204%     ActionKey='Action';
205%     while isfield(DataOut,ActionKey)
206%         ActionKey=[ActionKey '_1'];
207%     end
208%     DataOut.(ActionKey)=Param.Action;
209%     DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
210%     if isfield(DataOut,'Time')
211%         DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
212%     end
213% end
214
215%% MAIN LOOP ON SLICES
216%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
217for i_slice=1:NbSlice
218    index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
219    nbfiles=0;
220    nbmissing=0;
221   
222    %initiate result fields
223%     for ivar=1:length(DataOut.ListVarName)
224%         DataOut.(DataOut.ListVarName{ivar})=0; % initialise all fields to zero
225%     end
226   
227    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
228    for index=index_slice
229        if checkrun
230            update_waitbar(hseries.waitbar_frame,WaitbarPos,index/(nbfield))
231            stopstate=get(hseries.RUN,'BusyAction');
232        else
233            stopstate='queue';
234        end
235       
236        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
237        for iview=1:nbview
238            % reading input file(s)
239            [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
240            if ~isempty(errormsg)
241                errormsg=['error of input reading: ' errormsg];
242                break
243            end
244            if ~isempty(NbSlice_calib)
245                Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
246            end
247        end
248        Field=[]; % initiate the current input field structure
249        %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
250        %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
251        % EDIT FROM HERE
252       
253        if isempty(errormsg)
254            % coordinate transform (or other user defined transform)
255            if ~isempty(transform_fct)
256                if nbview==2
257                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
258                    if isempty(Data{2})
259                        Data(2)=[];
260                    end
261                else
262                    Data{1}=transform_fct(Data{1},XmlData{1});
263                end
264            end
265           
266            % field calculation (vort, div...)
267            if strcmp(FileType{1},'civx')||strcmp(FileType{1},'civ')
268                Data{1}=calc_field(InputFields{1}.FieldName,Data{1});%calculate field (vort..)
269            end
270           
271            % field substration (for two input file series)
272            if length(Data)==2
273                if strcmp(FileType{2},'civx')||strcmp(FileType{2},'civ')
274                    Data{2}=calc_field(InputFields{2}.FieldName,Data{2});%calculate field (vort..)
275                end
276                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
277                if ~isempty(errormsg)
278                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
279                    return
280                end
281            else
282                Field=Data{1};
283            end
284           
285            %field projection on an object
286            if Param.CheckObject
287                [Field,errormsg]=proj_field(Field,Param.ProjObject);
288                if ~isempty(errormsg)
289                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
290                    return
291                end
292            end
293            nbfiles=nbfiles+1;
294           
295            %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
296            %update sum
297            if nbfiles==1 %first field
298                time_1=[];
299                if isfield(Field,'Time')
300                    time_1=Field.Time(1);
301                end
302                DataOut=Field;%default
303                for ivar=1:length(Field.ListVarName)
304                    VarName=Field.ListVarName{ivar};
305                    DataOut.(VarName)=double(DataOut.(VarName));
306                end
307            else   %current field
308                for ivar=1:length(Field.ListVarName)
309                    VarName=Field.ListVarName{ivar};
310                    sizmean=size(DataOut.(VarName));
311                    siz=size(Field.(VarName));
312                    if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
313                        msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
314                        return
315                    else
316                        DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
317                    end
318                end
319            end
320            %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
321        else
322            display(errormsg)
323        end
324    end
325    %%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
326   
327    for ivar=1:length(Field.ListVarName)
328        VarName=Field.ListVarName{ivar};
329        DataOut.(VarName)=DataOut.(VarName)/nbfiles; % normalize the mean
330    end
331    if nbmissing~=0
332        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
333    end
334    if isempty(time) % time is read from files
335        if isfield(Field,'Time')
336            time_end=Field.Time(1);%last time read
337            if ~isempty(time_1)
338                DataOut.Time=time_1;
339                DataOut.Time_end=time_end;
340            end
341        end
342    else  % time from ImaDoc prevails if it exists
343        j1=1;%default
344        if ~isempty(j1_series{1})
345            j1=j1_series{1};
346        end
347        DataOut.Time=time(1,i1_series{1}(1),j1filexml);
348        DataOut.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
349    end
350   
351    %writing the result file
352    OutputFile=fullfile_uvmat(RootPath{1},Param.OutputSubDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),i_slice,[]);
353    if CheckImage{1} %case of images
354        if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
355            DataOut.A=uint16(DataOut.A);
356            imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
357        else
358            DataOut.A=uint8(DataOut.A);
359            imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
360        end
361        display([OutputFile ' written']);
362    else %case of netcdf input file , determine global attributes
363        errormsg=struct2nc(OutputFile,DataOut); %save result file
364        if isempty(errormsg)
365            display([OutputFile ' written']);
366        else
367            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
368            display(errormsg)
369        end
370    end  % end averaging  loop
371end
372%%%%%%%%%%%%%%%% end loop on slices %%%%%%%%%%%%%%%%
373
374%% open the result file with uvmat (in RUN mode)
375if checkrun
376    hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
377    delete(hget_field)
378    uvmat(OutputFile)% open the last result file with uvmat
379end
Note: See TracBrowser for help on using the repository browser.