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

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

comments added at the head of functions

File size: 18.8 KB
Line 
1%'merge_proj': project and concatene fields, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=merge_proj(num_i1,num_i2,num_j1,num_j2,Series)
4%
5%OUTPUT
6% GUI_input=list of options in the GUI series.fig needed for the function
7%
8%INPUT:
9%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
10%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
11%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
12%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
13%Series: Matlab structure containing information set by the series interface
14%
15function GUI_input=merge_proj(num_i1,num_i2,num_j1,num_j2,Series)
16
17%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
18if ~exist('num_i1','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%-------------------------------------------------
36hseries=guidata(Series.hseries);%handles of the GUI series
37WaitbarPos=get(hseries.waitbar_frame,'Position'); %positiopn of waitbar frame
38%-------------------------------------------------
39
40
41
42%projection object
43test_object=get(hseries.GetObject,'Value');
44if test_object
45    hset_object=findobj(allchild(0),'tag','set_object');
46    ProjObject=read_set_object(guidata(hset_object));
47    if ~isfield(ProjObject,'Style')
48            msgbox_uvmat('ERROR','Undefined projection object style')
49            return
50    end
51    if ~isequal(ProjObject.Style,'plane')
52            msgbox_uvmat('ERROR','The projection object must be a plane')
53            return
54    end
55    %answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
56    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' ProjObject.Style]);
57    if ~isequal(answeryes,'Yes')
58        return
59    end
60end
61
62%numbers of view fields (nbre of inputs in RootPath)
63testcell=iscell(Series.RootFile);
64if ~testcell
65    Series.RootPath={Series.RootPath};
66    Series.RootFile={Series.RootFile};
67    Series.SubDir={Series.SubDir};
68    Series.FileExt={Series.FileExt};
69    Series.NomType={Series.NomType};
70    num_i1={num_i1};
71    num_i2={num_i2};
72    num_j1={num_j1};
73    num_j2={num_j2};
74end
75nbview=length(Series.RootFile);%number of views (file series to merge)
76nbfield=size(num_i1{1},1)*size(num_i1{1},2);%number of fields in the time series
77% transform=Series.CoordType; %  field transform function
78hhh=which('mmreader');
79for iview=1:nbview
80    test_movie(iview)=0;
81    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
82        if isequal(lower(Series.FileExt{iview}),'.avi')
83            MovieObject{iview}=mmreader(fullfile(Series.RootPath{iview},[Series.RootFile{iview} Series.FileExt{iview}]));
84            test_movie(iview)=1;
85        end
86    end
87end
88
89%Calibration data and timing: read the ImaDoc files
90% mode=''; %default
91timecell={};
92itime=0;
93NbSlice_calib={}; %test for z index
94for iview=1:nbview%Loop on views
95    XmlData{iview}=[];%default
96    filebase{iview}=fullfile(Series.RootPath{iview},Series.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
159if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
160    time=[];
161end
162
163% coordinate transform or other user defined transform
164transform_fct=[];%default
165if isfield(Series,'transform_fct')
166    transform_fct=Series.transform_fct;
167end
168
169% Field and velocity type (the same for all views)
170FieldName='';
171if strcmp(get(hseries.FieldMenu,'Visible'),'on')
172Field_str=get(hseries.FieldMenu,'String');
173val=get(hseries.FieldMenu,'Value');
174FieldName=Field_str(val);%the same set of fields for all views
175VelType_str=get(hseries.VelTypeMenu,'String');
176VelType_val=get(hseries.VelTypeMenu,'Value');
177VelType=VelType_str{VelType_val}; %the same for all views
178if strcmp(FieldName,'')
179    msgbox_uvmat('ERROR','no input field defined in FieldMenu')
180elseif strcmp(FieldName,'get_field...')
181    hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
182    SubField=get_field('read_get_field',hObject,eventdata,hget_field); %read the names of the variables to plot in the get_field GUI
183end
184end
185%detect whether all the files are 'images' or 'netcdf'
186testima=0;
187testvol=0;
188testcivx=0;
189testnc=0;
190FileExt=get(hseries.FileExt,'String');
191for iview=1:nbview
192     ext=FileExt{iview};
193     form=imformats(ext(2:end));
194     if isequal(lower(ext),'.vol')
195         testvol=testvol+1;
196     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
197         testima=testima+1;
198     elseif isequal(ext,'.nc')
199         testnc=testnc+1;
200     end
201end
202if testvol
203    msgbox_uvmat('ERROR','volume images not implemented yet')
204    return
205end
206if testnc~=nbview && testima~=nbview && testvol~=nbview
207    msgbox_uvmat('ERROR','need a set of images or a set of netcdf files with the same fields as input')
208    return
209end
210if ~isequal(FieldName,'get_field...')
211    testcivx=testnc;
212end
213
214%name of output files and directory:
215% res_subdir=fullfile(Series.RootPath{1},[Series.SubDir{1} '_STAT']);
216ProjectDir=fileparts(fileparts(Series.RootPath{1}));% preoject directory (GERK)
217prompt={['result directory (in' ProjectDir ')']};
218RootPath=get(hseries.RootPath,'String');
219SubDir=get(hseries.SubDir,'String');
220if isequal(length(RootPath),1)
221    fulldir=RootPath{1};
222    subdir='merge_proj';
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=[];
231    dirlist=sort(Series.RootFile);
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;
247    cd(fulldir);
248    succeed=mkdir(subdir);
249    if succeed
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);
257    else
258        msgbox_uvmat('ERROR',['Cannot create directory ' fulldir])
259        return
260    end
261end
262filebasesub=fullfile(res_subdir,Series.RootFile{1});
263filebase_merge=fullfile(res_subdir,'merged');%root name for the merged files
264
265    %MAIN LOOP
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%          Amerge=0;
271         
272         %----------LOOP ON VIEWS----------------------
273        nbtime=0;
274        for iview=1:nbview
275            %name of the current file
276            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});
277            if ~exist(filename,'file')
278                msgbox_uvmat('ERROR',['missing input file' filename])
279                break
280            end
281
282            %reading the current file
283            if testima
284                if test_movie(iview)
285                    Field{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
286                else
287                    Field{iview}.A=imread(filename);
288                end % TODO: introduce ListVarName
289                npxy=size(Field{iview}.A);
290                Field{iview}.ListVarName={'AX','AY','A'};
291                Field{iview}.VarDimName={'AX','AY',{'AY','AX'}};
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];
294                Field{iview}.CoordUnit='pixel';
295                Field{iview}.AName='image';
296                timeread(iview)=0;
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            % coord transform
314            % z index
315     
316            if ~isempty(NbSlice_calib)
317                Field{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
318            end
319%              Field{iview}.ZIndex=1;
320            if ~isempty(transform_fct)
321                Field{iview}=transform_fct(Field{iview},XmlData{iview});  %transform to phys if requested
322            end
323            if testcivx
324                Field{iview}=calc_field(FieldName,Field{iview});
325            end
326
327            %projection on object (gridded plane)
328            if test_object
329                Field{iview}=proj_field(Field{iview},ProjObject);
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       
341        % generating the name of the merged field
342        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));
343       
344        % time:
345        time_i=0;%default
346        if isempty(time)% time from ImaDoc prevails
347            time_i=sum(timeread)/nbtime;
348        else
349            time_i=(time(iview,num_i1{iview}(ifile),num_j1{iview}(ifile))+time(iview,num_i2{iview}(ifile),num_j2{iview}(ifile)))/2;
350        end
351       
352        % recording the merged field
353        if testima    %in case of input images an image is produced   
354            if isa(MergeData.A,'uint8')
355                bitdepth=8;
356            elseif isa(MergeData.A,'uint16')
357                bitdepth=16;
358            end
359            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
360            %write xml calibration file
361            siz=size(MergeData.A);
362            npy=siz(1);
363            npx=siz(2);
364            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
365                Rangx=MergeData.VarAttribute{1}.Coord_2;
366                Rangy=MergeData.VarAttribute{1}.Coord_1;
367            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
368                Rangx=[MergeData.AX(1) MergeData.AX(end)];
369                Rangy=[MergeData.AY(1) MergeData.AY(end)];
370            else
371                Rangx=[0.5 npx-0.5];
372                Rangy=[npy-0.5 0.5];%default
373            end
374            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
375            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
376            T_x=-pxcmx*Rangx(1)+0.5;
377            T_y=-pxcmy*Rangy(2)+0.5;
378            GeometryCal.focal=1;
379            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
380            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
381            ImaDoc.GeometryCalib=GeometryCal;
382            t=struct2xml(ImaDoc);
383            t=set(t,1,'name','ImaDoc');
384            save(t,[filebase_merge '.xml'])     
385            display([filebase_merge '.xml saved'])
386        else
387            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
388            MergeData.nb_coord=2;
389            MergeData.nb_dim=2;
390            dt=[];
391            if isfield(Field{1},'dt')&& isnumeric(Field{1}.dt)
392                dt=Field{1}.dt;
393            end
394            for iview =2:numel(Field)
395                if ~(isfield(Field{iview},'dt')&& isequal(Field{iview}.dt,dt))
396                    dt=[];%dt not the same for all fields
397                end
398            end
399            if isempty(dt)
400                MergeData.ListGlobalAttribute(6)=[];
401            else
402               MergeData.dt=dt;
403            end
404            %MergeData.dt=1;
405            MergeData.Time=time_i;
406            error=struct2nc(mergename,MergeData);%save result file
407            if isempty(error)
408                display(['output file ' mergename ' written'])
409            else
410                display(error)
411            end
412        end
413    end
414end
415
416%--------------------------------------------------------------------------   
417function MergeData=merge_field(Data)
418% initiate Matlab  structure for physical field
419if isempty(Data)||~iscell(Data)
420    MergeData=[];
421    return
422end
423MergeData=Data{1};%default
424error=0;
425nbview=length(Data);
426if nbview==1
427    return
428end
429% for iview=1:nbview
430%     if ~isequal(MergeData.ListDimName,Data{iview}.ListDimName)
431%         error=1;
432%     end
433%     if ~isequal(MergeData.ListVarName,Data{iview}.ListVarName)
434%         error=1;
435%     end
436% end
437% if error
438%     MergeData.Txt='ERROR: attempt at merging fields of incompatible type';
439%     return
440% end
441%
442%group the variables (fields of 'FieldData') in cells of variables with the same dimensions
443[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
444%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
445% CellVarIndex=cells of variable index arrays
446ivar_new=0; % index of the current variable in the projected field
447for icell=1:length(CellVarIndex)
448    if NbDim(icell)==1
449        continue
450    end
451    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
452    VarType=VarTypeCell{icell};
453    ivar_X=VarType.coord_x;
454    ivar_Y=VarType.coord_y;
455    ivar_FF=VarType.errorflag;
456    if isempty(ivar_X)
457        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
458    else
459        if length(ivar_Y)~=1
460                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
461                return
462        end
463        test_grid=0;
464    end
465    %case of input fields with unstructured coordinates
466    if ~test_grid
467        for ivar=VarIndex
468            VarName=MergeData.ListVarName{ivar};
469            for iview=1:nbview
470                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
471            end
472        end
473    %case of fields defined on a structured  grid
474    else 
475        testFF=0;
476        for iview=2:nbview
477            for ivar=VarIndex
478                VarName=MergeData.ListVarName{ivar};
479                if isfield(MergeData,'VarAttribute')
480                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
481                        testFF=1;
482                    end
483                end
484                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
485            end
486        end
487        if testFF
488            nbaver=nbview-MergeData.FF;
489            indgood=find(nbaver>0);
490            for ivar=VarIndex
491                VarName=MergeData.ListVarName{ivar};
492                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
493            end
494        else
495            for ivar=VarIndex
496                VarName=MergeData.ListVarName{ivar};
497                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
498            end   
499        end
500    end
501end
502   
Note: See TracBrowser for help on using the repository browser.