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

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

fgunctions under series adapted to the renovated GUI series

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