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

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

bug corrected in merge_proj

File size: 18.6 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 (TODO: case BATCH ?)
46transform_fct='';%default
47if isfield(Param,'transform_fct') % transform function handle
48    transform_fct=Param.transform_fct;
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 ~isequal(hhh,'')&& mmreader.isPlatformSupported()
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}=proj_field(Field{iview},ProjObject);
322            end
323        end   
324        %----------END LOOP ON VIEWS----------------------
325         
326        %% merge the nbview fields
327        MergeData=merge_field(Field);
328        if isfield(MergeData,'Txt')
329            msgbox_uvmat('ERROR',MergeData.Txt)
330            return
331        end       
332     % generating the name of the merged field
333     if testima
334         ResultExt='.png';
335     else
336         ResultExt=FileExt{iview};
337     end
338     i1=i1_series{iview}(ifile);
339     if ~isempty(i2_series{iview})
340         i2=i2_series{iview}(ifile);
341     else
342         i2=i1;
343     end
344     j1=1;
345     j2=1;
346     if ~isempty(j1_series{iview})
347         j1=j1_series{iview}(ifile);
348          if ~isempty(j2_series{iview})
349              j2=j2_series{iview}(ifile);
350          else
351              j2=j1;
352          end
353     end
354     mergename=fullfile_uvmat(res_subdir,'','merged',ResultExt,NomType{iview},i1,i2,j1,j2);
355    % mergename=name_generator(filebase_merge,i1,j1_series{iview}(ifile),ResultExt,NomType{iview},1,i2_series{iview}(ifile),j2_series{iview}(ifile));
356       
357     % time of the merged field:
358        time_i=0;%default
359        if isempty(time)% time from ImaDoc prevails
360            time_i=sum(timeread)/nbtime;
361        else
362            time_i=i1;
363            %time_i=(time(iview,i1,j1)+time(iview,i2,j2))/2; TODO: upgrade
364        end
365       
366     % recording the merged field
367        if testima    %in case of input images an image is produced   
368            if isa(MergeData.A,'uint8')
369                bitdepth=8;
370            elseif isa(MergeData.A,'uint16')
371                bitdepth=16;
372            end
373            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
374            %write xml calibration file
375            siz=size(MergeData.A);
376            npy=siz(1);
377            npx=siz(2);
378            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
379                Rangx=MergeData.VarAttribute{1}.Coord_2;
380                Rangy=MergeData.VarAttribute{1}.Coord_1;
381            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
382                Rangx=[MergeData.AX(1) MergeData.AX(end)];
383                Rangy=[MergeData.AY(1) MergeData.AY(end)];
384            else
385                Rangx=[0.5 npx-0.5];
386                Rangy=[npy-0.5 0.5];%default
387            end
388            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
389            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
390            T_x=-pxcmx*Rangx(1)+0.5;
391            T_y=-pxcmy*Rangy(2)+0.5;
392            GeometryCal.focal=1;
393            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
394            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
395            ImaDoc.GeometryCalib=GeometryCal;
396            t=struct2xml(ImaDoc);
397            t=set(t,1,'name','ImaDoc');
398            save(t,[filebase_merge '.xml'])     
399            display([filebase_merge '.xml saved'])
400        else
401            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
402            MergeData.nb_coord=2;
403            MergeData.nb_dim=2;
404            dt=[];
405            if isfield(Field{1},'dt')&& isnumeric(Field{1}.dt)
406                dt=Field{1}.dt;
407            end
408            for iview =2:numel(Field)
409                if ~(isfield(Field{iview},'dt')&& isequal(Field{iview}.dt,dt))
410                    dt=[];%dt not the same for all fields
411                end
412            end
413            if isempty(dt)
414                MergeData.ListGlobalAttribute(6)=[];
415            else
416               MergeData.dt=dt;
417            end
418            MergeData.Time=time_i;
419            error=struct2nc(mergename,MergeData);%save result file
420            if isempty(error)
421                display(['output file ' mergename ' written'])
422            else
423                display(error)
424            end
425        end
426    end
427end
428
429%'merge_field': concatene fields
430%------------------------------------------------------------------------
431function MergeData=merge_field(Data)
432%% default output
433if isempty(Data)||~iscell(Data)
434    MergeData=[];
435    return
436end
437MergeData=Data{1};%default
438error=0;
439nbview=length(Data);
440if nbview==1
441    return
442end
443
444%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
445[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
446%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
447% CellVarIndex=cells of variable index arrays
448ivar_new=0; % index of the current variable in the projected field
449for icell=1:length(CellVarIndex)
450    if NbDim(icell)==1
451        continue
452    end
453    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
454    VarType=VarTypeCell{icell};
455    ivar_X=VarType.coord_x;
456    ivar_Y=VarType.coord_y;
457    ivar_FF=VarType.errorflag;
458    if isempty(ivar_X)
459        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
460    else
461        if length(ivar_Y)~=1
462                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
463                return
464        end
465        test_grid=0;
466    end
467    %case of input fields with unstructured coordinates
468    if ~test_grid
469        for ivar=VarIndex
470            VarName=MergeData.ListVarName{ivar};
471            for iview=1:nbview
472                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
473            end
474        end
475    %case of fields defined on a structured  grid
476    else 
477        testFF=0;
478        for iview=2:nbview
479            for ivar=VarIndex
480                VarName=MergeData.ListVarName{ivar};
481                if isfield(MergeData,'VarAttribute')
482                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
483                        testFF=1;
484                    end
485                end
486                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
487            end
488        end
489        if testFF
490            nbaver=nbview-MergeData.FF;
491            indgood=find(nbaver>0);
492            for ivar=VarIndex
493                VarName=MergeData.ListVarName{ivar};
494                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
495            end
496        else
497            for ivar=VarIndex
498                VarName=MergeData.ListVarName{ivar};
499                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
500            end   
501        end
502    end
503end
504
505   
Note: See TracBrowser for help on using the repository browser.