source: trunk/src/plot_field.m @ 428

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

bugs fixed. Introduction of transparency and axis aspect ratio in uvmat

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