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

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

geometry_calib is now updated when a new image is viewed by uvmat
imadoc2struct corrected for time reading

File size: 17.7 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    cd(dircur);
237    else
238    msgbox_uvmat('ERROR',['Cannot create directory ' fulldir])
239    return
240    end       
241end
242filebasesub=fullfile(res_subdir,Series.RootFile{1});
243filebase_merge=fullfile(res_subdir,'merged');%root name for the merged files
244
245    %MAIN LOOP
246for ifile=1:nbfield               
247    stopstate=get(hseries.RUN,'BusyAction');
248    if isequal(stopstate,'queue')% enable STOP command from the 'series' interface
249         update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
250%          Amerge=0;
251         
252         %----------LOOP ON VIEWS----------------------
253        nbtime=0;
254        for iview=1:nbview
255            %name of the current file
256            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});
257            if ~exist(filename,'file')
258                msgbox_uvmat('ERROR',['missing input file' filename])
259                break
260            end
261
262            %reading the current file
263            if testima
264                if test_movie(iview)
265                    Field{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
266                else
267                    Field{iview}.A=imread(filename);
268                end % TODO: introduce ListVarName
269                npxy=size(Field{iview}.A);
270                Field{iview}.ListVarName={'AX','AY','A'};
271                Field{iview}.VarDimName={'AX','AY',{'AY','AX'}};
272                Field{iview}.AX=[0.5 npxy(2)-0.5]; % coordinates of the first and last pixel centers
273                Field{iview}.AY=[npxy(1)-0.5 0.5];
274                Field{iview}.CoordType='px';
275                Field{iview}.AName='image';
276                timeread(iview)=0;
277            else
278                if testcivx
279                    [Field{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
280                else
281                    [Field{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
282                    Field{iview}.VarAttribute=SubField.VarAttribute;
283                end
284                if isfield(Field{iview},'Txt')
285                    msgbox_uvmat('ERROR',Field{iview}.Txt)
286                    return
287                end
288                if isfield(Field{iview},'Time')
289                    timeread(iview)=Field{iview}.Time;
290                    nbtime=nbtime+1;
291                end
292            end
293            % coord transform
294            % z index
295     
296            if ~isempty(NbSlice_calib)
297                Field{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1
298            end
299%              Field{iview}.ZIndex=1;
300            if ~isempty(transform_fct)
301                XmlData{iview}.GeometryCalib
302                Field{iview}=transform_fct(Field{iview},XmlData{iview});               
303                %transform to phys if requested
304            end
305            if testcivx
306                Field{iview}=calc_field(FieldName,Field{iview});
307            end
308
309            %projection on object (gridded plane)
310            if test_object
311                Field{iview}=proj_field(Field{iview},ProjObject);
312            end
313        end   
314         %----------END LOOP ON VIEWS----------------------
315         
316        %merge the nbview fields
317        MergeData=merge_field(Field);
318        if isfield(MergeData,'Txt')
319            msgbox_uvmat('ERROR',MergeData.Txt)
320            return
321        end
322       
323        % generating the name of the merged field
324        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));
325       
326        % time:
327        time_i=0;%default
328        if isempty(time)% time from ImaDoc prevails
329            time_i=sum(timeread)/nbtime;
330        else
331            time_i=(time(iview,num_i1{iview}(ifile),num_j1{iview}(ifile))+time(iview,num_i2{iview}(ifile),num_j2{iview}(ifile)))/2;
332        end
333       
334        % recording the merged field
335        if testima    %in case of input images an image is produced   
336            if isa(MergeData.A,'uint8')
337                bitdepth=8;
338            elseif isa(MergeData.A,'uint16')
339                bitdepth=16;
340            end
341            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
342            %write xml calibration file
343            siz=size(MergeData.A);
344            npy=siz(1);
345            npx=siz(2);
346            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
347                Rangx=MergeData.VarAttribute{1}.Coord_2;
348                Rangy=MergeData.VarAttribute{1}.Coord_1;
349            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
350                Rangx=[MergeData.AX(1) MergeData.AX(end)];
351                Rangy=[MergeData.AY(1) MergeData.AY(end)];
352            else
353                Rangx=[0.5 npx-0.5];
354                Rangy=[npy-0.5 0.5];%default
355            end
356            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
357            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
358            T_x=-pxcmx*Rangx(1)+0.5;
359            T_y=-pxcmy*Rangy(2)+0.5;
360            GeometryCal.focal=1;
361            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
362            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
363            ImaDoc.GeometryCalib=GeometryCal;
364            t=struct2xml(ImaDoc);
365            t=set(t,1,'name','ImaDoc');
366            save(t,[filebase_merge '.xml'])     
367            display([filebase_merge '.xml saved'])
368        else
369            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
370            MergeData.nb_coord=2;
371            MergeData.nb_dim=2;
372            dt=[];
373            if isfield(Field{1},'dt')&& isnumeric(Field{1}.dt)
374                dt=Field{1}.dt;
375            end
376            for iview =2:numel(Field)
377                if ~(isfield(Field{iview},'dt')&& isequal(Field{iview}.dt,dt))
378                    dt=[];%dt not the same for all fields
379                end
380            end
381            if isempty(dt)
382                MergeData.ListGlobalAttribute(6)=[];
383            else
384               MergeData.dt=dt;
385            end
386            %MergeData.dt=1;
387            MergeData.Time=time_i;
388            error=struct2nc(mergename,MergeData);%save result file
389            if isempty(error)
390                display(['output file ' mergename ' written'])
391            else
392                display(error)
393            end
394        end
395    end
396end
397
398%--------------------------------------------------------------------------   
399function MergeData=merge_field(Data)
400% initiate Matlab  structure for physical field
401if isempty(Data)||~iscell(Data)
402    MergeData=[];
403    return
404end
405MergeData=Data{1};%default
406error=0;
407nbview=length(Data);
408if nbview==1
409    return
410end
411% for iview=1:nbview
412%     if ~isequal(MergeData.ListDimName,Data{iview}.ListDimName)
413%         error=1;
414%     end
415%     if ~isequal(MergeData.ListVarName,Data{iview}.ListVarName)
416%         error=1;
417%     end
418% end
419% if error
420%     MergeData.Txt='ERROR: attempt at merging fields of incompatible type';
421%     return
422% end
423%
424%group the variables (fields of 'FieldData') in cells of variables with the same dimensions
425[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
426%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
427% CellVarIndex=cells of variable index arrays
428ivar_new=0; % index of the current variable in the projected field
429for icell=1:length(CellVarIndex)
430    if NbDim(icell)==1
431        continue
432    end
433    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
434    VarType=VarTypeCell{icell};
435    ivar_X=VarType.coord_x;
436    ivar_Y=VarType.coord_y;
437    ivar_FF=VarType.errorflag;
438    if isempty(ivar_X)
439        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
440    else
441        if length(ivar_Y)~=1
442                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
443                return
444        end
445        test_grid=0;
446    end
447    %case of input fields with unstructured coordinates
448    if ~test_grid
449        for ivar=VarIndex
450            VarName=MergeData.ListVarName{ivar};
451            for iview=1:nbview
452                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
453            end
454        end
455    %case of fields defined on a structured  grid
456    else 
457        testFF=0;
458        for iview=2:nbview
459            for ivar=VarIndex
460                VarName=MergeData.ListVarName{ivar};
461                if isfield(MergeData,'VarAttribute')
462                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
463                        testFF=1;
464                    end
465                end
466                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
467            end
468        end
469        if testFF
470            nbaver=nbview-MergeData.FF;
471            indgood=find(nbaver>0);
472            for ivar=VarIndex
473                VarName=MergeData.ListVarName{ivar};
474                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
475            end
476        else
477            for ivar=VarIndex
478                VarName=MergeData.ListVarName{ivar};
479                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
480            end   
481        end
482    end
483end
484   
Note: See TracBrowser for help on using the repository browser.