source: trunk/src/plot_field.m @ 1176

Last change on this file since 1176 was 1176, checked in by sommeria, 2 days ago

background image introduced for civ1

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