source: trunk/src/plot_field.m @ 411

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

bugs corrected in uvmat: fixed x/y and calc_field for the new PIV data

File size: 53.8 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        end
811       
812        % set  colormap for  image display
813        if ~CheckContour
814            % rescale the grey levels with min and max, put a grey scale colorbar
815            B=A;
816            if BW
817                vec=linspace(0,1,255);%define a linear greyscale colormap
818                map=[vec' vec' vec'];
819                colormap(map);  %grey scale color map
820            else
821                colormap('default'); % standard faulse colors for div, vort , scalar fields
822            end
823        end
824       
825    % case of color images
826    else
827        if BW
828            B=uint16(sum(A,3));
829        else
830            B=uint8(A);
831        end
832        MinA=0;
833        MaxA=255;
834    end
835   
836    % display usual image
837    if ~CheckContour     
838        % interpolate field to increase resolution of image display
839        test_interp=1;
840        if max(np) <= 64
841            npxy=8*np;% increase the resolution 8 times
842        elseif max(np) <= 128
843            npxy=4*np;% increase the resolution 4 times
844        elseif max(np) <= 256
845            npxy=2*np;% increase the resolution 2 times
846        else
847            npxy=np;
848            test_interp=0; % no interpolation done
849        end
850        if test_interp==1%if we interpolate   
851            x=linspace(AX(1),AX(2),np(2));
852            y=linspace(AY(1),AY(2),np(1));
853            [X,Y]=meshgrid(x,y);
854            xi=linspace(AX(1),AX(2),npxy(2));
855            yi=linspace(AY(1),AY(2),npxy(1));
856            B = interp2(X,Y,double(B),xi,yi');
857        end           
858        % create new image if there  no image handle is found
859        if isempty(hima)
860            tag=get(haxes,'Tag');
861            if MinA<MaxA
862                hima=imagesc(AX,AY,B,[MinA MaxA]);
863            else % to deal with uniform field
864                hima=imagesc(AX,AY,B,[MaxA-1 MaxA]);
865            end
866            % the function imagesc reset the axes 'DataAspectRatioMode'='auto', change if .CheckFixEqual is
867            % requested:
868           if isfield(PlotParam.Coordinates,'CheckFixEqual') && isequal(PlotParam.Coordinates.CheckFixEqual,1)
869                set(haxes,'DataAspectRatioMode','manual')
870                set(haxes,'DataAspectRatio',[1 1 1])
871           end
872            set(hima,'Tag','ima')
873            set(hima,'HitTest','off')
874            set(haxes,'Tag',tag);%preserve the axes tag (removed by image fct !!!)     
875            uistack(hima, 'bottom')
876        % update an existing image
877        else
878            set(hima,'CData',B);
879            if MinA<MaxA
880                set(haxes,'CLim',[MinA MaxA])
881            else
882                set(haxes,'CLim',[MinA MaxA+1])
883            end
884            set(hima,'XData',AX);
885            set(hima,'YData',AY);
886        end
887        % set the transparency to 0.5 if vectors are also plotted
888        if test_vec
889            set(hima,'AlphaData',0.5)
890        else
891            set(hima,'AlphaData',1)
892        end
893    end
894    test_ima=1;
895   
896    %display the colorbar code for B/W images if Poscolorbar not empty
897    if siz==2 && exist('PosColorbar','var')&& ~isempty(PosColorbar)
898        if isempty(hcol)||~ishandle(hcol)
899             hcol=colorbar;%create new colorbar
900        end
901        if length(PosColorbar)==4
902                 set(hcol,'Position',PosColorbar)           
903        end
904        %YTick=0;%default
905        if MaxA>MinA
906            if CheckContour
907                colbarlim=get(hcol,'YLim');
908                scale_bar=(colbarlim(2)-colbarlim(1))/(abscontmax-abscontmin);               
909                YTick=cont_pos(2:end-1);
910                YTick_scaled=colbarlim(1)+scale_bar*(YTick-abscontmin);
911                set(hcol,'YTick',YTick_scaled);
912            elseif (isfield(PlotParam.Scalar,'CheckBW') && isequal(PlotParam.Scalar.CheckBW,1))||isa(A,'uint8')|| isa(A,'uint16')%images
913                hi=get(hcol,'children');
914                if iscell(hi)%multiple images in colorbar
915                    hi=hi{1};
916                end
917                set(hi,'YData',[MinA MaxA])
918                set(hi,'CData',(1:256)')
919                set(hcol,'YLim',[MinA MaxA])
920                YTick=colbartick(MinA,MaxA);
921                set(hcol,'YTick',YTick)               
922            else
923                hi=get(hcol,'children');
924                if iscell(hi)%multiple images in colorbar
925                    hi=hi{1};
926                end
927                set(hi,'YData',[MinA MaxA])
928                set(hi,'CData',(1:64)')
929                YTick=colbartick(MinA,MaxA);
930                set(hcol,'YLim',[MinA MaxA])
931                set(hcol,'YTick',YTick)
932            end
933            set(hcol,'Yticklabel',num2str(YTick'));
934        end
935    elseif ishandle(hcol)
936        delete(hcol); %erase existing colorbar if not needed
937    end
938else%no scalar plot
939    if ~isempty(hima) && ishandle(hima)
940        delete(hima)
941    end
942    if ~isempty(hcol)&& ishandle(hcol)
943       delete(hcol)
944    end
945    PlotParamOut=rmfield(PlotParamOut,'Scalar');
946end
947
948%%   vector plot %%%%%%%%%%%%%%%%%%%%%%%%%%
949if test_vec
950   %vector scale representation
951    if size(vec_U,1)==numel(vec_Y) && size(vec_U,2)==numel(vec_X); % x, y  coordinate variables
952        [vec_X,vec_Y]=meshgrid(vec_X,vec_Y);
953    end   
954    vec_X=reshape(vec_X,1,numel(vec_X));%reshape in matlab vectors
955    vec_Y=reshape(vec_Y,1,numel(vec_Y));
956    vec_U=reshape(vec_U,1,numel(vec_U));
957    vec_V=reshape(vec_V,1,numel(vec_V));
958     MinMaxX=max(vec_X)-min(vec_X);
959    if  isfield(PlotParam.Vectors,'CheckFixVectors') && isequal(PlotParam.Vectors.CheckFixVectors,1)&& isfield(PlotParam.Vectors,'VecScale')...
960               &&~isempty(PlotParam.Vectors.VecScale) && isa(PlotParam.Vectors.VecScale,'double') %fixed vector scale
961        scale=PlotParam.Vectors.VecScale;  %impose the length of vector representation
962    else
963        if ~test_false %remove false vectors   
964            indsel=1:numel(vec_X);%
965        end
966        if isempty(vec_U)
967            scale=1;
968        else
969            if isempty(indsel)
970                MaxU=max(abs(vec_U));
971                MaxV=max(abs(vec_V));
972            else
973                MaxU=max(abs(vec_U(indsel)));
974                MaxV=max(abs(vec_V(indsel)));
975            end
976            scale=MinMaxX/(max(MaxU,MaxV)*50);
977            PlotParam.Vectors.VecScale=scale;%update the 'scale' display
978        end
979    end
980   
981    %record vectors on the plotting axes
982    if test_C==0
983        vec_C=ones(1,numel(vec_X));
984    end
985   
986    %decimate by a factor 2 in vector mesh(4 in nbre of vectors)
987    if isfield(PlotParam.Vectors,'CheckDecimate4') && PlotParam.Vectors.CheckDecimate4
988        diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
989        dy_thresh=max(abs(diffy))/2;
990        ind_jump=find(abs(diffy) > dy_thresh); %indices with diff(vec_Y)> max/2, detect change of line
991        ind_sel=1:ind_jump(1);%select the first line
992        for i=2:2:length(ind_jump)-1
993            ind_sel=[ind_sel (ind_jump(i)+1:ind_jump(i+1))];% select the odd lines
994        end
995        nb_sel=length(ind_sel);
996        ind_sel=ind_sel(1:2:nb_sel);% take half the points on a line
997        vec_X=vec_X(ind_sel);
998        vec_Y=vec_Y(ind_sel);
999        vec_U=vec_U(ind_sel);
1000        vec_V=vec_V(ind_sel);
1001        vec_C=vec_C(ind_sel);
1002        if ~isempty(ivar_F)
1003           vec_F=vec_F(ind_sel);
1004        end
1005        if ~isempty(ivar_FF)
1006           vec_FF=vec_FF(ind_sel);
1007        end
1008    end
1009   
1010    %get main level color code
1011    [colorlist,col_vec,PlotParamOut.Vectors]=set_col_vec(PlotParam.Vectors,vec_C);
1012   
1013    % take flags into account: add flag colors to the list of colors
1014    sizlist=size(colorlist);
1015    nbcolor=sizlist(1);
1016    if test_black
1017       nbcolor=nbcolor+1;
1018       colorlist(nbcolor,:)=[0 0 0]; %add black to the list of colors
1019       if ~isempty(ivar_FF)
1020          %  ind_flag=find(vec_F~=1 & vec_F~=0 & vec_FF==0);  %flag warning but not false
1021            col_vec(vec_F~=1 & vec_F~=0 & vec_FF==0)=nbcolor;
1022       else
1023            col_vec(vec_F~=1 & vec_F~=0)=nbcolor;
1024       end
1025    end
1026    nbcolor=nbcolor+1;
1027    if ~isempty(ivar_FF)
1028        if isfield(PlotParam.Vectors,'CheckHideFalse') && PlotParam.Vectors.CheckHideFalse==1
1029            colorlist(nbcolor,:)=[NaN NaN NaN];% no plot of false vectors
1030        else
1031            colorlist(nbcolor,:)=[1 0 1];% magenta color
1032        end
1033        col_vec(vec_FF~=0)=nbcolor;
1034    end
1035    %plot vectors:
1036    quiresetn(haxes,vec_X,vec_Y,vec_U,vec_V,scale,colorlist,col_vec);   
1037
1038else
1039    hvec=findobj(haxes,'Tag','vel');
1040    if ~isempty(hvec)
1041        delete(hvec);
1042    end
1043    PlotParamOut=rmfield(PlotParamOut,'Vectors');
1044end
1045
1046%listfields={'AY','AX','A','X','Y','U','V','C','W','F','FF'};
1047%listdim={'AY','AX',{'AY','AX'},'nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors'};
1048%Role={'coord_y','coord_x','scalar','coord_x','coord_y','vector_x','vector_y','scalar','vector_z','warnflag','errorflag'};
1049%ind_select=[];
1050nbvar=0;
1051
1052%store the coordinate extrema occupied by the field
1053if ~isempty(Data)
1054    XMin=[];
1055    XMax=[];
1056    YMin=[];
1057    YMax=[];
1058    fix_lim=isfield(PlotParam.Coordinates,'CheckFixLimits') && PlotParam.Coordinates.CheckFixLimits;
1059    if fix_lim
1060        if isfield(PlotParam.Coordinates,'MinX')&&isfield(PlotParam.Coordinates,'MaxX')&&isfield(PlotParam.Coordinates,'MinY')&&isfield(PlotParam.Coordinates,'MaxY')
1061            XMin=PlotParam.Coordinates.MinX;
1062            XMax=PlotParam.Coordinates.MaxX;
1063            YMin=PlotParam.Coordinates.MinY;
1064            YMax=PlotParam.Coordinates.MaxY;
1065        end  %else PlotParamOut.XMin =PlotParam.XMin...
1066    else
1067        if test_ima %both background image and vectors coexist, take the wider bound
1068            XMin=min(AX);
1069            XMax=max(AX);
1070            YMin=min(AY);
1071            YMax=max(AY);
1072            if test_vec
1073                XMin=min(XMin,min(vec_X));
1074                XMax=max(XMax,max(vec_X));
1075                YMin=min(YMin,min(vec_Y));
1076                YMax=max(YMax,max(vec_Y));
1077            end
1078        elseif test_vec
1079            XMin=min(vec_X);
1080            XMax=max(vec_X);
1081            YMin=min(vec_Y);
1082            YMax=max(vec_Y);
1083        end
1084    end
1085%     PlotParamOut.RangeX=[XMin XMax]; %range of x, to be stored in the user data of the plot axes
1086%     PlotParamOut.RangeY=[YMin YMax]; %range of x, to be stored in the user data of the plot axes
1087%     if ~fix_lim
1088        PlotParamOut.Coordinates.MinX=XMin;
1089        PlotParamOut.Coordinates.MaxX=XMax;
1090        PlotParamOut.Coordinates.MinY=YMin;
1091        PlotParamOut.Coordinates.MaxY=YMax;
1092        if XMax>XMin
1093            set(haxes,'XLim',[XMin XMax]);% set x limits of frame in axes coordinates
1094        end
1095        if YMax>YMin
1096            set(haxes,'YLim',[YMin YMax]);% set x limits of frame in axes coordinates
1097        end
1098%     end
1099    set(haxes,'YDir','normal')
1100    set(get(haxes,'XLabel'),'String',[XName ' (' x_units ')']);
1101    set(get(haxes,'YLabel'),'String',[YName ' (' y_units ')']);
1102    PlotParamOut.Coordinates.x_units=x_units;
1103    PlotParamOut.Coordinates.y_units=y_units;
1104end
1105%-------------------------------------------------------------------
1106% --- function for plotting vectors
1107%INPUT:
1108% haxes: handles of the plotting axes
1109% x,y,u,v: vectors coordinates and vector components to plot, arrays withb the same dimension
1110% scale: scaling factor for vector length representation
1111% colorlist(icolor,:): list of vector colors, dim (nbcolor,3), depending on color #i
1112% col_vec: matlab vector setting the color number #i for each velocity vector
1113function quiresetn(haxes,x,y,u,v,scale,colorlist,col_vec)
1114%-------------------------------------------------------------------
1115%define arrows
1116theta=0.5 ;%angle arrow
1117alpha=0.3 ;%length arrow
1118rot=alpha*[cos(theta) -sin(theta); sin(theta) cos(theta)]';
1119%find the existing lines
1120h=findobj(haxes,'Tag','vel');% search existing lines in the current axes
1121sizh=size(h);
1122set(h,'EraseMode','xor');
1123set(haxes,'NextPlot','replacechildren');
1124
1125%drawnow
1126%create lines (if no lines) or modify them
1127if ~isequal(size(col_vec),size(x))
1128    col_vec=ones(size(x));% case of error in col_vec input
1129end
1130sizlist=size(colorlist);
1131ncolor=sizlist(1);
1132
1133for icolor=1:ncolor
1134    %determine the line positions for each color icolor
1135    ind=find(col_vec==icolor);
1136    xc=x(ind);
1137    yc=y(ind);
1138    uc=u(ind)*scale;
1139    vc=v(ind)*scale;
1140    n=size(xc);
1141    xN=NaN*ones(size(xc));
1142    matx=[xc(:)-uc(:)/2 xc(:)+uc(:)/2 xN(:)]';
1143    %     matx=[xc(:) xc(:)+uc(:) xN(:)]';
1144    matx=reshape(matx,1,3*n(2));
1145    maty=[yc(:)-vc(:)/2 yc(:)+vc(:)/2 xN(:)]';
1146    %     maty=[yc(:) yc(:)+vc(:) xN(:)]';
1147    maty=reshape(maty,1,3*n(2));
1148   
1149    %determine arrow heads
1150    arrowplus=rot*[uc;vc];
1151    arrowmoins=rot'*[uc;vc];
1152    x1=xc+uc/2-arrowplus(1,:);
1153    x2=xc+uc/2;
1154    x3=xc+uc/2-arrowmoins(1,:);
1155    y1=yc+vc/2-arrowplus(2,:);
1156    y2=yc+vc/2;
1157    y3=yc+vc/2-arrowmoins(2,:);
1158    matxar=[x1(:) x2(:) x3(:) xN(:)]';
1159    matxar=reshape(matxar,1,4*n(2));
1160    matyar=[y1(:) y2(:) y3(:) xN(:)]';
1161    matyar=reshape(matyar,1,4*n(2));
1162    %draw the line or modify the existing ones
1163    tri=reshape(1:3*length(uc),3,[])';   
1164    isn=isnan(colorlist(icolor,:));%test if color NaN
1165    if 2*icolor > sizh(1) %if icolor exceeds the number of existing ones
1166        if ~isn(1) %if the vectors are visible color not nan
1167            if n(2)>0
1168                hold on
1169                line(matx,maty,'Color',colorlist(icolor,:),'Tag','vel');% plot new lines
1170                line(matxar,matyar,'Color',colorlist(icolor,:),'Tag','vel');% plot arrows
1171            end
1172        end
1173    else
1174        if isn(1)
1175            delete(h(2*icolor-1))
1176            delete(h(2*icolor))
1177        else
1178            set(h(2*icolor-1),'Xdata',matx,'Ydata',maty);
1179            set(h(2*icolor-1),'Color',colorlist(icolor,:));
1180            set(h(2*icolor-1),'EraseMode','xor');
1181            set(h(2*icolor),'Xdata',matxar,'Ydata',matyar);
1182            set(h(2*icolor),'Color',colorlist(icolor,:));
1183            set(h(2*icolor),'EraseMode','xor');
1184        end
1185    end
1186end
1187if sizh(1) > 2*ncolor
1188    for icolor=ncolor+1 : sizh(1)/2%delete additional objects
1189        delete(h(2*icolor-1))
1190        delete(h(2*icolor))
1191    end
1192end
1193
1194%-------------------------------------------------------------------
1195% ---- determine tick positions for colorbar
1196function YTick=colbartick(MinA,MaxA)
1197%-------------------------------------------------------------------
1198%determine tick positions with "simple" values between MinA and MaxA
1199YTick=0;%default
1200maxabs=max([abs(MinA) abs(MaxA)]);
1201if maxabs>0
1202ord=10^(floor(log10(maxabs)));%order of magnitude
1203div=1;
1204siz2=1;
1205while siz2<2
1206    values=-10:div:10;
1207    ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);%indices of 'values' such that MinA<ord*values<MaxA
1208    siz=size(ind);
1209    if siz(2)<4%if there are less than 4 selected values (4 levels)
1210        values=-9:0.5*div:9;
1211        ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);
1212    end
1213    siz2=size(ind,2);
1214    div=div/10;
1215end
1216YTick=ord*values(ind);
1217end
1218
1219% -------------------------------------------------------------------------
1220% --- 'proj_grid': project  fields with unstructured coordinantes on a regular grid
1221function [A,rangx,rangy]=proj_grid(vec_X,vec_Y,vec_A,rgx_in,rgy_in,npxy_in)
1222% -------------------------------------------------------------------------
1223if length(vec_Y)<2
1224    msgbox_uvmat('ERROR','less than 2 points in proj_grid.m');
1225    return;
1226end
1227diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
1228index=find(diffy);% find the indices of vec_Y after wich a change of horizontal line occurs(diffy non zero)
1229if isempty(index); msgbox_uvmat('ERROR','points aligned along abscissa in proj_grid.m'); return; end;%points aligned% A FAIRE: switch to line plot.
1230diff2=diff(diffy(index));% diff2 = fluctuations of the detected vertical grid mesh dy
1231if max(abs(diff2))>0.001*abs(diffy(index(1))) % if max(diff2) is larger than 1/1000 of the first mesh dy
1232    % the data are not regularly spaced and must be interpolated  on a regular grid
1233    if exist('rgx_in','var') & ~isempty (rgx_in) & isnumeric(rgx_in) & length(rgx_in)==2%  positions imposed from input
1234        rangx=rgx_in; % first and last positions
1235        rangy=rgy_in;
1236        dxy(1)=1/(npxy_in(1)-1);%grid mesh in y
1237        dxy(2)=1/(npxy_in(2)-1);%grid mesh in x
1238        dxy(1)=(rangy(2)-rangy(1))/(npxy_in(1)-1);%grid mesh in y
1239        dxy(2)=(rangx(2)-rangx(1))/(npxy_in(2)-1);%grid mesh in x
1240    else % interpolation grid automatically determined
1241        rangx(1)=min(vec_X);
1242        rangx(2)=max(vec_X);
1243        rangy(2)=min(vec_Y);
1244        rangy(1)=max(vec_Y);
1245        dxymod=sqrt((rangx(2)-rangx(1))*(rangy(1)-rangy(2))/length(vec_X));
1246        dxy=[-dxymod/4 dxymod/4];% increase the resolution 4 times
1247    end
1248    xi=[rangx(1):dxy(2):rangx(2)];
1249    yi=[rangy(1):dxy(1):rangy(2)];
1250    A=griddata_uvmat(vec_X,vec_Y,vec_A,xi,yi');
1251    A=reshape(A,length(yi),length(xi));
1252else
1253    x=vec_X(1:index(1));% the set of abscissa (obtained on the first line)
1254    indexend=index(end);% last vector index of line change
1255    ymax=vec_Y(indexend+1);% y coordinate AFTER line change
1256    ymin=vec_Y(index(1));
1257    y=vec_Y(index);
1258    y(length(y)+1)=ymax;
1259    nx=length(x);   %number of grid points in x
1260    ny=length(y);   % number of grid points in y
1261    B=(reshape(vec_A,nx,ny))'; %vec_A reshaped as a rectangular matrix
1262    [X,Y]=meshgrid(x,y);% positions X and Y also reshaped as matrix
1263
1264    %linear interpolation to improve the image resolution and/or adjust
1265    %to prescribed positions
1266    test_interp=1;
1267    if exist('rgx_in','var') & ~isempty (rgx_in) & isnumeric(rgx_in) & length(rgx_in)==2%  positions imposed from input
1268        rangx=rgx_in; % first and last positions
1269        rangy=rgy_in;
1270        npxy=npxy_in;
1271    else       
1272        rangx=[vec_X(1) vec_X(nx)];% first and last position found for x
1273          rangy=[max(ymax,ymin) min(ymax,ymin)];
1274        if max(nx,ny) <= 64 & isequal(npxy_in,'np>256')
1275            npxy=[8*ny 8*nx];% increase the resolution 8 times
1276        elseif max(nx,ny) <= 128 & isequal(npxy_in,'np>256')
1277            npxy=[4*ny 4*nx];% increase the resolution 4 times
1278        elseif max(nx,ny) <= 256 & isequal(npxy_in,'np>256')
1279            npxy=[2*ny 2*nx];% increase the resolution 2 times
1280        else
1281            npxy=[ny nx];
1282            test_interp=0; % no interpolation done
1283        end
1284    end
1285    if test_interp==1%if we interpolate
1286        xi=[rangx(1):(rangx(2)-rangx(1))/(npxy(2)-1):rangx(2)];
1287        yi=[rangy(1):(rangy(2)-rangy(1))/(npxy(1)-1):rangy(2)];
1288        [XI,YI]=meshgrid(xi,yi);
1289        A = interp2(X,Y,B,XI,YI);
1290    else %no interpolation for a resolution higher than 256
1291        A=B;
1292    end
1293end
Note: See TracBrowser for help on using the repository browser.