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

Last change on this file since 668 was 668, checked in by sommeria, 11 years ago

a few bugs corrected.
multimask introduced in merge_proj
displ_uvmat transformed into disp_uvmat

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