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

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