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

Last change on this file since 456 was 447, checked in by sommeria, 13 years ago

aver_stat modified in the new rationalized form.
OTHER series FCTS NOT OPERATIONAL

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