source: trunk/src/plot_field.m @ 760

Last change on this file since 760 was 760, checked in by sommeria, 10 years ago

various improvements

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