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

Last change on this file since 356 was 340, checked in by sommeria, 12 years ago

small corrections to fit with the new GUI series;fig

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