source: trunk/src/plot_field.m @ 546

Last change on this file since 546 was 546, checked in by sommeria, 8 years ago

bugs corrected for tps projection on a grid + pb of colorbar display solved

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