source: trunk/src/plot_field.m @ 128

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

series: give writting access to the group for all subdirectories produced
uvmat.fig: change of vect and scalar frames (to be consistent with view_field)
uvmat: various cleaning
plot_field: various cleaning to improve axes definition and avoid blinking
geometry_calib: improved dispay of point coordiantes, improved link with dataview for REPLICATE.
struct2nc: repair bug , file was not closed.
cell2tab: cleaning
dataview: improve the browser
civ: solve pb of image naming

File size: 49.5 KB
Line 
1%'plot_field': plot any field with the structure defined in the uvmat package
2%------------------------------------------------------------------------
3%
4%  This function is used by uvmat to plot fields. It automatically chooses the representation
5% appropriate to the input field structure:
6%     2D vector fields are represented by arrows, 2D scalar fiedlds by grey scale images or contour plots, 1D fields are represented by usual plot with (abscissa, ordinate).
7%  The input field structure is first tested by check_field_structure.m,
8%  then split into blocks of related variables  by find_field_indices.m.
9%  The dimensionality of each block is obtained  by this fuction
10%  considering the presence of variables with the attribute .Role='coord_x'
11%  and/or coord_y and/or coord_z (case of unstructured coordinates), or
12%  dimension variables (case of matrices).
13%
14% function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,htext,PosColorbar)
15%
16% OUPUT:
17% PlotType: type of plot: 'text','line'(curve plot),'plane':2D view,'volume'
18% PlotParamOut: structure, representing the updated  plotting parameters, in case of automatic scaling
19% haxes: handle of the plotting axis, when a new figure is created.
20%
21%INPUT
22%    Data:   structure describing the field to plot
23%         (optional) .ListGlobalAttribute: cell listing the names of the global attributes
24%                    .Att_1,Att_2... : values of the global attributes
25%         (requested)  .ListVarName: list of variable names to select (cell array of  char strings {'VarName1', 'VarName2',...} )
26%         (requested)  .VarDimName: list of dimension names for each element of .ListVarName (cell array of string cells)
27%                      .VarAttribute: cell of attributes for each element of .ListVarName (cell array of structures of the form VarAtt.key=value)
28%         (requested) .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
29
30%            Variable attribute .Role :
31%    The only variable attribute used for plotting purpose is .Role which can take
32%    the values
33%       Role = 'scalar':  (default) represents a scalar field
34%            = 'coord_x', 'coord_y',  'coord_z': represents a separate set of
35%                        unstructured coordinate x, y  or z
36%            = 'vector': represents a vector field whose number of components
37%                is given by the last dimension (called 'nb_dim')
38%            = 'vector_x', 'vector_y', 'vector_z'  :represents the x, y or z  component of a vector 
39%            = 'warnflag' : provides a warning flag about the quality of data in a 'Field', default=0, no warning
40%            = 'errorflag': provides an error flag marking false data,
41%                   default=0, no error. Different non zero values can represent different criteria of elimination.
42%
43%
44%         additional elements characterizing the projection object (should not be necessary)--
45%            Data.Style : style of projection object
46%            Data.XObject,.YObject: set of coordinates defining the object position;
47%            Data.ProjMode=type of projection ;
48%            Data.ProjAngle=angle of projection;
49%            Data.DX,.DY,.DZ=increments;
50%            Data.MaxY,MinY: min and max Y
51
52%   haxes: handle of the plotting axes to update with the new plot. If this input is absent or not a valid axes handle, a new figure is created.
53%
54%   PlotParam: parameters for plotting, as read on the uvmat interface (by function 'read_plot_param.m')
55%     .FixedLimits:=0 (default) adjust axes limit to the X,Y data, =1: preserves the previous axes limits
56%     .Auto_xy: =0 (default): kepp 1 to 1 aspect ratio for x and y scales, =1: automatic adjustment of the graph
57%            --scalars--
58%    .Scalar.MaxA: upper bound (saturation color) for the scalar representation, max(field) by default
59%    .Scalar.MinA: lower bound (saturation) for the scalar representation, min(field) by default
60%    .Scalar.AutoScal: =1 (default) lower and upper bounds of the scalar representation set to the min and max of the field
61%               =0 lower and upper bound imposed by .AMax and .MinA
62%    .Scalar.BW= 1 black and white representation imposed, =0 by default.
63%    .Scalar.Contours= 1: represent scalars by contour plots (Matlab function 'contour'); =0 by default
64%    .IncrA : contour interval
65%            -- vectors--
66%    .Vectors.VecScale: scale for the vector representation
67%    .Vectors.AutoVec: =0 (default) automatic length for vector representation, =1: length set by .VecScale
68%    .Vectors.HideFalse= 0 (default) false vectors represented in magenta, =1: false vectors not represented;
69%    .Vectors.HideWarning= 0 (default) vectors marked by warnflag~=0 marked in black, 1: no warning representation;
70%    .Vectors.decimate4 = 0 (default) all vectors reprtesented, =1: half of  the vectors represented along each coordinate
71%         -- vector color--
72%    .Vectors.ColorCode= 'black','white': imposed color  (default ='blue')
73%                        'rgb', : three colors red, blue, green depending
74%                        on thresholds .colcode1 and .colcode2 on the input  scalar value (C)
75%                        'brg': like rgb but reversed color order (blue, green, red)
76%                        '64 colors': continuous color from blue to red (multijet)
77%    .Vectors.colcode1 : first threshold for rgb, first value for'continuous'
78%    .Vectors.colcode2 : second threshold for rgb, last value (saturation) for 'continuous'
79%    .Vectors.FixedCbounds;  =0 (default): the bounds on C representation are min and max, =1: they are fixed by .Minc and .MaxC
80%    .Vectors.MinC = imposed minimum of the scalar field used for vector color;
81%    .Vectors.MaxC = imposed maximum of the scalar field used for vector color;
82%
83%
84% PosColorbar: if not empty, display a colorbar for B&W images
85%               imposed position of the colorbar (ex [0.821 0.471 0.019 0.445])
86
87%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
88%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
89%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
90%     This file is part of the toolbox UVMAT.
91%
92%     UVMAT is free software; you can redistribute it and/or modify
93%     it under the terms of the GNU General Public License as published by
94%     the Free Software Foundation; either version 2 of the License, or
95%     (at your option) any later version.
96%
97%     UVMAT is distributed in the hope that it will be useful,
98%     but WITHOUT ANY WARRANTY; without even the implied warranty of
99%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
100%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
101%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
102
103function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,htext,PosColorbar)
104% TODO:
105% use htext: handles of the text edit box (uicontrol)
106% introduce PlotParam.Hold: 'on' or 'off' (for curves)
107
108%default output
109if ~exist('PlotParam','var'),PlotParam=[];end;
110if ~exist('htext','var'),htext=[];end;
111if ~exist('PosColorbar','var'),PosColorbar=[];end;
112PlotType='text'; %default
113PlotParamOut=PlotParam;%default
114
115% check input structure
116[Data,errormsg]=check_field_structure(Data);
117
118if ~isempty(errormsg)
119    msgbox_uvmat('ERROR',['input of plot_field/check_field_structure: ' errormsg])
120    display(['input of plot_field/check_field_structure:: ' errormsg])
121    return
122end
123
124testnewfig=1;%test to create a new figure (default)
125testzoomaxes=0;%test for the existence of a zoom secondary figure attached to the plotting axes
126if exist('haxes','var')
127    if ishandle(haxes)
128        if isequal(get(haxes,'Type'),'axes')
129%             axes(haxes)
130            testnewfig=0;
131            AxeData=get(haxes,'UserData');
132            if isfield(AxeData,'ZoomAxes')&& ishandle(AxeData.ZoomAxes)
133                if isequal(get(AxeData.ZoomAxes,'Type'),'axes')
134                    testzoomaxes=1;
135                    zoomaxes=AxeData.ZoomAxes;
136                end
137            end
138        end
139    end
140end
141
142if testnewfig% create a new figure and axes if the plotting axes does not exist
143    hfig=figure;
144%     if isfield(Data,'IndexObj') && isfield(Data,'Style') && isfield(Data,'ProjMode')
145%         figname=[num2str(Data.IndexObj) '-' Data.Style];
146%         set(hfig,'Name',figname)
147%     end
148%     testhandle=0;
149    if isfield(PlotParam,'text_display_1') && ishandle(PlotParam.text_display_1)
150        set(hfig,'UserData',PlotParam)
151%         testhandle=1;
152    end
153    set(hfig,'Units','normalized')
154    set(hfig,'WindowButtonDownFcn','mouse_down')
155    %set(hfig,'WindowButtonMotionFcn',{'mouse_motion',PlotParam})%set mouse action function
156    set(hfig,'WindowButtonMotionFcn','mouse_motion')%set mouse action function
157    set(hfig,'WindowButtonUpFcn','mouse_up')%set mouse action function
158    haxes=axes;
159    set(haxes,'position',[0.13,0.2,0.775,0.73])
160end
161if isfield(PlotParam,'text_display_1') && ishandle(PlotParam.text_display_1)
162    PlotParam=read_plot_param(PlotParam);   
163end
164if testnewfig
165  PlotParam.NextPlot='add'; %parameter for plot_profile and plot_hist
166end
167if isfield(PlotParam,'Auto_xy') && isequal(PlotParam.Auto_xy,1)
168    set(haxes,'DataAspectRatioMode','auto')%automatic aspect ratio
169end
170
171% check the cells of fields :
172% testnbdim=1;
173[CellVarIndex,NbDim,VarType,errormsg]=find_field_indices(Data);
174
175if ~isempty(errormsg)
176    msgbox_uvmat('ERROR',['input of plot_field/find_field_indices: ' errormsg])
177    display(['input of plot_field: ' errormsg])
178    return
179end
180if ~isfield(Data,'NbDim') %& ~isfield(Data,'Style')%determine the space dimensionb if not defined: choose the kind of plot
181    [Data.NbDim]=max(NbDim);
182end
183errormsg=[];
184if isequal(Data.NbDim,0)
185        AxeData=plot_text(Data,htext);
186        PlotType='text';
187        errormsg=[];
188elseif isequal(Data.NbDim,1)
189    [AxeData]=plot_profile(Data,CellVarIndex,VarType,haxes,PlotParam);%
190    if testzoomaxes
191        [AxeData,zoomaxes,PlotParamOut]=plot_profile(Data,CellVarIndex,VarType,zoomaxes,PlotParam);
192        AxeData.ZoomAxes=zoomaxes;
193    end
194    PlotType='line';
195    errormsg=[];
196elseif isequal(Data.NbDim,2)
197    ind_select=find(NbDim>=2);
198    if numel(ind_select)>2
199        errormsg='more than two fields to map';
200    else
201        [AxeData,xx,PlotParamOut,PlotType,errormsg]=plot_plane(Data,CellVarIndex(ind_select),VarType(ind_select),haxes,PlotParam,htext,PosColorbar);
202        if testzoomaxes && isempty(errormsg)
203            [AxeData,zoomaxes,PlotParamOut,xx,errormsg]=plot_plane(Data,CellVarIndex(ind_select),VarType(ind_select),zoomaxes,PlotParam,1,PosColorbar);
204            %AxeData.ZoomAxes=zoomaxes;
205            Data.ZoomAxes=zoomaxes;
206        end
207    end
208elseif isequal(Data.NbDim,3)
209    errormsg='volume plot not implemented yet';
210end
211if ~isempty(errormsg)
212    msgbox_uvmat('ERROR','volume plot not implemented yet')
213    return
214end
215
216%display (or delete) error message
217htext=findobj(haxes,'Tag','hTxt');
218if isfield(Data,'Txt')
219    if isempty(htext)
220        Xlim=get(haxes,'XLim');
221        Ylim=get(haxes,'YLim');
222        htext=text(Xlim(1),(Ylim(1)+Ylim(2))/2,Data.Txt,'Tag','hTxt','Color','r');
223        set(htext,'Interpreter','none')
224    else
225        set(htext,'String',Data.Txt)
226    end
227elseif ~isempty(htext)
228    delete(htext)
229end
230
231% set graph aspect ratio
232if isfield(AxeData,'Mesh')
233    Data.Mesh=AxeData.Mesh;
234end
235
236%set(haxes,'UserData',AxeData)
237set(haxes,'UserData',Data)
238% if ~testnewfig
239% %set(0,'Children',hstack);%put back the initial figure stack after plot creation
240%
241% end
242
243
244%-------------------------------------------------------------------
245function hdisplay=plot_text(FieldData,hdisplay_in)
246%-------------------------------------------------------------------
247if exist('hdisplay_in','var') && ~isempty(hdisplay_in) && ishandle(hdisplay_in) && isequal(get(hdisplay_in,'Type'),'uicontrol')
248    hdisplay=hdisplay_in;
249else
250    figure;%create new figure
251    hdisplay=uicontrol('Style','edit', 'Units','normalized','Position', [0 0 1 1],'Max',2,'FontName','monospaced');
252end
253   
254ff=fields(FieldData);%list of field names
255vv=struct2cell(FieldData);%list of field values
256
257for icell=1:length(vv)
258    Tabcell{icell,1}=ff{icell};
259    ss=vv{icell};
260    sizss=size(ss);
261    if isnumeric(ss)
262        if sizss(1)<=1 && length(ss)<5
263            displ{icell}=num2str(ss);
264        else
265            displ{icell}=[class(ss) ', size ' num2str(size(ss))];
266        end
267    elseif ischar(ss)
268        displ{icell}=ss;
269    elseif iscell(ss)
270        sizcell=size(ss);
271        if sizcell(1)==1 && length(sizcell)==2 %line cell
272           ssline='{''';
273           for icolumn=1:sizcell(2)
274               if isnumeric(ss{icolumn})
275                   if size(ss{icolumn},1)<=1 && length(ss{icolumn})<5
276                      sscolumn=num2str(ss{icolumn});%line vector
277                   else
278                      sscolumn=[class(ss{icolumn}) ', size ' num2str(size(ss{icolumn}))];
279                   end
280               elseif ischar(ss{icolumn})
281                   sscolumn=ss{icolumn};
282               else
283                   sscolumn=class(ss{icolumn});
284               end
285               if icolumn==1
286                   ssline=[ssline sscolumn];
287               else
288                   ssline=[ssline ''',''' sscolumn];
289               end
290           end
291           displ{icell}=[ssline '''}'];
292        else
293           displ{icell}=[class(ss) ', size ' num2str(sizcell)];
294        end
295    else
296        displ{icell}=class(ss);
297    end
298    Tabcell{icell,2}=displ{icell};
299end
300Tabchar=cell2tab(Tabcell,': ');
301set(hdisplay,'String', Tabchar)
302
303
304%-------------------------------------------------------------------
305function [AxeData,haxes]=plot_profile(data,CellVarIndex,VarType,haxes,PlotParam)
306%-------------------------------------------------------------------
307%TODO: modify existing plot if it exists
308
309hfig=get(haxes,'parent');
310AxeData=data;
311
312ColorOrder=[1 0 0;0 0.5 0;0 0 1;0 0.75 0.75;0.75 0 0.75;0.75 0.75 0;0.25 0.25 0.25];
313set(haxes,'ColorOrder',ColorOrder)
314if isfield(PlotParam,'NextPlot')
315    set(haxes,'NextPlot',PlotParam.NextPlot)
316end
317% adjust the size of the plot to include the whole field,
318if isfield(PlotParam,'FixedLimits') && isequal(PlotParam.FixedLimits,1)  %adjust the graph limits*
319    set(haxes,'XLimMode', 'manual')
320    set(haxes,'YLimMode', 'manual')
321else
322    set(haxes,'XLimMode', 'auto')
323    set(haxes,'YLimMode', 'auto')
324end
325legend_str={};
326
327%% prepare the string for plot command
328%initiate  the plot command
329plotstr='hhh=plot(';
330textmean={};
331coord_x_index=[];
332test_newplot=1;
333% hh=findobj(haxes,'tag','plot_line');
334% num_curve=numel(hh);
335% icurve=0;
336
337%loop on input  fields
338for icell=1:length(CellVarIndex)
339    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list data.ListVarName
340    if ~isempty(VarType{icell}.coord_x)
341        coord_x_index=VarType{icell}.coord_x;
342    else
343        coord_x_index_cell=VarType{icell}.coord(1);
344        if isequal(coord_x_index_cell,0)
345            continue  % the cell has no abscissa, skip it
346        end
347        if ~isempty(coord_x_index)&&~isequal(coord_x_index_cell,coord_x_index)
348            continue %all the selected variables must have the same first dimension
349        else
350            coord_x_index=coord_x_index_cell;
351        end
352    end
353    testplot=ones(size(data.ListVarName));%default test for plotted variables
354    xtitle=data.ListVarName{coord_x_index};
355    eval(['coord_x{icell}=data.' data.ListVarName{coord_x_index} ';']);%coordinate variable set as coord_x
356    if isfield(data,'VarAttribute')&& numel(data.VarAttribute)>=coord_x_index && isfield(data.VarAttribute{coord_x_index},'units')
357        xtitle=[xtitle '(' data.VarAttribute{coord_x_index}.units ')'];
358    end
359    eval(['coord_x{icell}=data.' data.ListVarName{coord_x_index} ';']);%coordinate variable set as coord_x
360    testplot(coord_x_index)=0;
361    if ~isempty(VarType{icell}.ancillary')
362        testplot(VarType{icell}.ancillary)=0;
363    end
364    if ~isempty(VarType{icell}.warnflag')
365        testplot(VarType{icell}.warnflag)=0;
366    end
367    if isfield(data,'VarAttribute')
368        VarAttribute=data.VarAttribute;
369        for ivar=1:length(VarIndex)
370            if length(VarAttribute)>=VarIndex(ivar) && isfield(VarAttribute{VarIndex(ivar)},'long_name')
371                plotname{VarIndex(ivar)}=VarAttribute{VarIndex(ivar)}.long_name;
372            else
373                plotname{VarIndex(ivar)}=data.ListVarName{VarIndex(ivar)};%name for display in plot A METTRE
374            end
375        end
376    end
377    %     test_newplot=0;%default
378    %     if num_curve>=icurve+numel(find(testplot(VarIndex)))%update existing curves
379    %         if ~isempty(VarType{icell}.discrete')
380    %             charplot_0='+';
381    %             LineStyle='none';
382    %         else
383    %             charplot_0='none';
384    %             LineStyle='-';
385    %         end
386    %         for ivar=1:length(VarIndex)
387    %             if testplot(VarIndex(ivar))
388    %                 icurve=icurve+1;
389    %                 VarName=data.ListVarName{VarIndex(ivar)};
390    %                 eval(['data.' VarName '=squeeze(data.' VarName ');'])
391    %                 set(hh(icurve),'LineStyle',LineStyle)
392    %                 set(hh(icurve),'Marker',charplot_0)
393    %                 set(hh(icurve),'XData',coord_x{icell})
394    %                 eval(['yy=data.' VarName ';'])
395    %                 set(hh(icurve),'YData',yy);
396    %             end
397    %         end
398    %     else% new plot
399    if ~isempty(VarType{icell}.discrete')
400        charplot_0='''+''';
401    else
402        charplot_0='''-''';
403    end
404    for ivar=1:length(VarIndex)
405        if testplot(VarIndex(ivar))
406            VarName=data.ListVarName{VarIndex(ivar)};
407            eval(['data.' VarName '=squeeze(data.' VarName ');'])
408            plotstr=[plotstr 'coord_x{' num2str(icell) '},data.' VarName ',' charplot_0 ','];
409            eval(['nbcomponent2=size(data.' VarName ',2);']);
410            eval(['nbcomponent1=size(data.' VarName ',1);']);
411            if numel(coord_x{icell})==2
412                coord_x{icell}=linspace(coord_x{icell}(1),coord_x{icell}(2),nbcomponent1);
413            end
414            eval(['varmean=mean(double(data.' VarName '));']);%mean value
415            textmean=[textmean; {[VarName 'mean= ' num2str(varmean,4)]}];
416            if nbcomponent1==1|| nbcomponent2==1
417                legend_str=[legend_str {VarName}]; %variable with one component
418            else  %variable with severals  components
419                for ic=1:min(nbcomponent1,nbcomponent2)
420                    legend_str=[legend_str [VarName '_' num2str(ic)]]; %variable with severals  components
421                end                                                   % labeled by their index (e.g. color component)
422            end
423        end
424    end
425end
426
427%% activate the plot
428if test_newplot && ~isequal(plotstr,'hhh=plot(')
429    plotstr=[plotstr '''tag'',''plot_line'');'];
430                %execute plot (instruction  plotstr) 
431    axes(haxes)% select the plotting axes for plot operation
432    eval(plotstr)
433   
434                %%%%%
435    grid(haxes, 'on')
436    hxlabel=xlabel(xtitle);
437    set(hxlabel,'Interpreter','none')% desable tex interpreter
438    if length(legend_str)>=1
439        hylabel=ylabel(legend_str{end});
440        set(hylabel,'Interpreter','none')% desable tex interpreter
441    end
442    if ~isempty(legend_str)
443        hlegend=findobj(hfig,'Tag','legend');
444        if isempty(hlegend)
445            hlegend=legend(legend_str);
446            txt=ver;
447            Release=txt(1).Release;
448            relnumb=str2num(Release(3:4));
449            if relnumb >= 14
450                set(hlegend,'Interpreter','none')% desable tex interpreter
451            end
452        else
453            legend_old=get(hlegend,'String');
454            if isequal(size(legend_old,1),size(legend_str,1))&&~isequal(legend_old,legend_str)
455                set(hlegend,'String',[legend_old legend_str]);
456            end
457        end
458    end
459    title_str='';
460    if isfield(data,'filename')
461       [Path, title_str, ext]=fileparts(data.filename);
462       title_str=[title_str ext];
463    end
464    if isfield(data,'Action')
465        if ~isequal(title_str,'')
466            title_str=[title_str ', '];
467        end
468        title_str=[title_str data.Action];
469    end
470    htitle=title(title_str);
471    txt=ver;
472    Release=txt(1).Release;
473    relnumb=str2num(Release(3:4));
474    if relnumb >= 14
475        set(htitle,'Interpreter','none')% desable tex interpreter
476    end
477    % A REPRENDRE Mean
478%         hlist=findobj(gcf,'Style','listbox','Tag','liststat');
479%         if isempty(hlist)
480%             'text'
481%             textmean
482%             set(gca,'position',[0.13,0.2,0.775,0.73])
483%             uicontrol('Style','popupmenu','Position',[20 20 200 20],'String',textmean,'Tag','liststat');
484%         else
485%             set(hlist(1),'String',textmean)
486%         end
487end
488
489
490%-------------------------------------------------------------------
491function [AxeData,haxes,PlotParamOut,PlotType,errormsg]=plot_plane(Data,CellVarIndex,VarTypeCell,haxes,PlotParam,htext,PosColorbar)
492%-------------------------------------------------------------------
493
494grid(haxes, 'off')
495%default plotting parameters
496PlotType='plane';%default
497if ~exist('PlotParam','var')
498    PlotParam=[];
499end
500if ~isfield(PlotParam,'Scalar')
501    PlotParam.Scalar=[];
502end
503if ~isfield(PlotParam,'Vectors')
504    PlotParam.Vectors=[];
505end
506PlotParamOut=PlotParam;%default
507hfig=get(haxes,'parent');
508hcol=findobj(hfig,'Tag','Colorbar'); %look for colorbar axes
509hima=findobj(haxes,'Tag','ima');% search existing image in the current axes
510AxeData=get(haxes,'UserData'); %default
511if ~isstruct(AxeData)% AxeData must be a structure
512    AxeData=[];
513end
514AxeData.NbDim=2;
515if isfield(Data,'ObjectCoord')
516    AxeData.ObjectCoord=Data.ObjectCoord;
517end
518errormsg=[];%default
519test_ima=0; %default: test for image or map plot
520test_vec=0; %default: test for vector plots
521test_black=0;
522test_false=0;
523test_C=0;
524XName='';
525x_units='';
526YName='';
527y_units='';
528for icell=1:length(CellVarIndex) % length(CellVarIndex) =1 or 2 (from the calling function)
529    VarType=VarTypeCell{icell};
530    ivar_X=VarType.coord_x; % defines (unique) index for the variable representing unstructured x coordinate (default =[])
531    ivar_Y=VarType.coord_y; % defines (unique)index for the variable representing unstructured y coordinate (default =[])
532    ivar_U=VarType.vector_x; % defines (unique) index for the variable representing x vector component (default =[])
533    ivar_V=VarType.vector_y; % defines (unique) index for the variable representing y vector component (default =[])
534    ivar_C=[VarType.scalar VarType.image VarType.color VarType.ancillary]; %defines index (indices) for the scalar or ancillary fields
535    if numel(ivar_C)>1
536        errormsg= 'error in plot_field: too many scalar inputs';
537        return
538    end
539    ivar_F=VarType.warnflag; %defines index (unique) for warning flag variable
540    ivar_FF=VarType.errorflag; %defines index (unique) for error flag variable
541    ind_coord=find(VarType.coord);
542    if numel(ind_coord)==2
543        VarType.coord=VarType.coord(ind_coord);
544    end
545%     idim_Y=[]; 
546%     test_grid=0;
547    if ~isempty(ivar_U) && ~isempty(ivar_V)% vector components detected
548        if test_vec
549            errormsg='error in plot_field: attempt to plot two vector fields';
550            return
551        else
552            test_vec=1;
553            eval(['vec_U=Data.' Data.ListVarName{ivar_U} ';'])
554            eval(['vec_V=Data.' Data.ListVarName{ivar_V} ';'])
555            if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates or structured ones (then ivar_X and ivar_Y empty)     
556                eval(['vec_X=Data.' Data.ListVarName{ivar_X} ';'])
557                eval(['vec_Y=Data.' Data.ListVarName{ivar_Y} ';'])
558            elseif numel(VarType.coord)==2 && ~isequal(VarType.coord,[0 0]);%coordinates defines by dimension variables
559                eval(['y=Data.' Data.ListVarName{VarType.coord(1)} ';'])
560                eval(['x=Data.' Data.ListVarName{VarType.coord(2)} ';'])
561                if numel(y)==2 % y defined by first and last values on aregular mesh
562                    y=linspace(y(1),y(2),size(vec_U,1));
563                end
564                if numel(x)==2 % y defined by first and last values on aregular mesh
565                    x=linspace(x(1),x(2),size(vec_U,2));
566                end
567                [vec_X,vec_Y]=meshgrid(x,y); 
568            else
569                errormsg='error in plot_field: invalid coordinate definition for vector field';
570                return
571            end
572            if ~isempty(ivar_C)
573                 eval(['vec_C=Data.' Data.ListVarName{ivar_C} ';']) ;
574                 vec_C=reshape(vec_C,1,numel(vec_C));
575                 test_C=1;
576            end
577            if ~isempty(ivar_F)%~(isfield(PlotParam.Vectors,'HideWarning')&& isequal(PlotParam.Vectors.HideWarning,1))
578                if test_vec
579                    eval(['vec_F=Data.' Data.ListVarName{ivar_F} ';']) % warning flags for  dubious vectors
580                    if  ~(isfield(PlotParam.Vectors,'HideWarning') && isequal(PlotParam.Vectors.HideWarning,1))
581                        test_black=1;
582                    end
583                end
584            end
585            if ~isempty(ivar_FF) %&& ~test_false
586                if test_vec% TODO: deal with FF for structured coordinates
587                    eval(['vec_FF=Data.' Data.ListVarName{ivar_FF} ';']) % flags for false vectors
588                end
589            end
590        end
591    elseif ~isempty(ivar_C) %scalar or image
592        if test_ima
593             errormsg='attempt to plot two scalar fields or images';
594            return
595        end
596        eval(['A=squeeze(Data.' Data.ListVarName{ivar_C} ');']) ;% scalar represented as color image
597        test_ima=1;
598        if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates or structured ones (then ivar_X and ivar_Y empty)
599            XName=Data.ListVarName{ivar_X};
600            YName=Data.ListVarName{ivar_Y};
601            eval(['AX=Data.' XName ';'])
602            eval(['AY=Data.' YName ';'])
603            [A,AX,AY]=proj_grid(AX',AY',A',[],[],'np>256');  % interpolate on a grid 
604            if isfield(Data,'VarAttribute')
605                if numel(Data.VarAttribute)>=ivar_X && isfield(Data.VarAttribute{ivar_X},'units')
606                    x_units=['(' Data.VarAttribute{ivar_X}.units ')'];
607                end
608                if numel(Data.VarAttribute)>=ivar_Y && isfield(Data.VarAttribute{ivar_Y},'units')
609                    y_units=['(' Data.VarAttribute{ivar_Y}.units ')'];
610                end
611            end       
612        elseif numel(VarType.coord)==2 %structured coordinates
613            XName=Data.ListVarName{VarType.coord(2)};
614            YName=Data.ListVarName{VarType.coord(1)};
615            eval(['AY=Data.' Data.ListVarName{VarType.coord(1)} ';'])
616            eval(['AX=Data.' Data.ListVarName{VarType.coord(2)} ';'])
617            test_interp_X=0; %default, regularly meshed X coordinate
618            test_interp_Y=0; %default, regularly meshed Y coordinate
619            if isfield(Data,'VarAttribute')
620                if numel(Data.VarAttribute)>=VarType.coord(2) && isfield(Data.VarAttribute{VarType.coord(2)},'units')
621                    x_units=['(' Data.VarAttribute{VarType.coord(2)}.units ')'];
622                end
623                if numel(Data.VarAttribute)>=VarType.coord(1) && isfield(Data.VarAttribute{VarType.coord(1)},'units')
624                    y_units=['(' Data.VarAttribute{VarType.coord(1)}.units ')'];
625                end
626            end 
627            if numel(AY)>2
628                DAY=diff(AY);
629                DAY_min=min(DAY);
630                DAY_max=max(DAY);
631                if sign(DAY_min)~=sign(DAY_max);% =1 for increasing values, 0 otherwise
632                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(1)} ];
633                      return
634                end
635                test_interp_Y=(DAY_max-DAY_min)> 0.0001*abs(DAY_max);
636            end
637            if numel(AX)>2
638                DAX=diff(AX);
639                DAX_min=min(DAX);
640                DAX_max=max(DAX);
641                if sign(DAX_min)~=sign(DAX_max);% =1 for increasing values, 0 otherwise
642                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(2)} ];
643                      return
644                end
645                test_interp_X=(DAX_max-DAX_min)> 0.0001*abs(DAX_max);
646            end 
647            if test_interp_Y         
648                npxy(1)=max([256 floor((AY(end)-AY(1))/DAY_min) floor((AY(end)-AY(1))/DAY_max)]);
649                yI=linspace(AY(1),AY(end),npxy(1));
650                if ~test_interp_X
651                    xI=linspace(AX(1),AX(end),size(A,2));%default
652                    AX=xI;
653                end
654            end
655            if test_interp_X 
656                npxy(1)=max([256 floor((AX(end)-AX(1))/DAX_min) floor((AX(end)-AX(1))/DAX_max)]);
657                xI=linspace(AX(1),AX(end),npxy(2));   
658                if ~test_interp_Y
659                   yI=linspace(AY(1),AY(end),size(A,1));
660                   AY=yI;
661                end
662            end
663            if test_interp_X || test_interp_Y               
664                [AX2D,AY2D]=meshgrid(AX,AY);
665                A=interp2(AX2D,AY2D,double(A),xI,yI');
666            end
667            AX=[AX(1) AX(end)];% keep only the lower and upper bounds for image represnetation
668            AY=[AY(1) AY(end)];
669        else
670            errormsg='error in plot_field: invalid coordinate definition ';
671            return
672        end
673          %x_label=[Data.ListVarName{ivar_X} '(' x_units ')'];
674    end         
675end
676
677%%   image or scalar plot %%%%%%%%%%%%%%%%%%%%%%%%%%
678
679if ~isfield(PlotParam.Scalar,'Contours')
680    PlotParam.Scalar.Contours=0; %default
681end
682PlotParamOut=PlotParam; %default
683if test_ima
684    % distinguish B/W and color images
685    np=size(A);%size of image
686    siz=numel(np);
687    if siz>3
688       errormsg=['unrecognized scalar type: ' num2str(siz) ' dimensions'];
689            return
690    end
691    if siz==3
692        if np(3)==1
693            siz=2;%B W image
694        elseif np(3)==3
695            siz=3;%color image
696        else
697            errormsg=['unrecognized scalar type: ' num2str(np(3)) ' color components'];
698            return
699        end
700    end
701   
702    %set the color map
703    if isfield(PlotParam.Scalar,'BW')
704        BW=PlotParam.Scalar.BW; %test for BW gray scale images
705    else
706        BW=(siz==2) && (isa(A,'uint8')|| isa(A,'uint16'));% non color images represented in gray scale by default
707    end
708   
709    %case of grey level images or contour plot
710    if siz==2
711        if ~isfield(PlotParam.Scalar,'AutoScal')
712            PlotParam.Scalar.AutoScal=0;%default
713        end
714        if ~isfield(PlotParam.Scalar,'MinA')
715            PlotParam.Scalar.MinA=[];%default
716        end
717        if ~isfield(PlotParam.Scalar,'MaxA')
718            PlotParam.Scalar.MaxA=[];%default
719        end
720        if isequal(PlotParam.Scalar.AutoScal,0)||isempty(PlotParam.Scalar.MinA)||~isa(PlotParam.Scalar.MinA,'double')  %correct if there is no numerical data in edit box
721            MinA=double(min(min(A)));
722        else
723            MinA=PlotParam.Scalar.MinA; 
724        end;
725        if isequal(PlotParam.Scalar.AutoScal,0)||isempty(PlotParam.Scalar.MaxA)||~isa(PlotParam.Scalar.MaxA,'double') %correct if there is no numerical data in edit box
726            MaxA=double(max(max(A)));
727        else
728            MaxA=PlotParam.Scalar.MaxA; 
729        end;
730        PlotParamOut.Scalar.MinA=MinA;
731        PlotParamOut.Scalar.MaxA=MaxA;
732       
733        % case of contour plot
734        if isequal(PlotParam.Scalar.Contours,1)
735            if ~isempty(hima) && ishandle(hima)
736                delete(hima)
737            end
738            if ~isfield(PlotParam.Scalar,'IncrA')
739                PlotParam.Scalar.IncrA=NaN;
740            end
741            if isnan(PlotParam.Scalar.IncrA)% | PlotParam.Scalar.AutoScal==0
742                cont=colbartick(MinA,MaxA);
743                intercont=cont(2)-cont(1);%default
744                PlotParamOut.Scalar.IncrA=intercont;
745            else
746               intercont=PlotParam.Scalar.IncrA;
747            end
748            B=A;           
749            abscontmin=intercont*floor(MinA/intercont);
750            abscontmax=intercont*ceil(MaxA/intercont);
751            contmin=intercont*floor(min(min(B))/intercont);
752            contmax=intercont*ceil(max(max(B))/intercont);
753            cont_pos_plus=0:intercont:contmax;
754            cont_pos_min=double(contmin):intercont:-intercont;
755            cont_pos=[cont_pos_min cont_pos_plus];
756            sizpx=(AX(end)-AX(1))/(np(2)-1);
757            sizpy=(AY(1)-AY(end))/(np(1)-1);
758            x_cont=AX(1):sizpx:AX(end); % pixel x coordinates for image display
759            y_cont=AY(1):-sizpy:AY(end); % pixel x coordinates for image display
760            txt=ver;%version of Matlab
761            Release=txt(1).Release;
762            relnumb=str2double(Release(3:4));
763            if relnumb >= 14
764                    vec=linspace(0,1,(abscontmax-abscontmin)/intercont);%define a greyscale colormap with steps intercont
765                map=[vec' vec' vec'];
766                colormap(map);
767                [var,hcontour]=contour(x_cont,y_cont,B,cont_pos);       
768                set(hcontour,'Fill','on')
769                set(hcontour,'LineStyle','none')
770                hold on
771            end
772            [var_p,hcontour_p]=contour(x_cont,y_cont,B,cont_pos_plus,'k-');
773            hold on
774            [var_m,hcontour_m]=contour(x_cont,y_cont,B,cont_pos_min,':');
775            set(hcontour_m,'LineColor',[1 1 1])
776            hold off
777            caxis([abscontmin abscontmax])
778            colormap(map);
779        end
780       
781        % set  colormap for  image display
782        if ~isequal(PlotParam.Scalar.Contours,1) 
783            % rescale the grey levels with min and max, put a grey scale colorbar
784            B=A;
785            if BW
786                vec=linspace(0,1,255);%define a linear greyscale colormap
787                map=[vec' vec' vec'];
788                colormap(map);  %grey scale color map
789            else
790                colormap('default'); % standard faulse colors for div, vort , scalar fields
791            end
792        end
793       
794    % case of color images
795    else
796        if BW
797            B=uint16(sum(A,3));
798        else
799            B=uint8(A);
800        end
801        MinA=0;
802        MaxA=255;
803    end
804   
805    % display usual image
806    if ~isequal(PlotParam.Scalar.Contours,1)     
807        % interpolate field to increase resolution of image display
808        test_interp=1;
809        if max(np) <= 64
810            npxy=8*np;% increase the resolution 8 times
811        elseif max(np) <= 128
812            npxy=4*np;% increase the resolution 4 times
813        elseif max(np) <= 256
814            npxy=2*np;% increase the resolution 2 times
815        else
816            npxy=np;
817            test_interp=0; % no interpolation done
818        end
819        if test_interp==1%if we interpolate   
820            x=linspace(AX(1),AX(2),np(2));
821            y=linspace(AY(1),AY(2),np(1));
822            [X,Y]=meshgrid(x,y);
823            xi=linspace(AX(1),AX(2),npxy(2));
824            yi=linspace(AY(1),AY(2),npxy(1));
825            B = interp2(X,Y,double(B),xi,yi');
826        end           
827        % create new image if there  no image handle is found
828        if isempty(hima)
829           % axes(haxes)% set haxes the current axes for image creation
830            set(hfig,'CurrentAxes',haxes) % set haxes the current axes for image creation
831            tag=get(haxes,'Tag');
832            if MinA<MaxA
833                hima=imagesc(AX,AY,B,[MinA MaxA]);
834            else % to deal with uniform field
835                hima=imagesc(AX,AY,B,[MaxA-1 MaxA]);
836            end
837            set(hima,'Tag','ima','HitTest','off')
838            set(haxes,'Tag',tag);%preserve the axes tag (removed by image fct !!!)           
839        % update an existing image
840        else
841            set(hima,'CData',B);
842            if MinA<MaxA
843                caxis([MinA MaxA])
844            else
845                caxis([MaxA-1 MaxA])
846            end
847            set(hima,'XData',AX);
848            set(hima,'YData',AY);
849        end
850    end
851    if ~isstruct(AxeData)
852        AxeData=[];
853    end
854    AxeData.A=A;
855    AxeData.AX=[AX(1) AX(end)];
856    AxeData.AY=[AY(1) AY(end)];
857    test_ima=1;
858   
859    %display the colorbar code for B/W images if Poscolorbar not empty
860    if siz==2 && exist('PosColorbar','var')&& ~isempty(PosColorbar)
861        if isempty(hcol)||~ishandle(hcol)
862             hcol=colorbar;%create new colorbar
863        end
864        if length(PosColorbar)==4
865                 set(hcol,'Position',PosColorbar)           
866        end
867        %YTick=0;%default
868        if MaxA>MinA
869            if isequal(PlotParam.Scalar.Contours,1)
870                colbarlim=get(hcol,'YLim');
871                scale_bar=(colbarlim(2)-colbarlim(1))/(abscontmax-abscontmin);               
872                YTick=cont_pos(2:end-1);
873                YTick_scaled=colbarlim(1)+scale_bar*(YTick-abscontmin);
874                set(hcol,'YTick',YTick_scaled);
875            elseif (isfield(PlotParam.Scalar,'BW') && isequal(PlotParam.Scalar.BW,1))||isa(A,'uint8')|| isa(A,'uint16')%images
876                hi=get(hcol,'children');
877                if iscell(hi)%multiple images in colorbar
878                    hi=hi{1};
879                end
880                set(hi,'YData',[MinA MaxA])
881                set(hi,'CData',(1:256)')
882                set(hcol,'YLim',[MinA MaxA])
883                YTick=colbartick(MinA,MaxA);
884                set(hcol,'YTick',YTick)               
885            else
886                hi=get(hcol,'children');
887                if iscell(hi)%multiple images in colorbar
888                    hi=hi{1};
889                end
890                set(hi,'YData',[MinA MaxA])
891                set(hi,'CData',(1:64)')
892                YTick=colbartick(MinA,MaxA);
893                set(hcol,'YLim',[MinA MaxA])
894                set(hcol,'YTick',YTick)
895            end
896            set(hcol,'Yticklabel',num2str(YTick'));
897        end
898    elseif ishandle(hcol)
899        delete(hcol); %erase existing colorbar if not needed
900    end
901else%no scalar plot
902    if ~isempty(hima) && ishandle(hima)
903        delete(hima)
904    end
905    if ~isempty(hcol)&& ishandle(hcol)
906       delete(hcol)
907    end
908    AxeData.A=[];
909    AxeData.AX=[];
910    AxeData.AY=[];
911    PlotParamOut=rmfield(PlotParamOut,'Scalar');
912end
913
914%%   vector plot %%%%%%%%%%%%%%%%%%%%%%%%%%
915if test_vec
916   %vector scale representation
917    if size(vec_U,1)==numel(vec_Y) && size(vec_U,2)==numel(vec_X); % x, y  coordinate variables
918        [vec_X,vec_Y]=meshgrid(vec_X,vec_Y);
919    end   
920    vec_X=reshape(vec_X,1,numel(vec_X));%reshape in matlab vectors
921    vec_Y=reshape(vec_Y,1,numel(vec_Y));
922    vec_U=reshape(vec_U,1,numel(vec_U));
923    vec_V=reshape(vec_V,1,numel(vec_V));
924    MinMaxX=max(vec_X)-min(vec_X);
925    MinMaxY=max(vec_Y)-min(vec_Y);
926    AxeData.Mesh=sqrt((MinMaxX*MinMaxY)/length(vec_X));
927    if  ~isfield(PlotParam.Vectors,'AutoVec') || isequal(PlotParam.Vectors.AutoVec,0)|| ~isfield(PlotParam.Vectors,'VecScale')...
928               ||isempty(PlotParam.Vectors.VecScale)||~isa(PlotParam.Vectors.VecScale,'double') %automatic vector scale
929%         scale=[];
930        if test_false %remove false vectors
931            indsel=find(AxeData.FF==0);%indsel =indices of good vectors
932        else     
933            indsel=[1:numel(vec_X)];%
934        end
935        if isempty(vec_U)
936            scale=1;
937        else
938            if isempty(indsel)
939                MaxU=max(abs(vec_U));
940                MaxV=max(abs(vec_V));
941            else
942                MaxU=max(abs(vec_U(indsel)));
943                MaxV=max(abs(vec_V(indsel)));
944            end
945            scale=MinMaxX/(max(MaxU,MaxV)*50);
946            PlotParam.Vectors.VecScale=scale;%update the 'scale' display
947        end
948    else
949        scale=PlotParam.Vectors.VecScale;  %impose the length of vector representation
950    end;
951   
952    %record vectors on the plotting axes
953    if test_C==0
954        vec_C=ones(1,numel(vec_X));
955    end
956    AxeData.X=vec_X';
957    AxeData.Y=vec_Y';
958    AxeData.U=vec_U';
959    AxeData.V=vec_V';
960    AxeData.C=vec_C';
961    if isempty(ivar_F)
962        AxeData.F=[];
963    else
964        AxeData.F=vec_F';
965    end
966    if isempty(ivar_FF)
967        AxeData.FF=[];
968    else
969        AxeData.FF=vec_FF';
970    end
971   
972    %decimate by a factor 2 in vector mesh(4 in nbre of vectors)
973    if isfield(PlotParam.Vectors,'decimate4')&isequal(PlotParam.Vectors.decimate4,1)
974        diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
975        dy_thresh=max(abs(diffy))/2;
976        ind_jump=find(abs(diffy) > dy_thresh); %indices with diff(vec_Y)> max/2, detect change of line
977        ind_sel=1:ind_jump(1);%select the first line
978        for i=2:2:length(ind_jump)-1
979            ind_sel=[ind_sel [ind_jump(i)+1:ind_jump(i+1)]];% select the odd lines
980        end
981        nb_sel=length(ind_sel);
982        ind_sel=ind_sel(1:2:nb_sel);% take half the points on a line
983        vec_X=vec_X(ind_sel);
984        vec_Y=vec_Y(ind_sel);
985        vec_U=vec_U(ind_sel);
986        vec_V=vec_V(ind_sel);
987        vec_C=vec_C(ind_sel);
988        if ~isempty(ivar_F)
989           vec_F=vec_F(ind_sel);
990        end
991        if ~isempty(ivar_FF)
992           vec_FF=vec_FF(ind_sel);
993        end
994    end
995   
996    %get main level color code
997    [colorlist,col_vec,PlotParamOut.Vectors]=set_col_vec(PlotParam.Vectors,vec_C);
998   
999    % take flags into account: add flag colors to the list of colors
1000    sizlist=size(colorlist);
1001    nbcolor=sizlist(1);
1002    if test_black
1003       nbcolor=nbcolor+1;
1004       colorlist(nbcolor,:)=[0 0 0]; %add black to the list of colors
1005       if ~isempty(ivar_FF)
1006            ind_flag=find(vec_F~=1 & vec_F~=0 & vec_FF==0);  %flag warning but not false
1007       else
1008            ind_flag=find(vec_F~=1 & vec_F~=0);
1009       end
1010       col_vec(ind_flag)=nbcolor;   
1011    end
1012    nbcolor=nbcolor+1;
1013    if ~isempty(ivar_FF)
1014        ind_flag=find(vec_FF~=0);
1015        if isfield(PlotParam.Vectors,'HideFalse') && PlotParam.Vectors.HideFalse==1
1016            colorlist(nbcolor,:)=[NaN NaN NaN];% no plot of false vectors
1017        else
1018            colorlist(nbcolor,:)=[1 0 1];% magenta color
1019        end
1020        col_vec(ind_flag)=nbcolor;
1021    end
1022    %plot vectors:
1023    quiresetn(haxes,vec_X,vec_Y,vec_U,vec_V,scale,colorlist,col_vec);   
1024
1025else
1026    hvec=findobj(haxes,'Tag','vel');
1027    if ~isempty(hvec)
1028        delete(hvec);
1029    end
1030    AxeData.X=[];
1031    AxeData.Y=[];
1032    AxeData.U=[];
1033    AxeData.V=[];
1034    AxeData.C=[];
1035    AxeData.W=[];
1036    AxeData.F=[];
1037     AxeData.FF=[];
1038    AxeData.Mesh=[];
1039    PlotParamOut=rmfield(PlotParamOut,'Vectors');
1040end
1041if isfield(Data,'Z')
1042    AxeData.Z=Data.Z;% A REVOIR
1043end
1044listfields={'AY','AX','A','X','Y','U','V','C','W','F','FF'};
1045listdim={'AY','AX',{'AY','AX'},'nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors'};
1046Role={'coord_y','coord_x','scalar','coord_x','coord_y','vector_x','vector_y','scalar','vector_z','warnflag','errorflag'};
1047%ind_select=[];
1048nbvar=0;
1049AxeData.ListVarName={};
1050AxeData.VarDimName={};
1051AxeData.VarAttribute={};
1052for ilist=1:numel(listfields)
1053    eval(['testvar=isfield(AxeData,listfields{ilist}) && ~isempty(AxeData.' listfields{ilist} ');'])
1054    if testvar
1055        nbvar=nbvar+1;
1056        AxeData.ListVarName{nbvar}=listfields{ilist};
1057        AxeData.VarDimName{nbvar}=listdim{ilist};
1058        AxeData.VarAttribute{nbvar}.Role=Role{ilist};
1059    end
1060end
1061%store the coordinate extrema occupied by the field
1062test_lim=0;
1063if test_vec
1064    Xlim=[min(vec_X) max(vec_X)];
1065    Ylim=[min(vec_Y) max(vec_Y)];
1066    test_lim=1;
1067    if test_ima%both background image and vectors coexist, take the wider bound
1068        Xlim(1)=min(AX(1),Xlim(1));
1069        Xlim(2)=max(AX(end),Xlim(2));
1070        Ylim(1)=min(AY(end),Ylim(1));
1071        Ylim(2)=max(AY(1),Ylim(2));
1072    end
1073elseif test_ima %only image plot
1074    Xlim(1)=min(AX(1),AX(end));
1075    Xlim(2)=max(AX(1),AX(end));
1076    Ylim(1)=min(AY(1),AY(end));
1077    Ylim(2)=max(AY(1),AY(end));
1078    test_lim=1;
1079end
1080AxeData.RangeX=Xlim;
1081AxeData.RangeY=Ylim;
1082% adjust the size of the plot to include the whole field, except if PlotParam.FixedLimits=1
1083if ~(isfield(PlotParam,'FixedLimits') && PlotParam.FixedLimits) && test_lim
1084        if Xlim(2)>Xlim(1)
1085            set(haxes,'XLim',Xlim);% set x limits of frame in axes coordinates
1086        end
1087        if Ylim(2)>Ylim(1)
1088            set(haxes,'YLim',Ylim);% set y limits of frame in axes coordinate
1089        end
1090end
1091if ~(isfield(PlotParam,'Auto_xy') && isequal(PlotParam.Auto_xy,1))
1092     set(haxes,'DataAspectRatio',[1 1 1])
1093end
1094set(haxes,'YDir','normal')
1095set(get(haxes,'XLabel'),'String',[XName x_units]);
1096set(get(haxes,'YLabel'),'String',[YName y_units]);
1097
1098%-------------------------------------------------------------------
1099% --- function for plotting vectors
1100%INPUT:
1101% haxes: handles of the plotting axes
1102% x,y,u,v: vectors coordinates and vector components to plot, arrays withb the same dimension
1103% scale: scaling factor for vector length representation
1104% colorlist(icolor,:): list of vector colors, dim (nbcolor,3), depending on color #i
1105% col_vec: matlab vector setting the color number #i for each velocity vector
1106function quiresetn(haxes,x,y,u,v,scale,colorlist,col_vec)
1107%-------------------------------------------------------------------
1108%define arrows
1109theta=0.5 ;%angle arrow
1110alpha=0.3 ;%length arrow
1111rot=alpha*[cos(theta) -sin(theta); sin(theta) cos(theta)]';
1112%find the existing lines
1113%h=findobj(gca,'Type','Line');% search existing lines in the current axes
1114h=findobj(haxes,'Tag','vel');% search existing lines in the current axes
1115sizh=size(h);
1116set(h,'EraseMode','xor');
1117set(haxes,'NextPlot','replacechildren');
1118     
1119%drawnow
1120%create lines (if no lines) or modify them
1121if ~isequal(size(col_vec),size(x))
1122    col_vec=ones(size(x));% case of error in col_vec input
1123end
1124sizlist=size(colorlist);
1125ncolor=sizlist(1);
1126
1127for icolor=1:ncolor
1128    %determine the line positions for each color icolor
1129    ind=find(col_vec==icolor);
1130    xc=x(ind);
1131    yc=y(ind);
1132    uc=u(ind)*scale;
1133    vc=v(ind)*scale;
1134    n=size(xc);
1135    xN=NaN*ones(size(xc));
1136    matx=[xc(:)-uc(:)/2 xc(:)+uc(:)/2 xN(:)]';
1137%     matx=[xc(:) xc(:)+uc(:) xN(:)]';
1138    matx=reshape(matx,1,3*n(2));
1139    maty=[yc(:)-vc(:)/2 yc(:)+vc(:)/2 xN(:)]';
1140%     maty=[yc(:) yc(:)+vc(:) xN(:)]';
1141    maty=reshape(maty,1,3*n(2));
1142   
1143    %determine arrow heads
1144    arrowplus=rot*[uc;vc];
1145    arrowmoins=rot'*[uc;vc];
1146    x1=xc+uc/2-arrowplus(1,:);
1147    x2=xc+uc/2;
1148    x3=xc+uc/2-arrowmoins(1,:);
1149    y1=yc+vc/2-arrowplus(2,:);
1150    y2=yc+vc/2;
1151    y3=yc+vc/2-arrowmoins(2,:);
1152%     x1=xc+uc-arrowplus(1,:);
1153%     x2=xc+uc;
1154%     x3=xc+uc-arrowmoins(1,:);
1155%     y1=yc+vc-arrowplus(2,:);
1156%     y2=yc+vc;
1157%     y3=yc+vc-arrowmoins(2,:);
1158    matxar=[x1(:) x2(:) x3(:) xN(:)]';
1159    matxar=reshape(matxar,1,4*n(2));
1160    matyar=[y1(:) y2(:) y3(:) xN(:)]';
1161    matyar=reshape(matyar,1,4*n(2));
1162    %draw the line or modify the existing ones
1163      hx = [x1;x2;x3];
1164      hy = [y1;y2;y3];
1165    tri=reshape([1:3*length(uc)],3,[])';
1166    d = tri(:,[1 2 3 1])';
1167   
1168    isn=isnan(colorlist(icolor,:));%test if color NaN
1169    if 2*icolor > sizh(1) %if icolor exceeds the number of existing ones
1170        %axes(haxes)
1171        hfig=get(haxes,'parent');
1172%         axes(haxes)
1173        set(0,'CurrentFigure',hfig)
1174        set(hfig,'CurrentAxes',haxes)
1175        if ~isn(1) %if the vectors are visible color not nan
1176            if n(2)>0
1177                hold on
1178                line(matx,maty,'Color',colorlist(icolor,:),'Tag','vel');% plot new lines
1179                line(matxar,matyar,'Color',colorlist(icolor,:),'Tag','vel');% plot arrows
1180%                 fill(hx(d),hy(d),colorlist(icolor,:),'EdgeColor','none','
1181%                 Tag','Vel');
1182          end
1183        end
1184    else
1185        if isn(1)
1186            delete(h(2*icolor-1))
1187            delete(h(2*icolor))
1188        else
1189            set(h(2*icolor-1),'Xdata',matx,'Ydata',maty);
1190            set(h(2*icolor-1),'Color',colorlist(icolor,:));
1191            set(h(2*icolor-1),'EraseMode','xor');
1192            set(h(2*icolor),'Xdata',matxar,'Ydata',matyar);
1193            set(h(2*icolor),'Color',colorlist(icolor,:));
1194            set(h(2*icolor),'EraseMode','xor');
1195        end
1196     end
1197end
1198if sizh(1) > 2*ncolor
1199    for icolor=ncolor+1 : sizh(1)/2%delete additional objects
1200        delete(h(2*icolor-1))
1201        delete(h(2*icolor))
1202    end
1203end
1204
1205%-------------------------------------------------------------------
1206% ---- determine tick positions for colorbar
1207function YTick=colbartick(MinA,MaxA)
1208%-------------------------------------------------------------------
1209%determine tick positions with "simple" values between MinA and MaxA
1210YTick=0;%default
1211maxabs=max([abs(MinA) abs(MaxA)]);
1212if maxabs>0
1213ord=10^(floor(log10(maxabs)));%order of magnitude
1214div=1;
1215siz2=1;
1216while siz2<2
1217%     values=[-9:div:9];
1218    values=-10:div:10;
1219    ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);%indices of 'values' such that MinA<ord*values<MaxA
1220    siz=size(ind);
1221    if siz(2)<4%if there are less than 4 selected values (4 levels)
1222        values=-9:0.5*div:9;
1223        ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);
1224    end
1225    siz2=size(ind,2);
1226%     siz2=siz(2)
1227    div=div/10;
1228end
1229YTick=ord*values(ind);
1230end
1231
Note: See TracBrowser for help on using the repository browser.