source: trunk/src/plot_field.m @ 252

Last change on this file since 252 was 252, checked in by sommeria, 10 years ago

various bugs corrected.

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