source: trunk/src/plot_field.m @ 871

Last change on this file since 871 was 871, checked in by sommeria, 6 years ago

histo improved

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