source: trunk/src/plot_field.m @ 225

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

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=Data.' XName ';'])
588                eval(['vec_Y=Data.' YName ';'])
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 or structured ones (then ivar_X and ivar_Y empty)
630            XName=Data.ListVarName{ivar_X};
631            YName=Data.ListVarName{ivar_Y};
632            eval(['AX=Data.' XName ';'])
633            eval(['AY=Data.' YName ';'])
634            [A,AX,AY]=proj_grid(AX',AY',A',[],[],'np>256');  % interpolate on a grid 
635            if isfield(Data,'VarAttribute')
636                if numel(Data.VarAttribute)>=ivar_X && isfield(Data.VarAttribute{ivar_X},'units')
637                    x_units=[' (' Data.VarAttribute{ivar_X}.units ')'];
638                end
639                if numel(Data.VarAttribute)>=ivar_Y && isfield(Data.VarAttribute{ivar_Y},'units')
640                    y_units=[' (' Data.VarAttribute{ivar_Y}.units ')'];
641                end
642            end       
643        elseif numel(VarType.coord)==2 %structured coordinates
644            XName=Data.ListVarName{VarType.coord(2)};
645            YName=Data.ListVarName{VarType.coord(1)};
646            eval(['AY=Data.' Data.ListVarName{VarType.coord(1)} ';'])
647            eval(['AX=Data.' Data.ListVarName{VarType.coord(2)} ';'])
648            test_interp_X=0; %default, regularly meshed X coordinate
649            test_interp_Y=0; %default, regularly meshed Y coordinate
650            if isfield(Data,'VarAttribute')
651                if numel(Data.VarAttribute)>=VarType.coord(2) && isfield(Data.VarAttribute{VarType.coord(2)},'units')
652                    x_units=Data.VarAttribute{VarType.coord(2)}.units;
653                end
654                if numel(Data.VarAttribute)>=VarType.coord(1) && isfield(Data.VarAttribute{VarType.coord(1)},'units')
655                    y_units=Data.VarAttribute{VarType.coord(1)}.units;
656                end
657            end 
658            if numel(AY)>2
659                DAY=diff(AY);
660                DAY_min=min(DAY);
661                DAY_max=max(DAY);
662                if sign(DAY_min)~=sign(DAY_max);% =1 for increasing values, 0 otherwise
663                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(1)} ];
664                      return
665                end
666                test_interp_Y=(DAY_max-DAY_min)> 0.0001*abs(DAY_max);
667            end
668            if numel(AX)>2
669                DAX=diff(AX);
670                DAX_min=min(DAX);
671                DAX_max=max(DAX);
672                if sign(DAX_min)~=sign(DAX_max);% =1 for increasing values, 0 otherwise
673                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(2)} ];
674                      return
675                end
676                test_interp_X=(DAX_max-DAX_min)> 0.0001*abs(DAX_max);
677            end 
678            if test_interp_Y         
679                npxy(1)=max([256 floor((AY(end)-AY(1))/DAY_min) floor((AY(end)-AY(1))/DAY_max)]);
680                yI=linspace(AY(1),AY(end),npxy(1));
681                if ~test_interp_X
682                    xI=linspace(AX(1),AX(end),size(A,2));%default
683                    AX=xI;
684                end
685            end
686            if test_interp_X 
687                npxy(2)=max([256 floor((AX(end)-AX(1))/DAX_min) floor((AX(end)-AX(1))/DAX_max)]);
688                xI=linspace(AX(1),AX(end),npxy(2));   
689                if ~test_interp_Y
690                   yI=linspace(AY(1),AY(end),size(A,1));
691                   AY=yI;
692                end
693            end
694            if test_interp_X || test_interp_Y               
695                [AX2D,AY2D]=meshgrid(AX,AY);
696                A=interp2(AX2D,AY2D,double(A),xI,yI');
697            end
698            AX=[AX(1) AX(end)];% keep only the lower and upper bounds for image represnetation
699            AY=[AY(1) AY(end)];
700        else
701            errormsg='error in plot_field: invalid coordinate definition ';
702            return
703        end
704    end
705    %define coordinates as CoordUnits, if not defined as attribute for each variable
706    if isfield(Data,'CoordUnit')
707        if isempty(x_units)
708            x_units=Data.CoordUnit;
709        end
710        if isempty(y_units)
711            y_units=Data.CoordUnit;
712        end
713    end
714       
715end
716
717%%   image or scalar plot %%%%%%%%%%%%%%%%%%%%%%%%%%
718
719if ~isfield(PlotParam.Scalar,'Contours')
720    PlotParam.Scalar.Contours=0; %default
721end
722PlotParamOut=PlotParam; %default
723if test_ima
724    % distinguish B/W and color images
725    np=size(A);%size of image
726    siz=numel(np);
727    if siz>3
728       errormsg=['unrecognized scalar type: ' num2str(siz) ' dimensions'];
729            return
730    end
731    if siz==3
732        if np(3)==1
733            siz=2;%B W image
734        elseif np(3)==3
735            siz=3;%color image
736        else
737            errormsg=['unrecognized scalar type in plot_field: considered as 2D field with ' num2str(np(3)) ' color components'];
738            return
739        end
740    end
741   
742    %set the color map
743    if isfield(PlotParam.Scalar,'BW')
744        BW=PlotParam.Scalar.BW; %test for BW gray scale images
745    else
746        BW=(siz==2) && (isa(A,'uint8')|| isa(A,'uint16'));% non color images represented in gray scale by default
747    end
748   
749    %case of grey level images or contour plot
750    if siz==2
751        if ~isfield(PlotParam.Scalar,'FixScal')
752            PlotParam.Scalar.FixScal=0;%default
753        end
754        if ~isfield(PlotParam.Scalar,'MinA')
755            PlotParam.Scalar.MinA=[];%default
756        end
757        if ~isfield(PlotParam.Scalar,'MaxA')
758            PlotParam.Scalar.MaxA=[];%default
759        end
760        Aline=[];
761        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
762            Aline=reshape(A,1,[]);
763            Aline=Aline(~isnan(A));
764            if isempty(Aline)
765                 errormsg='NaN input scalar or image in plot_field';
766                return
767            end
768            MinA=double(min(Aline));
769            %MinA=double(min(min(A)));
770        else
771            MinA=PlotParam.Scalar.MinA;
772        end;
773        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
774            if isempty(Aline)
775               Aline=reshape(A,1,[]);
776               Aline=Aline(~isnan(A));
777               if isempty(Aline)
778                 errormsg='NaN input scalar or image in plot_field';
779                return
780               end
781            end
782            MaxA=double(max(Aline));
783           % MaxA=double(max(max(A)));
784        else
785            MaxA=PlotParam.Scalar.MaxA; 
786        end;
787        PlotParamOut.Scalar.MinA=MinA;
788        PlotParamOut.Scalar.MaxA=MaxA;
789       
790        % case of contour plot
791        if isequal(PlotParam.Scalar.Contours,1)
792            if ~isempty(hima) && ishandle(hima)
793                delete(hima)
794            end
795            if ~isfield(PlotParam.Scalar,'IncrA')
796                PlotParam.Scalar.IncrA=NaN;
797            end
798            if isnan(PlotParam.Scalar.IncrA)% | PlotParam.Scalar.AutoScal==0
799                cont=colbartick(MinA,MaxA);
800                intercont=cont(2)-cont(1);%default
801                PlotParamOut.Scalar.IncrA=intercont;
802            else
803               intercont=PlotParam.Scalar.IncrA;
804            end
805            B=A;           
806            abscontmin=intercont*floor(MinA/intercont);
807            abscontmax=intercont*ceil(MaxA/intercont);
808            contmin=intercont*floor(min(min(B))/intercont);
809            contmax=intercont*ceil(max(max(B))/intercont);
810            cont_pos_plus=0:intercont:contmax;
811            cont_pos_min=double(contmin):intercont:-intercont;
812            cont_pos=[cont_pos_min cont_pos_plus];
813            sizpx=(AX(end)-AX(1))/(np(2)-1);
814            sizpy=(AY(1)-AY(end))/(np(1)-1);
815            x_cont=AX(1):sizpx:AX(end); % pixel x coordinates for image display
816            y_cont=AY(1):-sizpy:AY(end); % pixel x coordinates for image display
817           % axes(haxes)% set the input axes handle as current axis
818    txt=ver('MATLAB');
819    Release=txt.Release;
820            relnumb=str2double(Release(3:4));
821            if relnumb >= 14
822                    vec=linspace(0,1,(abscontmax-abscontmin)/intercont);%define a greyscale colormap with steps intercont
823                map=[vec' vec' vec'];
824                colormap(map);
825                [var,hcontour]=contour(x_cont,y_cont,B,cont_pos);       
826                set(hcontour,'Fill','on')
827                set(hcontour,'LineStyle','none')
828                hold on
829            end
830            [var_p,hcontour_p]=contour(x_cont,y_cont,B,cont_pos_plus,'k-');
831            hold on
832            [var_m,hcontour_m]=contour(x_cont,y_cont,B,cont_pos_min,':');
833            set(hcontour_m,'LineColor',[1 1 1])
834            hold off
835            caxis([abscontmin abscontmax])
836            colormap(map);
837        end
838       
839        % set  colormap for  image display
840        if ~isequal(PlotParam.Scalar.Contours,1) 
841            % rescale the grey levels with min and max, put a grey scale colorbar
842            B=A;
843            if BW
844                vec=linspace(0,1,255);%define a linear greyscale colormap
845                map=[vec' vec' vec'];
846                colormap(map);  %grey scale color map
847            else
848                colormap('default'); % standard faulse colors for div, vort , scalar fields
849            end
850        end
851       
852    % case of color images
853    else
854        if BW
855            B=uint16(sum(A,3));
856        else
857            B=uint8(A);
858        end
859        MinA=0;
860        MaxA=255;
861    end
862   
863    % display usual image
864    if ~isequal(PlotParam.Scalar.Contours,1)     
865        % interpolate field to increase resolution of image display
866        test_interp=1;
867        if max(np) <= 64
868            npxy=8*np;% increase the resolution 8 times
869        elseif max(np) <= 128
870            npxy=4*np;% increase the resolution 4 times
871        elseif max(np) <= 256
872            npxy=2*np;% increase the resolution 2 times
873        else
874            npxy=np;
875            test_interp=0; % no interpolation done
876        end
877        if test_interp==1%if we interpolate   
878            x=linspace(AX(1),AX(2),np(2));
879            y=linspace(AY(1),AY(2),np(1));
880            [X,Y]=meshgrid(x,y);
881            xi=linspace(AX(1),AX(2),npxy(2));
882            yi=linspace(AY(1),AY(2),npxy(1));
883            B = interp2(X,Y,double(B),xi,yi');
884        end           
885        % create new image if there  no image handle is found
886        if isempty(hima)
887            tag=get(haxes,'Tag');
888            if MinA<MaxA
889                hima=imagesc(AX,AY,B,[MinA MaxA]);
890            else % to deal with uniform field
891                hima=imagesc(AX,AY,B,[MaxA-1 MaxA]);
892            end
893            set(hima,'Tag','ima','HitTest','off')
894            set(haxes,'Tag',tag);%preserve the axes tag (removed by image fct !!!)     
895            uistack(hima, 'bottom')
896        % update an existing image
897        else
898            set(hima,'CData',B);
899            if MinA<MaxA
900                set(haxes,'CLim',[MinA MaxA])
901                %caxis([MinA MaxA])
902            else
903                set(haxes,'CLim',[MinA MaxA])
904                %caxis([MaxA-1 MaxA])
905            end
906            set(hima,'XData',AX);
907            set(hima,'YData',AY);
908        end
909    end
910%     if ~isstruct(AxeData)
911%         AxeData=[];
912%     end
913    test_ima=1;
914   
915    %display the colorbar code for B/W images if Poscolorbar not empty
916    if siz==2 && exist('PosColorbar','var')&& ~isempty(PosColorbar)
917        if isempty(hcol)||~ishandle(hcol)
918             hcol=colorbar;%create new colorbar
919        end
920        if length(PosColorbar)==4
921                 set(hcol,'Position',PosColorbar)           
922        end
923        %YTick=0;%default
924        if MaxA>MinA
925            if isequal(PlotParam.Scalar.Contours,1)
926                colbarlim=get(hcol,'YLim');
927                scale_bar=(colbarlim(2)-colbarlim(1))/(abscontmax-abscontmin);               
928                YTick=cont_pos(2:end-1);
929                YTick_scaled=colbarlim(1)+scale_bar*(YTick-abscontmin);
930                set(hcol,'YTick',YTick_scaled);
931            elseif (isfield(PlotParam.Scalar,'BW') && isequal(PlotParam.Scalar.BW,1))||isa(A,'uint8')|| isa(A,'uint16')%images
932                hi=get(hcol,'children');
933                if iscell(hi)%multiple images in colorbar
934                    hi=hi{1};
935                end
936                set(hi,'YData',[MinA MaxA])
937                set(hi,'CData',(1:256)')
938                set(hcol,'YLim',[MinA MaxA])
939                YTick=colbartick(MinA,MaxA);
940                set(hcol,'YTick',YTick)               
941            else
942                hi=get(hcol,'children');
943                if iscell(hi)%multiple images in colorbar
944                    hi=hi{1};
945                end
946                set(hi,'YData',[MinA MaxA])
947                set(hi,'CData',(1:64)')
948                YTick=colbartick(MinA,MaxA);
949                set(hcol,'YLim',[MinA MaxA])
950                set(hcol,'YTick',YTick)
951            end
952            set(hcol,'Yticklabel',num2str(YTick'));
953        end
954    elseif ishandle(hcol)
955        delete(hcol); %erase existing colorbar if not needed
956    end
957else%no scalar plot
958    if ~isempty(hima) && ishandle(hima)
959        delete(hima)
960    end
961    if ~isempty(hcol)&& ishandle(hcol)
962       delete(hcol)
963    end
964    PlotParamOut=rmfield(PlotParamOut,'Scalar');
965end
966
967%%   vector plot %%%%%%%%%%%%%%%%%%%%%%%%%%
968if test_vec
969   %vector scale representation
970    if size(vec_U,1)==numel(vec_Y) && size(vec_U,2)==numel(vec_X); % x, y  coordinate variables
971        [vec_X,vec_Y]=meshgrid(vec_X,vec_Y);
972    end   
973    vec_X=reshape(vec_X,1,numel(vec_X));%reshape in matlab vectors
974    vec_Y=reshape(vec_Y,1,numel(vec_Y));
975    vec_U=reshape(vec_U,1,numel(vec_U));
976    vec_V=reshape(vec_V,1,numel(vec_V));
977     MinMaxX=max(vec_X)-min(vec_X);
978    if  isfield(PlotParam.Vectors,'FixVec') && isequal(PlotParam.Vectors.FixVec,1)&& isfield(PlotParam.Vectors,'VecScale')...
979               &&~isempty(PlotParam.Vectors.VecScale) && isa(PlotParam.Vectors.VecScale,'double') %fixed vector scale
980        scale=PlotParam.Vectors.VecScale;  %impose the length of vector representation
981    else
982        if ~test_false %remove false vectors   
983            indsel=1:numel(vec_X);%
984        end
985        if isempty(vec_U)
986            scale=1;
987        else
988            if isempty(indsel)
989                MaxU=max(abs(vec_U));
990                MaxV=max(abs(vec_V));
991            else
992                MaxU=max(abs(vec_U(indsel)));
993                MaxV=max(abs(vec_V(indsel)));
994            end
995            scale=MinMaxX/(max(MaxU,MaxV)*50);
996            PlotParam.Vectors.VecScale=scale;%update the 'scale' display
997        end
998    end
999   
1000    %record vectors on the plotting axes
1001    if test_C==0
1002        vec_C=ones(1,numel(vec_X));
1003    end
1004   
1005    %decimate by a factor 2 in vector mesh(4 in nbre of vectors)
1006    if isfield(PlotParam.Vectors,'decimate4') && isequal(PlotParam.Vectors.decimate4,1)
1007        diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
1008        dy_thresh=max(abs(diffy))/2;
1009        ind_jump=find(abs(diffy) > dy_thresh); %indices with diff(vec_Y)> max/2, detect change of line
1010        ind_sel=1:ind_jump(1);%select the first line
1011        for i=2:2:length(ind_jump)-1
1012            ind_sel=[ind_sel (ind_jump(i)+1:ind_jump(i+1))];% select the odd lines
1013        end
1014        nb_sel=length(ind_sel);
1015        ind_sel=ind_sel(1:2:nb_sel);% take half the points on a line
1016        vec_X=vec_X(ind_sel);
1017        vec_Y=vec_Y(ind_sel);
1018        vec_U=vec_U(ind_sel);
1019        vec_V=vec_V(ind_sel);
1020        vec_C=vec_C(ind_sel);
1021        if ~isempty(ivar_F)
1022           vec_F=vec_F(ind_sel);
1023        end
1024        if ~isempty(ivar_FF)
1025           vec_FF=vec_FF(ind_sel);
1026        end
1027    end
1028   
1029    %get main level color code
1030    [colorlist,col_vec,PlotParamOut.Vectors]=set_col_vec(PlotParam.Vectors,vec_C);
1031   
1032    % take flags into account: add flag colors to the list of colors
1033    sizlist=size(colorlist);
1034    nbcolor=sizlist(1);
1035    if test_black
1036       nbcolor=nbcolor+1;
1037       colorlist(nbcolor,:)=[0 0 0]; %add black to the list of colors
1038       if ~isempty(ivar_FF)
1039          %  ind_flag=find(vec_F~=1 & vec_F~=0 & vec_FF==0);  %flag warning but not false
1040            col_vec(vec_F~=1 & vec_F~=0 & vec_FF==0)=nbcolor;
1041       else
1042           % ind_flag=find(vec_F~=1 & vec_F~=0);
1043            col_vec(vec_F~=1 & vec_F~=0)=nbcolor;
1044       end
1045      % col_vec(ind_flag)=nbcolor;   
1046    end
1047    nbcolor=nbcolor+1;
1048    if ~isempty(ivar_FF)
1049        %ind_flag=find(vec_FF~=0);
1050        if isfield(PlotParam.Vectors,'HideFalse') && PlotParam.Vectors.HideFalse==1
1051            colorlist(nbcolor,:)=[NaN NaN NaN];% no plot of false vectors
1052        else
1053            colorlist(nbcolor,:)=[1 0 1];% magenta color
1054        end
1055        col_vec(vec_FF~=0)=nbcolor;
1056    end
1057    %plot vectors:
1058    quiresetn(haxes,vec_X,vec_Y,vec_U,vec_V,scale,colorlist,col_vec);   
1059
1060else
1061    hvec=findobj(haxes,'Tag','vel');
1062    if ~isempty(hvec)
1063        delete(hvec);
1064    end
1065    PlotParamOut=rmfield(PlotParamOut,'Vectors');
1066end
1067
1068%listfields={'AY','AX','A','X','Y','U','V','C','W','F','FF'};
1069%listdim={'AY','AX',{'AY','AX'},'nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors'};
1070%Role={'coord_y','coord_x','scalar','coord_x','coord_y','vector_x','vector_y','scalar','vector_z','warnflag','errorflag'};
1071%ind_select=[];
1072nbvar=0;
1073
1074%store the coordinate extrema occupied by the field
1075if ~isempty(Data)
1076    fix_lim=isfield(PlotParam,'FixLimits') && PlotParam.FixLimits;
1077    if fix_lim
1078        if ~isfield(PlotParam,'MinX')||~isfield(PlotParam,'MaxX')||~isfield(PlotParam,'MinY')||~isfield(PlotParam,'MaxY')
1079            fix_lim=0; %free limits if lits are not set,
1080        end  %else PlotParamOut.XMin =PlotParam.XMin...
1081    end
1082%     if ~fix_lim
1083        XMin=[];
1084        XMax=[];
1085        YMin=[];
1086        YMax=[];
1087        if test_ima%both background image and vectors coexist, take the wider bound
1088            XMin=min(AX);
1089            XMax=max(AX);
1090            YMin=min(AY);
1091            YMax=max(AY);
1092        end
1093        if test_vec
1094            XMin=[XMin min(vec_X)];
1095            XMax=[XMax max(vec_X)];
1096            YMin=[YMin min(vec_Y)];
1097            YMax=[YMax max(vec_Y)];
1098        end
1099        PlotParamOut.RangeX=[min(XMin) max(XMax)]; %range of x, to be stored in the user data of the plot axes
1100        PlotParamOut.RangeY=[min(YMin) max(YMax)]; %range of x, to be stored in the user data of the plot axes
1101    if ~fix_lim
1102        PlotParamOut.MinX=min(XMin);
1103        PlotParamOut.MaxX=max(XMax);
1104        PlotParamOut.MinY=min(YMin);
1105        PlotParamOut.MaxY=max(YMax);
1106        if XMax>XMin
1107            set(haxes,'XLim',[XMin XMax]);% set x limits of frame in axes coordinates
1108        end
1109        if YMax>YMin
1110            set(haxes,'YLim',[YMin YMax]);% set x limits of frame in axes coordinates
1111        end
1112    end
1113    set(haxes,'YDir','normal')
1114    set(get(haxes,'XLabel'),'String',[XName ' (' x_units ')']);
1115    set(get(haxes,'YLabel'),'String',[YName ' (' y_units ')']);
1116    PlotParamOut.x_units=x_units;
1117    PlotParamOut.y_units=y_units;
1118end
1119%-------------------------------------------------------------------
1120% --- function for plotting vectors
1121%INPUT:
1122% haxes: handles of the plotting axes
1123% x,y,u,v: vectors coordinates and vector components to plot, arrays withb the same dimension
1124% scale: scaling factor for vector length representation
1125% colorlist(icolor,:): list of vector colors, dim (nbcolor,3), depending on color #i
1126% col_vec: matlab vector setting the color number #i for each velocity vector
1127function quiresetn(haxes,x,y,u,v,scale,colorlist,col_vec)
1128%-------------------------------------------------------------------
1129%define arrows
1130theta=0.5 ;%angle arrow
1131alpha=0.3 ;%length arrow
1132rot=alpha*[cos(theta) -sin(theta); sin(theta) cos(theta)]';
1133%find the existing lines
1134h=findobj(haxes,'Tag','vel');% search existing lines in the current axes
1135sizh=size(h);
1136set(h,'EraseMode','xor');
1137set(haxes,'NextPlot','replacechildren');
1138
1139%drawnow
1140%create lines (if no lines) or modify them
1141if ~isequal(size(col_vec),size(x))
1142    col_vec=ones(size(x));% case of error in col_vec input
1143end
1144sizlist=size(colorlist);
1145ncolor=sizlist(1);
1146
1147for icolor=1:ncolor
1148    %determine the line positions for each color icolor
1149    ind=find(col_vec==icolor);
1150    xc=x(ind);
1151    yc=y(ind);
1152    uc=u(ind)*scale;
1153    vc=v(ind)*scale;
1154    n=size(xc);
1155    xN=NaN*ones(size(xc));
1156    matx=[xc(:)-uc(:)/2 xc(:)+uc(:)/2 xN(:)]';
1157    %     matx=[xc(:) xc(:)+uc(:) xN(:)]';
1158    matx=reshape(matx,1,3*n(2));
1159    maty=[yc(:)-vc(:)/2 yc(:)+vc(:)/2 xN(:)]';
1160    %     maty=[yc(:) yc(:)+vc(:) xN(:)]';
1161    maty=reshape(maty,1,3*n(2));
1162   
1163    %determine arrow heads
1164    arrowplus=rot*[uc;vc];
1165    arrowmoins=rot'*[uc;vc];
1166    x1=xc+uc/2-arrowplus(1,:);
1167    x2=xc+uc/2;
1168    x3=xc+uc/2-arrowmoins(1,:);
1169    y1=yc+vc/2-arrowplus(2,:);
1170    y2=yc+vc/2;
1171    y3=yc+vc/2-arrowmoins(2,:);
1172    matxar=[x1(:) x2(:) x3(:) xN(:)]';
1173    matxar=reshape(matxar,1,4*n(2));
1174    matyar=[y1(:) y2(:) y3(:) xN(:)]';
1175    matyar=reshape(matyar,1,4*n(2));
1176    %draw the line or modify the existing ones
1177    tri=reshape(1:3*length(uc),3,[])';   
1178    isn=isnan(colorlist(icolor,:));%test if color NaN
1179    if 2*icolor > sizh(1) %if icolor exceeds the number of existing ones
1180        if ~isn(1) %if the vectors are visible color not nan
1181            if n(2)>0
1182                hold on
1183                line(matx,maty,'Color',colorlist(icolor,:),'Tag','vel');% plot new lines
1184                line(matxar,matyar,'Color',colorlist(icolor,:),'Tag','vel');% plot arrows
1185            end
1186        end
1187    else
1188        if isn(1)
1189            delete(h(2*icolor-1))
1190            delete(h(2*icolor))
1191        else
1192            set(h(2*icolor-1),'Xdata',matx,'Ydata',maty);
1193            set(h(2*icolor-1),'Color',colorlist(icolor,:));
1194            set(h(2*icolor-1),'EraseMode','xor');
1195            set(h(2*icolor),'Xdata',matxar,'Ydata',matyar);
1196            set(h(2*icolor),'Color',colorlist(icolor,:));
1197            set(h(2*icolor),'EraseMode','xor');
1198        end
1199    end
1200end
1201if sizh(1) > 2*ncolor
1202    for icolor=ncolor+1 : sizh(1)/2%delete additional objects
1203        delete(h(2*icolor-1))
1204        delete(h(2*icolor))
1205    end
1206end
1207
1208%-------------------------------------------------------------------
1209% ---- determine tick positions for colorbar
1210function YTick=colbartick(MinA,MaxA)
1211%-------------------------------------------------------------------
1212%determine tick positions with "simple" values between MinA and MaxA
1213YTick=0;%default
1214maxabs=max([abs(MinA) abs(MaxA)]);
1215if maxabs>0
1216ord=10^(floor(log10(maxabs)));%order of magnitude
1217div=1;
1218siz2=1;
1219while siz2<2
1220%     values=[-9:div:9];
1221    values=-10:div:10;
1222    ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);%indices of 'values' such that MinA<ord*values<MaxA
1223    siz=size(ind);
1224    if siz(2)<4%if there are less than 4 selected values (4 levels)
1225        values=-9:0.5*div:9;
1226        ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);
1227    end
1228    siz2=size(ind,2);
1229%     siz2=siz(2)
1230    div=div/10;
1231end
1232YTick=ord*values(ind);
1233end
1234
Note: See TracBrowser for help on using the repository browser.