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

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

a few bug repairs and update in the series fcts

File size: 19.9 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 GUI_config=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%% calibration data and timing: read the ImaDoc files
133mode=''; %default
134timecell={};
135itime=0;
136NbSlice_calib={};
137XmlData=cell(1,nbview);%initiate the structures containing the data from the xml file (calibration and timing)
138for iview=1:nbview%Loop on views
139    SubDirBase=regexprep(SubDir{iview},'\..*','');%take the root part of SubDir, before the first dot '.'
140    filexml=[fullfile(RootPath{iview},SubDirBase) '.xml'];%new convention: xml at the level of the image folder
141    if ~exist(filexml,'file')
142        filexml=[fullfile(RootPath{iview},SubDir{iview},RootFile{iview}) '.xml']; % old convention: xml inside the image folder
143        if ~exist(filexml,'file')
144            filexml=[fullfile(RootPath{iview},SubDir{iview},RootFile{iview}) '.civ']; % very old convention: .civ file
145            if ~exist(filexml,'file')
146                filexml='';
147            end
148        end
149    end
150    if ~isempty(filexml)
151        [XmlData{iview},error]=imadoc2struct(filexml);
152    end
153    if isfield(XmlData{iview},'Time')
154        itime=itime+1;
155        timecell{itime}=XmlData{iview}.Time;
156    end
157    if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
158        NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
159        if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
160            msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
161        end
162    end
163end
164
165%% check coincidence in time for several input file series
166multitime=0;
167if isempty(timecell)
168    time=[];
169elseif length(timecell)==1
170    time=timecell{1};
171elseif length(timecell)>1
172    multitime=1;
173    for icell=1:length(timecell)
174        if ~isequal(size(timecell{icell}),size(timecell{1}))
175            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
176            time=timecell{1};
177            multitime=0;
178            break
179        end
180    end
181end
182if multitime
183    for icell=1:length(timecell)
184        time(icell,:,:)=timecell{icell};
185    end
186    diff_time=max(max(diff(time)));
187    if diff_time>0
188        msgbox_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)])
189    end   
190end
191if 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'
192    time=[];
193end
194
195%% coordinate transform or other user defined transform
196transform_fct='';%default
197if isfield(Param,'FieldTransform')&&isfield(Param.FieldTransform,'TransformHandle')
198    transform_fct=Param.FieldTransform.TransformHandle;
199end
200%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
201 % EDIT FROM HERE
202
203%% check the validity of  input file types
204if CheckImage{1}
205    FileExtOut='.png'; % write result as .png images for image inputs
206elseif CheckNc{1}
207    FileExtOut='.nc';% write result as .nc files for netcdf inputs
208else
209    msgbox_uvmat('ERROR',['invalid file type input ' FileType{1}])
210    return
211end
212for iview=1:nbview
213        if ~isequal(CheckImage{iview},CheckImage{1})||~isequal(CheckNc{iview},CheckNc{1})
214        msgbox_uvmat('ERROR','input set of input series: need  either netcdf either image series')
215    return
216end
217NomTypeOut=NomType;% output file index will indicate the first and last ref index in the series
218
219%% Set field names and velocity types
220%use Param.InputFields for all views
221
222%% Initiate output fields
223%initiate the output structure as a copy of the first input one (reproduce fields)
224[DataOut,ParamOut,errormsg] = read_field(filecell{1,1},FileType{1},Param.InputFields,1);
225if ~isempty(errormsg)
226    msgbox_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg])
227    return
228end
229time_1=[];
230if isfield(DataOut,'Time')
231    time_1=DataOut.Time(1);
232end
233if CheckNc{iview}
234    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
235        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
236    end
237    DataOut.Conventions='uvmat';
238    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
239    ActionKey='Action';
240    while isfield(DataOut,ActionKey)
241        ActionKey=[ActionKey '_1'];
242    end
243    DataOut.(ActionKey)=Param.Action;
244    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
245    if isfield(DataOut,'Time')
246        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
247    end
248end
249
250%% MAIN LOOP ON SLICES
251%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
252for i_slice=1:NbSlice
253    index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
254    nbfiles=0;
255    nbmissing=0;
256   
257   %initiate result fields
258   
259   for ivar=1:length(DataOut.ListVarName)
260       DataOut.(DataOut.ListVarName{ivar})=0; % initialise all fields to zero
261   end
262
263    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
264    for index=index_slice
265        if checkrun
266            update_waitbar(hseries.waitbar_frame,WaitbarPos,index/(nbfield))
267            stopstate=get(hseries.RUN,'BusyAction');
268        else
269            stopstate='queue';
270        end
271       
272        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
273        Data=cell(1,nbview);%initiate the set Data
274        for iview=1:nbview
275            % reading input file(s)
276            [Data{iview},ParamOut,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
277            if ~isempty(errormsg)
278                errormsg=['error of input reading: ' errormsg];
279                break
280            end
281            if ~isempty(NbSlice_calib)
282                Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
283            end
284         %transform the input field (e.g; phys) if requested
285            if ~isempty(transform_fct)
286                Data{iview}=transform_fct(Data{iview},XmlData{iview});  %transform to phys if requested
287            end
288                        % field calculation (vort, div...)
289            if strcmp(FileType{1},'civx')||strcmp(FileType{1},'civ')
290                Data{iview}=calc_field(Param.InputFields.FieldName,Data{iview});%calculate field (vort..)
291            end
292           
293         %projection on object (gridded plane)
294            if test_object
295                [Data{iview},errormsg]=proj_field(Data{iview},ProjObject);
296                if ~isempty(errormsg)
297                    msgbox_uvmat('ERROR',['error in merge_proge/proj_field: ' errormsg])
298                    return
299                end
300            end
301        end   
302        %----------END LOOP ON VIEWS----------------------
303         
304        %% merge the nbview fields
305        MergeData=merge_field(Data);
306        if isfield(MergeData,'Txt')
307            msgbox_uvmat('ERROR',MergeData.Txt)
308            return
309        end       
310     % generating the name of the merged field
311     i1=i1_series{iview}(index);
312     if ~isempty(i2_series{iview})
313         i2=i2_series{iview}(index);
314     else
315         i2=i1;
316     end
317     j1=1;
318     j2=1;
319     if ~isempty(j1_series{iview})
320         j1=j1_series{iview}(index);
321          if ~isempty(j2_series{iview})
322              j2=j2_series{iview}(index);
323          else
324              j2=j1;
325          end
326     end
327     OutputFile=fullfile_uvmat(RootPath{1},Param.OutputSubDir,RootFile{1},FileExtOut,NomType{1},i1,i2,j1,j2);
328           
329     % time of the merged field:
330        time_i=0;%default
331        if isempty(time)% time from ImaDoc prevails
332            time_i=sum(timeread)/nbtime;
333        else
334           % time_i=i1;
335            time_i=(time(i1,j1)+time(i2,j2))/2; %TODO: upgrade
336        end
337       
338     % recording the merged field
339        if testima    %in case of input images an image is produced   
340            if isa(MergeData.A,'uint8')
341                bitdepth=8;
342            elseif isa(MergeData.A,'uint16')
343                bitdepth=16;
344            end
345            imwrite(MergeData.A,OutputFile,'BitDepth',bitdepth);
346            %write xml calibration file
347            siz=size(MergeData.A);
348            npy=siz(1);
349            npx=siz(2);
350            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
351                Rangx=MergeData.VarAttribute{1}.Coord_2;
352                Rangy=MergeData.VarAttribute{1}.Coord_1;
353            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
354                Rangx=[MergeData.AX(1) MergeData.AX(end)];
355                Rangy=[MergeData.AY(1) MergeData.AY(end)];
356            else
357                Rangx=[0.5 npx-0.5];
358                Rangy=[npy-0.5 0.5];%default
359            end
360            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
361            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
362            T_x=-pxcmx*Rangx(1)+0.5;
363            T_y=-pxcmy*Rangy(2)+0.5;
364            GeometryCal.focal=1;
365            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
366            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
367            ImaDoc.GeometryCalib=GeometryCal;
368            t=struct2xml(ImaDoc);
369            t=set(t,1,'name','ImaDoc');
370            save(t,[filebase_merge '.xml'])     
371            display([filebase_merge '.xml saved'])
372        else
373            MergeData.ListGlobalAttribute={'Conventions','Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
374            MergeData.Conventions='uvmat';
375            MergeData.nb_coord=2;
376            MergeData.nb_dim=2;
377            dt=[];
378            if isfield(Data{1},'dt')&& isnumeric(Data{1}.dt)
379                dt=Data{1}.dt;
380            end
381            for iview =2:numel(Data)
382                if ~(isfield(Data{iview},'dt')&& isequal(Data{iview}.dt,dt))
383                    dt=[];%dt not the same for all fields
384                end
385            end
386            if isempty(dt)
387                MergeData.ListGlobalAttribute(6)=[];
388            else
389               MergeData.dt=dt;
390            end
391            MergeData.Time=time_i;
392            error=struct2nc(OutputFile,MergeData);%save result file
393            if isempty(error)
394                display(['output file ' OutputFile ' written'])
395            else
396                display(error)
397            end
398        end
399    end
400end
401
402%'merge_field': concatene fields
403%------------------------------------------------------------------------
404function MergeData=merge_field(Data)
405%% default output
406if isempty(Data)||~iscell(Data)
407    MergeData=[];
408    return
409end
410MergeData=Data{1};%default
411error=0;
412nbview=length(Data);
413if nbview==1
414    return
415end
416
417%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
418[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
419%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
420% CellVarIndex=cells of variable index arrays
421ivar_new=0; % index of the current variable in the projected field
422for icell=1:length(CellVarIndex)
423    if NbDim(icell)==1
424        continue
425    end
426    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
427    VarType=VarTypeCell{icell};
428    ivar_X=VarType.coord_x;
429    ivar_Y=VarType.coord_y;
430    ivar_FF=VarType.errorflag;
431    if isempty(ivar_X)
432        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
433    else
434        if length(ivar_Y)~=1
435                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
436                return
437        end
438        test_grid=0;
439    end
440    %case of input fields with unstructured coordinates
441    if ~test_grid
442        for ivar=VarIndex
443            VarName=MergeData.ListVarName{ivar};
444            for iview=1:nbview
445                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
446            end
447        end
448    %case of fields defined on a structured  grid
449    else 
450        testFF=0;
451        for iview=2:nbview
452            for ivar=VarIndex
453                VarName=MergeData.ListVarName{ivar};
454                if isfield(MergeData,'VarAttribute')
455                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
456                        testFF=1;
457                    end
458                end
459                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
460            end
461        end
462        if testFF
463            nbaver=nbview-MergeData.FF;
464            indgood=find(nbaver>0);
465            for ivar=VarIndex
466                VarName=MergeData.ListVarName{ivar};
467                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
468            end
469        else
470            for ivar=VarIndex
471                VarName=MergeData.ListVarName{ivar};
472                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
473            end   
474        end
475    end
476end
477
478   
Note: See TracBrowser for help on using the repository browser.