source: trunk/src/plot_field.m @ 872

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

bugs corrected

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