source: trunk/src/plot_field.m @ 879

Last change on this file since 879 was 874, checked in by sommeria, 9 years ago

merge_proj corrected + various bugs

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