source: trunk/src/plot_field.m @ 379

Last change on this file since 379 was 379, checked in by sommeria, 12 years ago

several bugs corrected
set_object.fig rationalized so that read_set_object is replaced by the rgeneral fct read_GUI.

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