source: trunk/src/series/time_series.m @ 239

Last change on this file since 239 was 228, checked in by sommeria, 14 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: 22.9 KB
Line 
1%'time_series': extract a time series, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=time_series(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=time_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';'two';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
26        'FieldMenu';'two';...% 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 in the GUI series
37WaitbarPos=get(hseries.waitbar_frame,'Position'); %position of the waitbar frame
38
39%% projection object
40test_object=get(hseries.GetObject,'Value');
41if test_object
42    hset_object=findobj(allchild(0),'tag','set_object');
43    ProjObject=read_set_object(guidata(hset_object));
44    %answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
45    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' ProjObject.Style]);
46    if ~isequal(answeryes,'Yes')
47        return
48    end
49else
50    msgbox_uvmat('ERROR','a projection object is needed');
51    return
52end
53
54%% root names
55if iscell(Series.RootPath)
56    RootPath=Series.RootPath;
57    RootFile=Series.RootFile;
58    SubDir=Series.SubDir;
59    FileExt=Series.FileExt;
60    NomType=Series.NomType;
61else
62    RootPath={Series.RootPath};
63    RootFile={Series.RootFile};
64    SubDir={Series.SubDir};
65    FileExt={Series.FileExt};
66    NomType={Series.NomType};
67    num_i1={num_i1};
68    num_i2={num_i2};
69    num_j1={num_j1};
70    num_j2={num_j2};
71end
72ext=FileExt{1};
73form=imformats(ext([2:end]));%test valid Matlab image formats
74testima=0;
75if ~isempty(form)||isequal(lower(ext),'.avi')
76    testima=1;
77end
78nbview=length(RootPath);%number of series (1 or 2)
79nbfield=size(num_i1{1},1)*size(num_i1{1},2); %number of fields in the time series
80
81%Number of input series: this function  accepts only one or two input file series (sub_field is used in the latter case)
82nbview=length(RootPath);
83
84%determine image type
85hhh=which('mmreader');
86for iview=1:nbview
87    if isequal(FileExt{iview},'.nc')||isequal(FileExt{iview},'.cdf')
88        FileType{iview}='netcdf';
89    elseif isequal(lower(FileExt{iview}),'.avi')
90        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
91            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
92            FileType{iview}='movie';
93        else
94            FileType{iview}='avi';
95        end
96    elseif isequal(lower(FileExt{iview}),'.vol')
97        FileType{iview}='vol';
98    else
99       form=imformats(FileExt{iview}(2:end));
100       if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
101           if isequal(NomType{iview},'*');
102               FileType{iview}='multimage';
103           else
104               FileType{iview}='image';
105           end
106       end
107    end
108end
109filebase{1}=fullfile(RootPath{1},RootFile{1});
110
111% number of slices
112NbSlice=str2num(get(hseries.NbSlice,'String'));
113if isempty(NbSlice)
114    NbSlice=1;
115end
116NbSlice_name=num2str(NbSlice);
117
118% Field and velocity type (the same for the two views)
119if isfield(Series,'Field')
120    FieldName=Series.Field;%the same set of fields for all views
121else
122    FieldName={''};
123end
124if isequal(FieldName,{'get_field...'})
125    hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
126    if numel(hget_field)>1
127        delete(hget_field(2:end)) % delete multiple occurerence of the GUI get_fioeld
128    elseif isempty(hget_field)
129       filename=name_generator(filebase{1},num_i1{1}(1),num_j1{1}(1),FileExt{1},NomType{1},1,num_i2{1}(1),num_j2{1}(1),SubDir{1});
130       idetect(iview)=exist(filename,'file');
131       hget_field=get_field(filename);
132       return
133    end
134    SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
135    if isempty(SubField)
136        delete(hget_field)
137       filename=name_generator(filebase{1},num_i1{1}(1),num_j1{1}(1),FileExt{1},NomType{1},1,num_i2{1}(1),num_j2{1}(1),SubDir{1});
138        hget_field=get_field(filename);
139        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
140    end
141end
142
143%detect whether the two files are 'images' or 'netcdf'
144
145testcivx=0;
146FileExt=get(hseries.FileExt,'String');
147if ~isequal(FieldName,{'get_field...'})
148    testcivx=isequal(FileType{1},'netcdf');
149end
150
151VelType_str=get(hseries.VelTypeMenu,'String');
152VelType_val=get(hseries.VelTypeMenu,'Value');
153VelType{1}=VelType_str{VelType_val};
154if nbview==2
155    VelType_str=get(hseries.VelTypeMenu_1,'String');
156    VelType_val=get(hseries.VelTypeMenu_1,'Value');
157    VelType{2}=VelType_str{VelType_val};
158end
159
160%% Calibration data and timing: read the ImaDoc files
161mode=''; %default
162timecell={};
163XmlData={};
164itime=0;
165NbSlice_calib={};
166for iview=1:nbview%Loop on views
167    XmlData{iview}=[];%default
168    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
169    if exist([filebase{iview} '.xml'],'file')
170        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
171        if isfield(XmlData{iview},'Time')
172            itime=itime+1;
173            timecell{itime}=XmlData{iview}.Time;
174        end
175        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
176            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
177            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
178                msgbox_uvmat('WARNING','inconsistent number of Z indices for the field series');
179            end
180        end
181    elseif exist([filebase{iview} '.civ'],'file')
182        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
183        itime=itime+1;
184        timecell{itime}=time;
185        XmlData{iview}.Time=time;
186        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
187        GeometryCalib.Tx=0;
188        GeometryCalib.Ty=0;
189        GeometryCalib.Tz=1;
190        GeometryCalib.dpx=1;
191        GeometryCalib.dpy=1;
192        GeometryCalib.sx=1;
193        GeometryCalib.Cx=0;
194        GeometryCalib.Cy=0;
195        GeometryCalib.f=1;
196        GeometryCalib.kappa1=0;
197        GeometryCalib.CoordUnit='cm';
198        XmlData{iview}.GeometryCalib=GeometryCalib;
199        if error==1
200            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
201        end
202    end
203end
204
205%% check coincidence in time
206multitime=0;
207if isempty(timecell)
208    time=[];
209elseif length(timecell)==1
210    time=timecell{1};
211elseif length(timecell)>1
212    multitime=1;
213    for icell=1:length(timecell)
214        if ~isequal(size(timecell{icell}),size(timecell{1}))
215            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
216            time=timecell{1};
217            multitime=0;
218            break
219        end
220    end
221end
222if multitime
223    for icell=1:length(timecell)
224        time(icell,:,:)=timecell{icell};
225    end
226    diff_time=max(max(diff(time)));
227    if diff_time>0
228        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
229    end   
230end
231if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
232    time=[];
233end
234
235%%  Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
236subdir_result='time_series';
237pathdir=fullfile(RootPath{1},subdir_result);
238while exist(pathdir,'dir')
239    subdir_result=[subdir_result '.0'];
240    pathdir=fullfile(RootPath{1},subdir_result);
241end
242[m1,m2,m3]=mkdir(pathdir);
243if ~isequal(m2,'')
244     msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
245end
246[xx,msg2] = fileattrib(pathdir,'+w','g'); %yield writing access (+w) to user group (g)
247if ~strcmp(msg2,'')
248    msgbox_uvmat('ERROR',['pb of permission for ' pathdir ': ' msg2])%error message for directory creation
249    return
250end
251
252filebase_out=filebase{1};
253NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
254
255%% coordinate transform or other user defined transform
256transform_fct=[];%default
257if isfield(Series,'transform_fct')
258    transform_fct=Series.transform_fct;
259end
260
261%% velocity type
262VelType_str=get(hseries.VelTypeMenu,'String');
263VelType_val=get(hseries.VelTypeMenu,'Value');
264VelType{1}=VelType_str{VelType_val};
265if nbview==2
266    VelType_str=get(hseries.VelTypeMenu_1,'String');
267    VelType_val=get(hseries.VelTypeMenu_1,'Value');
268    VelType{2}=VelType_str{VelType_val};
269end
270
271%% LOOP ON SLICES
272for i_slice=1:NbSlice
273     dt=[];
274     nbmissing=0; %number of undetected files
275     nbfiles=0;
276    %%%%%%%%%%%%%%%%%%%%%%%%%%%%LOOP ON FIELDS IN  A SLICE
277    for ifile=i_slice:NbSlice:nbfield 
278        stopstate=get(hseries.RUN,'BusyAction');
279        if isequal(stopstate,'queue')% enable STOP command
280             update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
281             for iview=1:nbview
282                filename=...
283                           name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),FileExt{iview},NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile),SubDir{iview});
284                idetect(iview)=exist(filename,'file');
285                Data{iview}=[]; %default     
286                if ~isequal(FileType{iview},'netcdf')               
287                    Data{iview}.ListVarName={'A'};
288                    Data{iview}.AName='image';
289                    switch FileType{iview}
290                        case 'movie'
291                            A=read(MovieObject{iview},num_i1{iview}(ifile));
292                        case 'avi'
293                            mov=aviread(filename,num_i1{iview}(ifile));
294                            A=frame2im(mov(1));
295                        case 'vol'
296                            A=imread(filename);
297                        case 'multimage'
298                            A=imread(filename,num_i1{iview}(ifile));
299                        case 'image'
300                            A=imread(filename);
301                    end
302                    Data{iview}.ListVarName={'AY','AX','A'}; %
303                    npy=size(A,1);
304                    npx=size(A,2);
305                    nbcolor=size(A,3);
306                    if nbcolor==3
307                         Data{iview}.VarDimName={'AY','AX',{'AY','AX','rgb'}};
308                    else
309                         Data{iview}.VarDimName={'AY','AX',{'AY','AX'}};
310                    end 
311                    Data{iview}.AY=[npy-0.5 0.5];
312                    Data{iview}.AX=[0.5 npx-0.5];
313                    Data{iview}.A=double(A);
314                    Data{iview}.CoordUnit='pixel';
315                elseif testcivx
316                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
317                else
318                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
319                    Data{iview}.VarAttribute=SubField.VarAttribute;
320                end
321                if ~isempty(NbSlice_calib)  % z index
322                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
323                end
324             end
325             
326             % coordinate transform (or other user defined transform)
327            if ~isempty(transform_fct)
328                 % z index
329                if ~isempty(NbSlice_calib)
330                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;%Zindex for phys transform
331                end
332                if nbview==2
333                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
334                    if isempty(Data{2})
335                        Data(2)=[];
336                    end
337                else
338                    Data{1}=transform_fct(Data{1},XmlData{1});
339                end
340            end     
341            if testcivx
342                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
343            end
344            if length(Data)==2
345                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
346                if ~isempty(errormsg)
347                    msgbox_uvmat('ERROR',['error in time_series/sub_field:' errormsg])
348                    return
349                end
350            else
351                Field=Data{1};
352            end
353            if test_object
354                [Field,errormsg]=proj_field(Field,ProjObject);
355                if ~isempty(errormsg)
356                    msgbox_uvmat('ERROR',['error in time_series/proj_field:' errormsg])
357                    return
358                end
359            end
360            if min(idetect)>=1% the input file(s) have been detected         
361                nbfiles=nbfiles+1;
362                if nbfiles==1 %first field: initiate the time series
363                    RecordData=Field;%default
364                    RecordData.NbDim=Field.NbDim+1; %add the time dimension for plots         
365                    nbvar=length(Field.ListVarName);
366                    if nbvar==0
367                        msgbox_uvmat('ERROR','no input variable selected in get_field')
368                        return
369                    end
370                    testsum=2*ones(1,nbvar);%initiate flag for action on each variable
371                    indexfalse=0;
372                    CoordName={};
373                    indexremove=[];
374                    if isfield(Field,'VarAttribute') % look for coordinate and flag variables   
375                        for ivar=1:nbvar
376                            if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
377                               %Field.ListVarName{ivar}
378                                var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
379                                if isequal(var_role,'errorflag')
380                                    msgbox_uvmat('ERROR','do not handle error flags in time series')
381                                    return                                               
382                                end
383                                if isequal(var_role,'warnflag')                       
384                                    testsum(ivar)=0;  % not recorded variable
385                                    eval(['RecordData=rmfield(RecordData,''' Field.ListVarName{ivar} ''');']);%remove variable
386                                end                 
387                                if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|...
388                                    isequal(var_role,'coord_z')|isequal(var_role,'coord')
389                                    testsum(ivar)=1; %constant coordinates, record without time evolution
390                                end
391                            end
392                            % check whether the variable ivar is a dimension variable
393                            DimCell=Field.VarDimName{ivar};
394                            if ischar(DimCell)
395                                DimCell={DimCell};
396                            end
397                            if numel(DimCell)==1 && isequal(Field.ListVarName{ivar},DimCell{1})%detect dimension variables
398                               testsum(ivar)=1;
399                            end
400                        end
401                    end
402                    for ivar=1:nbvar
403                        if testsum(ivar)==2                     
404                            eval(['RecordData.' Field.ListVarName{ivar} '=[];'])
405                        end
406                    end
407                    RecordData.ListVarName=[{'Time'} RecordData.ListVarName];
408                end
409                for ivar=1:length(Field.ListVarName)
410                    VarName=Field.ListVarName{ivar};
411                    eval(['VarVal=Field.' VarName ';']);
412                    if testsum(ivar)==2% test for recorded variable
413                        eval(['VarVal=Field.' VarName ';']);
414                        if isequal(ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
415                            if isempty(VarVal)
416                                msgbox_uvmat('ERROR',['empty result at frame index ' num2str(num_i1{iview}(ifile))])
417                                return                             
418                            end
419                            VarVal=mean(VarVal,1);
420                        end
421                        VarVal=shiftdim(VarVal,-1); %shift dimension
422                        eval(['RecordData.' VarName '=cat(1,RecordData.' VarName ',VarVal);']);%concanete the current field to the time series   
423                    elseif testsum(ivar)==1% variable representing fixed coordinates
424                        eval(['VarInit=RecordData.' VarName ';']);
425                        if ~isequal(VarVal,VarInit)
426                            msgbox_uvmat('ERROR',['time series requires constant coordinates ' VarName])
427                            return
428                        end
429                    end                 
430                end
431                % time:
432                if isempty(time)% time read in ncfiles
433                   if isfield(Field,'Time')
434                       RecordData.Time(nbfiles,1)=Field.Time;
435                   else
436                       RecordData.Time(nbfiles,1)=nbfiles;%default
437                   end
438                else % time from ImaDoc prevails
439                    RecordData.Time(nbfiles,1)=(time(1,num_i1{1}(ifile),num_j1{1}(ifile))+time(end,num_i2{end}(ifile),num_j2{end}(ifile)))/2;
440                end
441            else
442                nbmissing=nbmissing+1;
443            end
444        end
445    end
446    %remove time for global attributes if exists
447    for iattr=1:numel(RecordData.ListGlobalAttribute)
448        if strcmp(RecordData.ListGlobalAttribute{iattr},'Time')
449            RecordData.ListGlobalAttribute(iattr)=[];
450            break
451        end
452    end
453    for ivar=1:numel(RecordData.ListVarName)
454        VarName=RecordData.ListVarName{ivar};
455        eval(['RecordData.' VarName '=squeeze(RecordData.' VarName ');']) %remove singletons
456    end
457        % add time dimension and update VarDimIndex:
458        for ivar=1:length(Field.ListVarName)
459             DimCell=Field.VarDimName(ivar);
460             if testsum(ivar)==2%variable used as time series
461                  RecordData.VarDimName{ivar}=[{'Time'} DimCell];
462             elseif testsum(ivar)==1
463                 RecordData.VarDimName{ivar}=DimCell;
464             end
465        end
466    indexremove=find(~testsum);
467    if ~isempty(indexremove)
468        RecordData.ListVarName(1+indexremove)=[];
469        RecordData.VarDimName(indexremove)=[];
470        if isfield(RecordData,'Role')&~isempty(RecordData.Role{1})%generaliser aus autres attributs
471            RecordData.Role(1+indexremove)=[];
472        end
473    end
474
475    %shift variable attributes
476    if isfield(RecordData,'VarAttribute')
477        RecordData.VarAttribute=[{[]} RecordData.VarAttribute];
478    end
479    RecordData.VarDimName=[{'Time'} RecordData.VarDimName];
480    RecordData.Action=Series.Action;%name of the processing programme
481   
482    %name of result file
483    [filemean]=...
484               name_generator(filebase_out,num_i1{1}(i_slice),num_j1{1}(i_slice),'.nc','_i1-i2_j1-j2',1,num_i2{end}(ifile),num_j2{end}(ifile),subdir_result);
485    errormsg=struct2nc(filemean,RecordData); %save result file
486    if isempty(errormsg)
487        display([filemean ' written'])
488    else
489        msgbox_uvmat('ERROR',['error in Series/struct2nc' errormsg])
490    end
491end
492
493figure
494haxes=axes;
495
496plot_field(RecordData,haxes)
497hget_field=findobj(allchild(0),'name','get_field');
498if ~isempty(hget_field)
499    delete(hget_field)
500end
501
502get_field(filemean,RecordData)
503   
504%-----------------------------------------------------------------------
505% --- Executes on selection change in CoordType.
506function CoordType_Callback(hObject, eventdata, handles)
507menu_str=get(handles.CoordType,'String');
508ind_coord=get(handles.CoordType,'Value');
509coord_option=menu_str{ind_coord};
510if isequal(coord_option,'more...');
511    fct_name='';
512    if exist('./TMP/current_usr_fct.mat','file')% if a file is found
513        h=load('./TMP/current_usr_fct.mat');
514        if isfield(h,'fct_name');
515            fct_name=h.fct_name;
516        end
517    end
518    prompt = {'Enter the name of the transform function'};
519    dlg_title = 'user defined transform';
520    num_lines= 1;
521    [FileName, PathName, filterindex] = uigetfile( ...
522       {'*.m', ' (*.m)';
523        '*.m',  '.m files '; ...
524        '*.*', 'All Files (*.*)'}, ...
525        'Pick a file', fct_name);
526    fct_name=fullfile(PathName,FileName);
527    addpath(PathName);%add the path to the selected fct
528    [errormsg,date_str]=check_functions;%check whether new functions can oversed the uvmat package A UTILISER
529    if ~exist(fct_name,'file')
530           warndlg(['image procesing fct ' fct_name ' not found'])
531    else
532        transform=FileName(1:end-2);%
533        update_menu(handles.CoordType,transform)%add the selected fct to the menu
534  %      set(handles.mouse_coord,'String',menu([1:end-1])')%update the mouse coord menu
535      %save ('./TMP/current_usr_fct.mat','fct_name');
536    end   
537end
538ind_coord=get(handles.CoordType,'Value');   
539
540%---------------------------------------------------------------------
541% % --- Executes on selection change in ProjObject.
542% function ProjObject_Callback(hObject, eventdata, handles)
543%
544% list_object=get(handles.ProjObject,'String');
545% index=get(handles.ProjObject,'Value');
546% hseries=get(handles.ProjObject,'Parent');
547% SeriesData=get(hseries,'UserData');
548% Obj=SeriesData.ProjObject{index};
549% [SeriesData.hset_object,SeriesData.sethandles]=set_object(SeriesData.ProjObject{index});
550% set(hseries,'UserData',SeriesData);
551
Note: See TracBrowser for help on using the repository browser.