source: trunk/src/plot_field.m @ 873

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

civ improved at mask edge

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