source: trunk/src/series/sub_field_series.m @ 226

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

add function sub_field_series to apply the sub_field operation to a series of fileds (for instance subtracting a background to an image series)

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