source: trunk/src/plot_field.m @ 415

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

bugs corrected: problems with Dt in read_civxdata and uvmat.

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