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

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

merge_proj corrected to project simulataneously velocity, vort, div...
Time reintroduced correctly
bug corrections for objects

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