source: trunk/src/plot_field.m @ 234

Last change on this file since 234 was 231, checked in by sommeria, 14 years ago

interactive test for piv introduced various bug corrections

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