source: trunk/src/plot_field.m @ 388

Last change on this file since 388 was 388, checked in by sommeria, 9 years ago

several bugs corrected
file indexing, color images...

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