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

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

functions upadated in series

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