source: trunk/src/plot_field.m @ 1085

Last change on this file since 1085 was 1077, checked in by sommeria, 5 years ago

various bug repair

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