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

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

bug corrected in merge_proj (tansform_fct was not properly transmitted with the new version of series)

File size: 18.7 KB
Line 
1
2
3
4%'merge_proj': project and concatene fields, used with series.fig
5%------------------------------------------------------------------------
6% function GUI_input=merge_proj(Param)
7%
8%OUTPUT
9% GUI_input=list of options in the GUI series.fig needed for the function
10%
11%INPUT:
12% Param: structure containing all the parameters read on the GUI series
13%  or name of the xml file containing these parameters (BATCH case)
14%
15function GUI_input=merge_proj(Param)
16
17%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
18if ~exist('Param','var')
19    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
20        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
21        'RootFile';'on';... %root input file name ('on' by default)
22        'FileExt';'on';... %input file extension ('on' by default)
23        'NomType';'on';...%type of file indexing ('on' by default)
24        'NbSlice';'on'; ...%nbre of slices ('off' by default)
25        'VelTypeMenu';'one';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
26        'FieldMenu';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
27        'CoordType';'on';...%can use a transform function 'off' by default
28        'GetObject';'on';...%can use projection object ,'off' by default
29        %'GetMask';'on'...%can use mask option   ,'off' by default
30        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
31               ''};
32    return %exit the function
33end
34
35%% input parameters:
36% read the xml file for batch case
37if ischar(Param) && ~isempty(find(regexp('Param','.xml$')))
38    Param=xml2struct(Param);
39else % RUN case : parameters introduced as the input structure Param
40    hseries=guidata(Param.hseries);%handles of the GUI series
41    WaitbarPos=get(hseries.waitbar_frame,'Position');% info for the waitbar
42end
43[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
44
45%% coordinate transform or other user defined transform
46transform_fct='';%default
47if isfield(Param,'FieldTransform')&&isfield(Param.FieldTransform,'fct_handle')
48    transform_fct=Param.FieldTransform.fct_handle;
49end
50
51%% projection object
52test_object=get(hseries.GetObject,'Value');
53if test_object
54    hset_object=findobj(allchild(0),'tag','set_object');
55    %ProjObject=read_set_object(guidata(hset_object));
56    ProjObject=read_GUI(hset_object);
57    if ~isfield(ProjObject,'Type')
58            msgbox_uvmat('ERROR','Undefined projection object type')
59            return
60    end
61    if ~isequal(ProjObject.Type,'plane')|| isequal(ProjObject.ProjMode,'projection')
62            msgbox_uvmat('ERROR','The projection object must be a plane with projection mode interp or filter')
63            return
64    end
65    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' ProjObject.Type]);
66    if ~isequal(answeryes,'Yes')
67        return
68    end
69end
70
71%% features of the input fields
72RootPath=Param.InputTable(:,1);
73RootFile=Param.InputTable(:,3);
74SubDir=Param.InputTable(:,2);
75NomType=Param.InputTable(:,4);
76FileExt=Param.InputTable(:,5);
77
78nbview=length(RootFile);%number of views (file series to merge)
79nbfield=size(i1_series{1},1)*size(i1_series{1},2);%number of fields in the time series
80hhh=which('mmreader');
81for iview=1:nbview
82    test_movie(iview)=0;
83    if ~isempty(hhh)
84        if isequal(lower(FileExt{iview}),'.avi')
85            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
86            test_movie(iview)=1;
87        end
88    end
89end
90
91%% Calibration data and timing: read the ImaDoc files
92timecell={};
93itime=0;
94NbSlice_calib={}; %test for z index
95for iview=1:nbview%Loop on views
96    XmlData{iview}=[];%default
97    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
98    if exist([filebase{iview} '.xml'],'file')
99        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
100        if isfield(XmlData{iview},'Time')
101            itime=itime+1;
102            timecell{itime}=XmlData{iview}.Time;
103        end
104        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
105            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);
106            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
107                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
108            end
109        end   
110    elseif exist([filebase{iview} '.civ'],'file')
111        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
112        itime=itime+1;
113        timecell{itime}=time;
114        XmlData{iview}.Time=time;
115        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
116        GeometryCalib.Tx=0;
117        GeometryCalib.Ty=0;
118        GeometryCalib.Tz=1;
119        GeometryCalib.dpx=1;
120        GeometryCalib.dpy=1;
121        GeometryCalib.sx=1;
122        GeometryCalib.Cx=0;
123        GeometryCalib.Cy=0;
124        GeometryCalib.f=1;
125        GeometryCalib.kappa1=0;
126        GeometryCalib.CoordUnit='cm';
127        XmlData{iview}.GeometryCalib=GeometryCalib;
128        if error==1
129            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
130        end
131    end
132end
133
134%% check coincidence in time
135multitime=0;
136if isempty(timecell)
137    time=[];
138elseif length(timecell)==1
139    time=timecell{1};
140elseif length(timecell)>1
141    multitime=1;
142    for icell=1:length(timecell)
143        if ~isequal(size(timecell{icell}),size(timecell{1}))
144            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
145            time=timecell{1};
146            multitime=0;
147            break
148        end
149    end
150end
151if multitime
152    for icell=1:length(timecell)
153        time(icell,:,:)=timecell{icell};
154    end
155    diff_time=max(max(diff(time)));
156    if diff_time>0
157        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
158    end   
159end
160% if size(time,2) < i2_series{1}(end) || size(time,3) < j2_series{1}(end)% ime array absent or too short in ImaDoc xml file'
161%     time=[];
162% end
163
164%% Field and velocity type (the same for all views)
165FieldName='';
166if isfield(Param,'InputFields')&&isfield(Param.InputFields,'FieldMenu') 
167    FieldName=Param.InputFields.FieldMenu;%the same set of fields for all views
168    VelType=Param.InputFields.VelTypeMenu;
169end
170% if strcmp(get(hseries.FieldMenu,'Visible'),'on')
171%     Field_str=get(hseries.FieldMenu,'String');
172%     val=get(hseries.FieldMenu,'Value');
173%     FieldName=Field_str(val);%the same set of fields for all views
174%     VelType_str=get(hseries.VelTypeMenu,'String');
175%     VelType_val=get(hseries.VelTypeMenu,'Value');
176%     VelType=VelType_str{VelType_val}; %the same for all views
177    if strcmp(FieldName,'')
178        msgbox_uvmat('ERROR','no input field defined in FieldMenu')
179    elseif strcmp(FieldName,'get_field...')
180        hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
181        SubField=get_field('read_get_field',hObject,eventdata,hget_field); %read the names of the variables to plot in the get_field GUI
182    end
183% end
184%detect whether all the files are 'images' or 'netcdf'
185testima=0;
186testvol=0;
187testcivx=0;
188testnc=0;
189for iview=1:nbview
190     ext=FileExt{iview};
191     form=imformats(ext(2:end));
192     if isequal(lower(ext),'.vol')
193         testvol=testvol+1;
194     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
195         testima=testima+1;
196     elseif isequal(ext,'.nc')
197         testnc=testnc+1;
198     end
199end
200if testvol
201    msgbox_uvmat('ERROR','volume images not implemented yet')
202    return
203end
204if testnc~=nbview && testima~=nbview && testvol~=nbview
205    msgbox_uvmat('ERROR','need a set of images or a set of netcdf files with the same fields as input')
206    return
207end
208if ~isequal(FieldName,'get_field...')
209    testcivx=testnc;
210end
211
212%% name of output files and directory:
213ProjectDir=fileparts(fileparts(RootPath{1}));% preoject directory (GERK)
214prompt={['result directory (in' ProjectDir ')']};
215% RootPath=get(hseries.RootPath,'String');
216% SubDir=get(hseries.SubDir,'String');
217if isequal(length(RootPath),1)
218    fulldir=RootPath{1};
219    subdir='merge_proj';
220    res_subdir=fullfile(fulldir,subdir);
221else
222    def={fullfile(ProjectDir,'0_RESULTS')};
223    dlgTitle='result directory';
224    lineNo=1;
225    answer=msgbox_uvmat('INPUT_TXT',dlgTitle,def);
226    fulldir=answer{1};
227    subdir=[];
228    dirlist=sort(RootFile);
229    for iview=1:nbview
230        if ~isempty(subdir)
231            subdir=[subdir '-'];
232        end
233        subdir=[subdir dirlist{iview}];
234    end 
235    res_subdir=fullfile(fulldir,subdir);
236end
237ext=FileExt{1};
238if ~exist(fulldir,'dir')
239    msgbox_uvmat('ERROR',['directory ' fulldir ' needs to be created'])
240    return
241end
242if ~exist(res_subdir,'dir')
243    dircur=pwd;
244    cd(fulldir);
245    succeed=mkdir(subdir);
246    if succeed
247        [xx,msg2] = fileattrib(res_subdir,'+w','g'); %yield writing access (+w) to user group (g)
248        if ~strcmp(msg2,'')
249            msgbox_uvmat('ERROR',['pb of permission for ' res_subdir ': ' msg2])%error message for directory creation
250            cd(dircur)
251            return
252        end
253        cd(dircur);
254    else
255        msgbox_uvmat('ERROR',['Cannot create directory ' fulldir])
256        return
257    end
258end
259filebasesub=fullfile(res_subdir,RootFile{1});
260%filebase_merge=fullfile(res_subdir,'merged');%root name for the merged files
261
262%% MAIN LOOP
263for ifile=1:nbfield               
264    stopstate=get(hseries.RUN,'BusyAction');
265    if isequal(stopstate,'queue')% enable STOP command from the 'series' interface
266         update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
267         
268        %% ----------LOOP ON VIEWS----------------------
269        nbtime=0;
270        for iview=1:nbview
271         %name of the current file
272         filename=filecell{iview,ifile};
273          %  filename=name_generator(filebase{iview},i1_series{iview}(ifile),j1_series{iview}(ifile),FileExt{iview},NomType{iview},1,i2_series{iview}(ifile),j2_series{iview}(ifile),SubDir{iview});
274            if ~exist(filename,'file')
275                msgbox_uvmat('ERROR',['missing input file' filename])
276                break
277            end
278            timeread(iview)=0;
279         %reading the current file
280            if testima
281                if test_movie(iview)
282                    Field{iview}.A=read(MovieObject{iview},i1_series{iview}(ifile));
283                else
284                    Field{iview}.A=imread(filename);
285                end % TODO: introduce ListVarName
286                npxy=size(Field{iview}.A);
287                Field{iview}.ListVarName={'AX','AY','A'};
288                Field{iview}.VarDimName={'AX','AY',{'AY','AX'}};
289                Field{iview}.AX=[0.5 npxy(2)-0.5]; % coordinates of the first and last pixel centers
290                Field{iview}.AY=[npxy(1)-0.5 0.5];
291                Field{iview}.CoordUnit='pixel';
292                Field{iview}.AName='image';
293            else
294                if testcivx
295                    [Field{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
296                else
297                    [Field{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
298                    Field{iview}.VarAttribute=SubField.VarAttribute;
299                end
300                if isfield(Field{iview},'Txt')
301                    msgbox_uvmat('ERROR',Field{iview}.Txt)
302                    return
303                end
304                if isfield(Field{iview},'Time')
305                    timeread(iview)=Field{iview}.Time;
306                    nbtime=nbtime+1;
307                end
308            end
309            if ~isempty(NbSlice_calib)
310                Field{iview}.ZIndex=mod(i1_series{iview}(ifile)-1,NbSlice_calib{1})+1;
311            end
312         %transform the input field (e.g; phys) if requested
313            if ~isempty(transform_fct)
314                Field{iview}=transform_fct(Field{iview},XmlData{iview});  %transform to phys if requested
315            end
316            if testcivx
317                Field{iview}=calc_field(FieldName,Field{iview});
318            end
319         %projection on object (gridded plane)
320            if test_object
321                [Field{iview},errormsg]=proj_field(Field{iview},ProjObject);
322                if ~isempty(errormsg)
323                    msgbox_uvmat('ERROR',['error in merge_proge/proj_field: ' errormsg])
324                    return
325                end
326            end
327        end   
328        %----------END LOOP ON VIEWS----------------------
329         
330        %% merge the nbview fields
331        MergeData=merge_field(Field);
332        if isfield(MergeData,'Txt')
333            msgbox_uvmat('ERROR',MergeData.Txt)
334            return
335        end       
336     % generating the name of the merged field
337     if testima
338         ResultExt='.png';
339     else
340         ResultExt=FileExt{iview};
341     end
342     i1=i1_series{iview}(ifile);
343     if ~isempty(i2_series{iview})
344         i2=i2_series{iview}(ifile);
345     else
346         i2=i1;
347     end
348     j1=1;
349     j2=1;
350     if ~isempty(j1_series{iview})
351         j1=j1_series{iview}(ifile);
352          if ~isempty(j2_series{iview})
353              j2=j2_series{iview}(ifile);
354          else
355              j2=j1;
356          end
357     end
358     mergename=fullfile_uvmat(res_subdir,'','merged',ResultExt,NomType{iview},i1,i2,j1,j2);
359    % mergename=name_generator(filebase_merge,i1,j1_series{iview}(ifile),ResultExt,NomType{iview},1,i2_series{iview}(ifile),j2_series{iview}(ifile));
360       
361     % time of the merged field:
362        time_i=0;%default
363        if isempty(time)% time from ImaDoc prevails
364            time_i=sum(timeread)/nbtime;
365        else
366            time_i=i1;
367            %time_i=(time(iview,i1,j1)+time(iview,i2,j2))/2; TODO: upgrade
368        end
369       
370     % recording the merged field
371        if testima    %in case of input images an image is produced   
372            if isa(MergeData.A,'uint8')
373                bitdepth=8;
374            elseif isa(MergeData.A,'uint16')
375                bitdepth=16;
376            end
377            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
378            %write xml calibration file
379            siz=size(MergeData.A);
380            npy=siz(1);
381            npx=siz(2);
382            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
383                Rangx=MergeData.VarAttribute{1}.Coord_2;
384                Rangy=MergeData.VarAttribute{1}.Coord_1;
385            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
386                Rangx=[MergeData.AX(1) MergeData.AX(end)];
387                Rangy=[MergeData.AY(1) MergeData.AY(end)];
388            else
389                Rangx=[0.5 npx-0.5];
390                Rangy=[npy-0.5 0.5];%default
391            end
392            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
393            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
394            T_x=-pxcmx*Rangx(1)+0.5;
395            T_y=-pxcmy*Rangy(2)+0.5;
396            GeometryCal.focal=1;
397            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
398            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
399            ImaDoc.GeometryCalib=GeometryCal;
400            t=struct2xml(ImaDoc);
401            t=set(t,1,'name','ImaDoc');
402            save(t,[filebase_merge '.xml'])     
403            display([filebase_merge '.xml saved'])
404        else
405            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
406            MergeData.nb_coord=2;
407            MergeData.nb_dim=2;
408            dt=[];
409            if isfield(Field{1},'dt')&& isnumeric(Field{1}.dt)
410                dt=Field{1}.dt;
411            end
412            for iview =2:numel(Field)
413                if ~(isfield(Field{iview},'dt')&& isequal(Field{iview}.dt,dt))
414                    dt=[];%dt not the same for all fields
415                end
416            end
417            if isempty(dt)
418                MergeData.ListGlobalAttribute(6)=[];
419            else
420               MergeData.dt=dt;
421            end
422            MergeData.Time=time_i;
423            error=struct2nc(mergename,MergeData);%save result file
424            if isempty(error)
425                display(['output file ' mergename ' written'])
426            else
427                display(error)
428            end
429        end
430    end
431end
432
433%'merge_field': concatene fields
434%------------------------------------------------------------------------
435function MergeData=merge_field(Data)
436%% default output
437if isempty(Data)||~iscell(Data)
438    MergeData=[];
439    return
440end
441MergeData=Data{1};%default
442error=0;
443nbview=length(Data);
444if nbview==1
445    return
446end
447
448%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
449[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
450%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
451% CellVarIndex=cells of variable index arrays
452ivar_new=0; % index of the current variable in the projected field
453for icell=1:length(CellVarIndex)
454    if NbDim(icell)==1
455        continue
456    end
457    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
458    VarType=VarTypeCell{icell};
459    ivar_X=VarType.coord_x;
460    ivar_Y=VarType.coord_y;
461    ivar_FF=VarType.errorflag;
462    if isempty(ivar_X)
463        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
464    else
465        if length(ivar_Y)~=1
466                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
467                return
468        end
469        test_grid=0;
470    end
471    %case of input fields with unstructured coordinates
472    if ~test_grid
473        for ivar=VarIndex
474            VarName=MergeData.ListVarName{ivar};
475            for iview=1:nbview
476                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
477            end
478        end
479    %case of fields defined on a structured  grid
480    else 
481        testFF=0;
482        for iview=2:nbview
483            for ivar=VarIndex
484                VarName=MergeData.ListVarName{ivar};
485                if isfield(MergeData,'VarAttribute')
486                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
487                        testFF=1;
488                    end
489                end
490                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
491            end
492        end
493        if testFF
494            nbaver=nbview-MergeData.FF;
495            indgood=find(nbaver>0);
496            for ivar=VarIndex
497                VarName=MergeData.ListVarName{ivar};
498                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
499            end
500        else
501            for ivar=VarIndex
502                VarName=MergeData.ListVarName{ivar};
503                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
504            end   
505        end
506    end
507end
508
509   
Note: See TracBrowser for help on using the repository browser.