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

Last change on this file since 136 was 128, checked in by sommeria, 14 years ago

series: give writting access to the group for all subdirectories produced
uvmat.fig: change of vect and scalar frames (to be consistent with view_field)
uvmat: various cleaning
plot_field: various cleaning to improve axes definition and avoid blinking
geometry_calib: improved dispay of point coordiantes, improved link with dataview for REPLICATE.
struct2nc: repair bug , file was not closed.
cell2tab: cleaning
dataview: improve the browser
civ: solve pb of image naming

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