source: trunk/src/plot_field.m @ 919

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