source: trunk/src/plot_field.m @ 525

Last change on this file since 525 was 525, checked in by sommeria, 12 years ago

various bug repairs and cleaning

File size: 55.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,htext,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%     .Coordinates: coordinate parameters:
48%           .CheckFixLimits:=0 (default) adjust axes limit to the X,Y data, =1: preserves the previous axes limits
49%     .Coordinates.CheckFixAspectRatio: =0 (default):automatic adjustment of the graph, keep 1 to 1 aspect ratio for x and y scales.
50%     .Coordinates.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 not empty, display a colorbar for B&W images
79%               imposed position of the colorbar (ex [0.821 0.471 0.019 0.445])
80
81%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
82%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
83%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
84%     This file is part of the toolbox UVMAT.
85%
86%     UVMAT is free software; you can redistribute it and/or modify
87%     it under the terms of the GNU General Public License as published by
88%     the Free Software Foundation; either version 2 of the License, or
89%     (at your option) any later version.
90%
91%     UVMAT is distributed in the hope that it will be useful,
92%     but WITHOUT ANY WARRANTY; without even the implied warranty of
93%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
94%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
95%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
96
97function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,PosColorbar)
98
99%% default input and output
100if ~exist('PlotParam','var'),PlotParam=[];end;
101if ~exist('PosColorbar','var'),PosColorbar=[];end;
102PlotType='text'; %default
103PlotParamOut=PlotParam;%default
104if ~isfield(PlotParam,'Coordinates')
105    PlotParam.Coordinates=[];
106end
107
108%% check input structure
109index_2D=[];
110index_1D=[];
111index_0D=[];
112errormsg=check_field_structure(Data);
113if ~isempty(errormsg)
114    msgbox_uvmat('ERROR',['input of plot_field/check_field_structure: ' errormsg])
115    display(['input of plot_field/check_field_structure: ' errormsg])
116    return
117end
118% check the cells of fields :
119[CellVarIndex,NbDim,VarType,errormsg]=find_field_cells(Data);
120if ~isempty(errormsg)
121    msgbox_uvmat('ERROR',['input of plot_field/find_field_cells: ' errormsg]);
122    return
123end
124index_2D=find(NbDim==2);%find 2D fields
125index_3D=find(NbDim>2,1);
126if ~isempty(index_3D)
127    if isfield(Data,'NbDim')&& isequal(Data.NbDim,2)
128        index_2D=[index_2D index_3D];
129    else
130        msgbox_uvmat('ERROR','volume plot not implemented yet');
131        return
132    end
133end
134index_1D=find(NbDim==1&~cellfun(@isempty,VarType));
135index_0D=find(NbDim==0);
136%remove coordinates variables from 1D plot
137% if ~isempty(index_2D)
138%     for ivar=1:length(index_1D)
139%         if isequal(CellVarIndex{index_1D(ivar)},VarType{index_1D(ivar)}.coord)
140%             index_1D(ivar)=0;
141%         end
142%     end
143%     index_1D=index_1D(index_1D>0);
144% end
145
146%% test axes and figure
147testnewfig=1;%test to create a new figure (default)
148testzoomaxes=0;%test for the existence of a zoom secondary figure attached to the plotting axes
149if exist('haxes','var')
150    if ishandle(haxes)
151        if isequal(get(haxes,'Type'),'axes')
152            testnewfig=0;
153            AxeData=get(haxes,'UserData');
154            if isfield(AxeData,'ZoomAxes')&& ishandle(AxeData.ZoomAxes)
155                if isequal(get(AxeData.ZoomAxes,'Type'),'axes')
156                    testzoomaxes=1;
157                    zoomaxes=AxeData.ZoomAxes;
158                end
159            end
160        end
161    end
162end
163
164%% create a new figure and axes if the plotting axes does not exist
165if testnewfig
166    hfig=figure;
167    set(hfig,'Units','normalized')
168    haxes=axes;
169    set(haxes,'position',[0.13,0.2,0.775,0.73])
170    PlotParam.NextPlot='add'; %parameter for plot_profile and plot_his
171else
172    hfig=get(haxes,'parent');
173    set(0,'CurrentFigure',hfig)% the parent of haxes becomes the current figure
174    set(hfig,'CurrentAxes',haxes)%  haxes becomes the current axes of the parent figure
175end
176
177%% set axes properties
178if isfield(PlotParam.Coordinates,'CheckFixLimits') && isequal(PlotParam.Coordinates.CheckFixLimits,1)  %adjust the graph limits
179    set(haxes,'XLimMode', 'manual')
180    set(haxes,'YLimMode', 'manual')
181else
182    set(haxes,'XLimMode', 'auto')
183    set(haxes,'YLimMode', 'auto')
184end
185% if ~isfield(PlotParam.Coordinates,'CheckFixAspectRatio')&& isfield(Data,'CoordUnit')
186%     PlotParam.Coordinates.CheckFixAspectRatio=1;% if CoordUnit is defined, the two coordiantes should be plotted with equal scale by default
187% end
188errormsg='';
189PlotParamOut.Coordinates=[]; %default output
190AxeData=get(haxes,'UserData');
191
192%% 2D plots
193if isempty(index_2D)
194    plot_plane([],[],[],haxes);%removes images or vector plots in the absence of 2D field plot
195else  %plot 2D field
196    [tild,PlotParamOut,PlotType,errormsg]=plot_plane(Data,CellVarIndex(index_2D),VarType(index_2D),haxes,PlotParam,PosColorbar);
197    AxeData.NbDim=2;
198    if testzoomaxes && isempty(errormsg)
199        [zoomaxes,PlotParamOut,tild,errormsg]=plot_plane(Data,CellVarIndex(index_2D),VarType(index_2D),zoomaxes,PlotParam,PosColorbar);
200        AxeData.ZoomAxes=zoomaxes;
201    end
202end
203
204%% 1D plot (usual graph y vs x)
205if isempty(index_1D)
206    if ~isempty(haxes)
207        plot_profile([],[],[],haxes);%removes usual praphs y vs x in the absence of 1D field plot
208    end
209else %plot 1D field (usual graph y vs x)
210    Coordinates=plot_profile(Data,CellVarIndex(index_1D),VarType(index_1D),haxes,PlotParam.Coordinates);%
211    if testzoomaxes
212        [zoomaxes,Coordinates]=plot_profile(Data,CellVarIndex(index_1D),VarType(index_1D),zoomaxes,PlotParam.Coordinates);
213        AxeData.ZoomAxes=zoomaxes;
214    end
215    if ~isempty(Coordinates)
216        PlotParamOut.Coordinates=Coordinates;
217    end
218    PlotType='line';
219end
220
221%% text display
222if isempty(index_2D) && isempty(index_1D)%text display alone
223    htext=findobj(hfig,'Tag','TableDisplay');
224else  %text display added to plot
225    htext=findobj(hfig,'Tag','text_display');
226end
227if ~isempty(htext)
228    if isempty(index_0D)
229        if strcmp(get(htext,'Type'),'uitable')
230            set(htext,'Data',{})
231        else
232            set(htext,'String',{''})
233        end
234    else
235        [errormsg]=plot_text(Data,CellVarIndex(index_0D),VarType(index_0D),htext);
236    end
237end
238
239%% display error message
240if ~isempty(errormsg)
241    msgbox_uvmat('ERROR', errormsg)
242end
243
244%% update the parameters stored in AxeData
245if ishandle(haxes)&&( ~isempty(index_2D)|| ~isempty(index_1D))
246%     AxeData=[];
247    if isfield(PlotParamOut,'MinX')
248        AxeData.RangeX=[PlotParamOut.MinX PlotParamOut.MaxX];%'[PlotParamOut.MinX PlotParamOut.MaxX];
249        AxeData.RangeY=[PlotParamOut.MinY PlotParamOut.MaxY];%[PlotParamOut.MinY PlotParamOut.MaxY]
250    end
251    set(haxes,'UserData',AxeData)
252end
253
254%% update the plotted field stored in parent figure
255if ~isempty(index_2D)|| ~isempty(index_1D)
256    FigData=get(hfig,'UserData');
257    if strcmp(get(hfig,'tag'),'view_field')||strcmp(get(hfig,'tag'),'uvmat')
258        FigData.(get(haxes,'tag'))=Data;
259        set(hfig,'UserData',FigData)
260    end
261end
262
263%-------------------------------------------------------------------
264function errormsg=plot_text(FieldData,CellVarIndex,VarTypeCell,htext)
265%-------------------------------------------------------------------
266errormsg=[];
267txt_cell={};
268Data={};
269for icell=1:length(CellVarIndex)
270    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list data.ListVarName
271    for ivar=1:length(VarIndex)
272        checkancillary=0;
273        if length(FieldData.VarAttribute)>=VarIndex(ivar)
274            VarAttribute=FieldData.VarAttribute{VarIndex(ivar)};
275            if isfield(VarAttribute,'Role')&&(strcmp(VarAttribute.Role,'ancillary')||strcmp(VarAttribute.Role,'coord_tps')...
276                    ||strcmp(VarAttribute.Role,'vector_x_tps')||strcmp(VarAttribute.Role,'vector_y_tps'))
277                checkancillary=1;
278            end
279        end
280%         if ~checkancillary% does not display variables with attribute '.Role=ancillary'
281            VarName=FieldData.ListVarName{VarIndex(ivar)};
282            VarValue=FieldData.(VarName);
283            Data =[Data [{VarName}; num2cell(VarValue)]];
284            if size(VarValue,1)~=1
285                VarValue=VarValue';% put the different values on a line
286            end
287            if size(VarValue,1)==1
288            txt=[VarName '=' num2str(VarValue)];
289            txt_cell=[txt_cell;{txt}];
290            end
291%         end
292    end
293end
294if strcmp(get(htext,'Type'),'uitable')
295    get(htext,'ColumnName')
296    set(htext,'ColumnName',Data(1,:))
297    set(htext,'Data',Data(2:end,:))
298else
299    set(htext,'String',txt_cell)
300    set(htext,'UserData',txt_cell)% for storage during mouse display
301end
302
303
304%-------------------------------------------------------------------
305function CoordinatesOut=plot_profile(data,CellVarIndex,VarType,haxes,Coordinates)
306%-------------------------------------------------------------------
307
308if ~exist('Coordinates','var')
309    Coordinates=[];
310end
311CoordinatesOut=Coordinates; %default
312hfig=get(haxes,'parent');
313%suppress existing plot isf empty data
314if isempty(data)
315    hplot=findobj(haxes,'tag','plot_line');
316    if ~isempty(hplot)
317        delete(hplot)
318    end
319    hlegend=findobj(hfig,'tag','legend');
320    if ~isempty(hlegend)
321        delete(hlegend)
322    end
323    return
324end
325
326ColorOrder=[1 0 0;0 0.5 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];
327set(haxes,'ColorOrder',ColorOrder)
328if isfield(Coordinates,'NextPlot')
329    set(haxes,'NextPlot',Coordinates.NextPlot)
330end
331% adjust the size of the plot to include the whole field,
332
333legend_str={};
334
335%% prepare the string for plot command
336plotstr='hhh=plot(';
337coord_x_index=[];
338xtitle='';
339ytitle='';
340test_newplot=1;
341
342%loop on input  fields
343for icell=1:length(CellVarIndex)
344    if isempty(VarType{icell})% coordiante variable
345        continue
346    end
347    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list data.ListVarName
348    if ~isempty(VarType{icell}.coord_x)
349        coord_x_index=VarType{icell}.coord_x;
350    else
351        coord_x_index_cell=VarType{icell}.coord(1);
352        if isequal(coord_x_index_cell,0)
353             continue  % the cell has no abscissa, skip it
354        end
355        coord_x_index=coord_x_index_cell;
356    end
357    testplot=ones(size(data.ListVarName));%default test for plotted variables
358    coord_x_name{icell}=data.ListVarName{coord_x_index};
359    coord_x{icell}=data.(data.ListVarName{coord_x_index});%coordinate variable set as coord_x
360    if isempty(find(strcmp(coord_x_name{icell},coord_x_name(1:end-1)))) %xtitle not already selected
361        xtitle=[xtitle coord_x_name{icell}];
362        if isfield(data,'VarAttribute')&& numel(data.VarAttribute)>=coord_x_index && isfield(data.VarAttribute{coord_x_index},'units')
363            xtitle=[xtitle '(' data.VarAttribute{coord_x_index}.units '), '];
364        else
365            xtitle=[xtitle ', '];
366        end
367    end
368    XMin(icell)=min(coord_x{icell});
369    XMax(icell)=max(coord_x{icell});
370    testplot(coord_x_index)=0;
371    if ~isempty(VarType{icell}.ancillary')
372        testplot(VarType{icell}.ancillary)=0;
373    end
374    if ~isempty(VarType{icell}.warnflag')
375        testplot(VarType{icell}.warnflag)=0;
376    end
377    if isfield(data,'VarAttribute')
378        VarAttribute=data.VarAttribute;
379        for ivar=1:length(VarIndex)
380            if length(VarAttribute)>=VarIndex(ivar) && isfield(VarAttribute{VarIndex(ivar)},'long_name')
381                plotname{VarIndex(ivar)}=VarAttribute{VarIndex(ivar)}.long_name;
382            else
383                plotname{VarIndex(ivar)}=data.ListVarName{VarIndex(ivar)};%name for display in plot A METTRE
384            end
385        end
386    end
387    if ~isempty(VarType{icell}.discrete')
388        charplot_0='''+''';
389    else
390        charplot_0='''-''';
391    end
392    YMin=0;
393    YMax=1;%default
394    for ivar=1:length(VarIndex)
395        if testplot(VarIndex(ivar))
396            VarName=data.ListVarName{VarIndex(ivar)};
397            ytitle=[ytitle VarName];
398            if isfield(data,'VarAttribute')&& numel(data.VarAttribute)>=VarIndex(ivar) && isfield(data.VarAttribute{VarIndex(ivar)},'units')
399                ytitle=[ytitle '(' data.VarAttribute{VarIndex(ivar)}.units '), '];
400            else
401                ytitle=[ytitle ', '];
402            end
403            eval(['data.' VarName '=squeeze(data.' VarName ');'])
404            %eval(['min(data.' VarName ')'])
405            YMin(ivar)=min(min(data.(VarName)));
406            YMax(ivar)=max(max(data.(VarName)));
407            plotstr=[plotstr 'coord_x{' num2str(icell) '},data.' VarName ',' charplot_0 ','];
408            eval(['nbcomponent2=size(data.' VarName ',2);']);
409            eval(['nbcomponent1=size(data.' VarName ',1);']);
410            if numel(coord_x{icell})==2
411                coord_x{icell}=linspace(coord_x{icell}(1),coord_x{icell}(2),nbcomponent1);
412            end
413            if nbcomponent1==1|| nbcomponent2==1
414                legend_str=[legend_str {VarName}]; %variable with one component
415            else  %variable with severals  components
416                for ic=1:min(nbcomponent1,nbcomponent2)
417                    legend_str=[legend_str [VarName '_' num2str(ic)]]; %variable with severals  components
418                end                                                   % labeled by their index (e.g. color component)
419            end
420        end
421    end
422    YMin_cell(icell)=min(YMin);
423    YMax_cell(icell)=max(YMax);
424end
425
426%% activate the plot
427if test_newplot && ~isequal(plotstr,'hhh=plot(') 
428    set(hfig,'CurrentAxes',haxes)
429    tag=get(haxes,'tag');   
430    %%%
431    plotstr=[plotstr '''tag'',''plot_line'');'];   
432    eval(plotstr)                  %execute plot (instruction  plotstr)
433    %%%
434    set(haxes,'tag',tag)
435    grid(haxes, 'on')
436    hxlabel=xlabel(xtitle(1:end-2));% xlabel (removes ', ' at the end)
437    set(hxlabel,'Interpreter','none')% desable tex interpreter
438    if length(legend_str)>=1
439        hylabel=ylabel(ytitle(1:end-2));% ylabel (removes ', ' at the end)
440        set(hylabel,'Interpreter','none')% desable tex interpreter
441    end
442    if ~isempty(legend_str)
443        hlegend=findobj(hfig,'Tag','legend');
444        if isempty(hlegend)
445            hlegend=legend(legend_str);
446            txt=ver('MATLAB');
447            Release=txt.Release;
448            relnumb=str2double(Release(3:4));% should be changed to Version for better compatibility
449            if relnumb >= 14
450                set(hlegend,'Interpreter','none')% desable tex interpreter
451            end
452        else
453            legend_old=get(hlegend,'String');
454            if isequal(size(legend_old,1),size(legend_str,1))&&~isequal(legend_old,legend_str)
455                set(hlegend,'String',[legend_old legend_str]);
456            end
457        end
458    end
459    title_str='';
460    if isfield(data,'filename')
461       [Path, title_str, ext]=fileparts(data.filename);
462       title_str=[title_str ext];
463    end
464    if isfield(data,'Action')&&isfield(data.Action,'ActionName')
465        if ~isequal(title_str,'')
466            title_str=[title_str ', '];
467        end
468        title_str=[title_str data.Action.ActionName];
469    end
470    htitle=title(title_str);
471%     txt=ver('MATLAB');
472%     Release=txt.Release;
473%     relnumb=str2double(Release(3:4));
474%     if relnumb >= 14
475    set(htitle,'Interpreter','none')% desable tex interpreter
476%     end
477end
478
479%% determine axes bounds
480%CoordinatesOut.RangeX=[min(XMin) max(XMax)];
481%CoordinatesOut.RangeY=[min(YMin_cell) max(YMax_cell)];
482fix_lim=isfield(Coordinates,'CheckFixLimits') && Coordinates.CheckFixLimits;
483if fix_lim
484    if ~isfield(Coordinates,'MinX')||~isfield(Coordinates,'MaxX')||~isfield(Coordinates,'MinY')||~isfield(Coordinates,'MaxY')
485        fix_lim=0; %free limits if lits are not set,
486    end
487end
488if fix_lim
489    set(haxes,'XLim',[Coordinates.MinX Coordinates.MaxX])
490    set(haxes,'YLim',[Coordinates.MinY Coordinates.MaxY])
491else   
492    CoordinatesOut.MinX=min(XMin);
493    CoordinatesOut.MaxX=max(XMax);
494    CoordinatesOut.MinY=min(YMin_cell);
495    CoordinatesOut.MaxY=max(YMax_cell);
496end
497
498%% determine plot aspect ratio
499if isfield(Coordinates,'CheckFixAspectRatio') && isequal(Coordinates.CheckFixAspectRatio,1)&&isfield(Coordinates,'AspectRatio')
500    set(haxes,'DataAspectRatioMode','manual')
501    set(haxes,'DataAspectRatio',[Coordinates.AspectRatio 1 1])
502else
503    set(haxes,'DataAspectRatioMode','auto')%automatic aspect ratio
504    AspectRatio=get(haxes,'DataAspectRatio');
505    CoordinatesOut.AspectRatio=AspectRatio(1)/AspectRatio(2);
506end
507
508%-------------------------------------------------------------------
509function [haxes,PlotParamOut,PlotType,errormsg]=plot_plane(Data,CellVarIndex,VarTypeCell,haxes,PlotParam,PosColorbar)
510%-------------------------------------------------------------------
511
512grid(haxes, 'off')% remove grid (possibly remaining from other graphs)
513%default plotting parameters
514PlotType='plane';%default
515if ~exist('PlotParam','var')
516    PlotParam=[];
517end
518
519if ~isfield(PlotParam,'Scalar')
520    PlotParam.Scalar=[];
521end
522if ~isfield(PlotParam,'Vectors')
523    PlotParam.Vectors=[];
524end
525
526PlotParamOut=PlotParam;%default
527hfig=get(haxes,'parent');
528hcol=findobj(hfig,'Tag','Colorbar'); %look for colorbar axes
529hima=findobj(haxes,'Tag','ima');% search existing image in the current axes
530errormsg='';%default
531test_ima=0; %default: test for image or map plot
532test_vec=0; %default: test for vector plots
533test_black=0;
534test_false=0;
535test_C=0;
536XName='';
537x_units='';
538YName='';
539y_units='';
540for icell=1:length(CellVarIndex) % length(CellVarIndex) =1 or 2 (from the calling function)
541    VarType=VarTypeCell{icell};
542    if ~isempty(VarType.coord_tps) %do not plot directly tps data (used for projection only)
543        continue
544    end
545    ivar_X=VarType.coord_x; % defines (unique) index for the variable representing unstructured x coordinate (default =[])
546    ivar_Y=VarType.coord_y; % defines (unique)index for the variable representing unstructured y coordinate (default =[])
547    ivar_U=VarType.vector_x; % defines (unique) index for the variable representing x vector component (default =[])
548    ivar_V=VarType.vector_y; % defines (unique) index for the variable representing y vector component (default =[])
549    ivar_C=[VarType.scalar VarType.image VarType.color VarType.ancillary]; %defines index (indices) for the scalar or ancillary fields
550    if numel(ivar_C)>1
551        errormsg= 'error in plot_field: too many scalar inputs';
552        return
553    end
554    ivar_F=VarType.warnflag; %defines index (unique) for warning flag variable
555    ivar_FF=VarType.errorflag; %defines index (unique) for error flag variable
556    ind_coord=find(VarType.coord);
557    if numel(ind_coord)==2
558        VarType.coord=VarType.coord(ind_coord);
559    end
560    if ~isempty(ivar_U) && ~isempty(ivar_V)% vector components detected
561        if test_vec
562            errormsg='error in plot_field: attempt to plot two vector fields: to get the difference project on a plane with mode interp';
563            return
564        else
565            test_vec=1;
566            vec_U=Data.(Data.ListVarName{ivar_U});
567            vec_V=Data.(Data.ListVarName{ivar_V});
568            if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field with unstructured coordinates
569                XName=Data.ListVarName{ivar_X};
570                YName=Data.ListVarName{ivar_Y};
571                vec_X=reshape(Data.(XName),[],1); %transform vectors in column matlab vectors
572                vec_Y=reshape(Data.(YName),[],1);
573            elseif numel(VarType.coord)==2 && ~isequal(VarType.coord,[0 0]);%coordinates defines by dimension variables
574                y=Data.(Data.ListVarName{VarType.coord(1)});
575                x=Data.(Data.ListVarName{VarType.coord(2)});
576                if numel(y)==2 % y defined by first and last values on aregular mesh
577                    y=linspace(y(1),y(2),size(vec_U,1));
578                end
579                if numel(x)==2 % y defined by first and last values on aregular mesh
580                    x=linspace(x(1),x(2),size(vec_U,2));
581                end
582                [vec_X,vec_Y]=meshgrid(x,y); 
583            else
584                errormsg='error in plot_field: invalid coordinate definition for vector field';
585                return
586            end
587            if isfield(PlotParam.Vectors,'ColorScalar') && ~isempty(PlotParam.Vectors.ColorScalar)
588                [VarVal,ListVarName,VarAttribute,errormsg]=calc_field_interp([],Data,PlotParam.Vectors.ColorScalar);
589%             if ~isempty(ivar_C)
590                 %vec_C=Data.(Data.ListVarName{ivar_C});
591                 if ~isempty(VarVal)
592                 vec_C=reshape(VarVal{1},1,numel(VarVal{1}));
593                 test_C=1;
594                 end
595            end
596            if ~isempty(ivar_F)%~(isfield(PlotParam.Vectors,'HideWarning')&& isequal(PlotParam.Vectors.HideWarning,1))
597                if test_vec
598                    vec_F=Data.(Data.ListVarName{ivar_F}); % warning flags for  dubious vectors
599                    if  ~(isfield(PlotParam.Vectors,'CheckHideWarning') && isequal(PlotParam.Vectors.CheckHideWarning,1))
600                        test_black=1;
601                    end
602                end
603            end
604            if ~isempty(ivar_FF) %&& ~test_false
605                if test_vec% TODO: deal with FF for structured coordinates
606                    vec_FF=Data.(Data.ListVarName{ivar_FF}); % flags for false vectors
607                end
608            end
609        end
610    elseif ~isempty(ivar_C) %scalar or image
611        if test_ima
612             errormsg='attempt to plot two scalar fields or images';
613            return
614        end
615        eval(['A=squeeze(Data.' Data.ListVarName{ivar_C} ');']) ;% scalar represented as color image
616        test_ima=1;
617        if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates  (then ivar_X and ivar_Y not empty)
618            A=reshape(A,1,[]);
619            XName=Data.ListVarName{ivar_X};
620            YName=Data.ListVarName{ivar_Y};
621            eval(['AX=reshape(Data.' XName ',1,[]);'])
622            eval(['AY=reshape(Data.' YName ',1,[]);'])
623            [A,AX,AY]=proj_grid(AX',AY',A',[],[],'np>256');  % interpolate on a grid 
624            if isfield(Data,'VarAttribute')
625                if numel(Data.VarAttribute)>=ivar_X && isfield(Data.VarAttribute{ivar_X},'units')
626                    x_units=[' (' Data.VarAttribute{ivar_X}.units ')'];
627                end
628                if numel(Data.VarAttribute)>=ivar_Y && isfield(Data.VarAttribute{ivar_Y},'units')
629                    y_units=[' (' Data.VarAttribute{ivar_Y}.units ')'];
630                end
631            end       
632        elseif numel(VarType.coord)==2 %structured coordinates
633            XName=Data.ListVarName{VarType.coord(2)};
634            YName=Data.ListVarName{VarType.coord(1)};
635            eval(['AY=Data.' Data.ListVarName{VarType.coord(1)} ';'])
636            eval(['AX=Data.' Data.ListVarName{VarType.coord(2)} ';'])
637            test_interp_X=0; %default, regularly meshed X coordinate
638            test_interp_Y=0; %default, regularly meshed Y coordinate
639            if isfield(Data,'VarAttribute')
640                if numel(Data.VarAttribute)>=VarType.coord(2) && isfield(Data.VarAttribute{VarType.coord(2)},'units')
641                    x_units=Data.VarAttribute{VarType.coord(2)}.units;
642                end
643                if numel(Data.VarAttribute)>=VarType.coord(1) && isfield(Data.VarAttribute{VarType.coord(1)},'units')
644                    y_units=Data.VarAttribute{VarType.coord(1)}.units;
645                end
646            end 
647            if numel(AY)>2
648                DAY=diff(AY);
649                DAY_min=min(DAY);
650                DAY_max=max(DAY);
651                if sign(DAY_min)~=sign(DAY_max);% =1 for increasing values, 0 otherwise
652                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(1)} ];
653                      return
654                end
655                test_interp_Y=(DAY_max-DAY_min)> 0.0001*abs(DAY_max);
656            end
657            if numel(AX)>2
658                DAX=diff(AX);
659                DAX_min=min(DAX);
660                DAX_max=max(DAX);
661                if sign(DAX_min)~=sign(DAX_max);% =1 for increasing values, 0 otherwise
662                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(2)} ];
663                      return
664                end
665                test_interp_X=(DAX_max-DAX_min)> 0.0001*abs(DAX_max);
666            end 
667            if test_interp_Y         
668                npxy(1)=max([256 floor((AY(end)-AY(1))/DAY_min) floor((AY(end)-AY(1))/DAY_max)]);
669                yI=linspace(AY(1),AY(end),npxy(1));
670                if ~test_interp_X
671                    xI=linspace(AX(1),AX(end),size(A,2));%default
672                    AX=xI;
673                end
674            end
675            if test_interp_X 
676                npxy(2)=max([256 floor((AX(end)-AX(1))/DAX_min) floor((AX(end)-AX(1))/DAX_max)]);
677                xI=linspace(AX(1),AX(end),npxy(2));   
678                if ~test_interp_Y
679                   yI=linspace(AY(1),AY(end),size(A,1));
680                   AY=yI;
681                end
682            end
683            if test_interp_X || test_interp_Y               
684                [AX2D,AY2D]=meshgrid(AX,AY);
685                A=interp2(AX2D,AY2D,double(A),xI,yI');
686            end
687            AX=[AX(1) AX(end)];% keep only the lower and upper bounds for image represnetation
688            AY=[AY(1) AY(end)];
689        else
690            errormsg='error in plot_field: invalid coordinate definition ';
691            return
692        end
693    end
694    %define coordinates as CoordUnits, if not defined as attribute for each variable
695    if isfield(Data,'CoordUnit')
696        if isempty(x_units)
697            x_units=Data.CoordUnit;
698        end
699        if isempty(y_units)
700            y_units=Data.CoordUnit;
701        end
702    end
703       
704end
705
706%%   image or scalar plot %%%%%%%%%%%%%%%%%%%%%%%%%%
707
708if isfield(PlotParam.Scalar,'ListContour')
709    CheckContour=strcmp(PlotParam.Scalar.ListContour,'contours');
710else
711    CheckContour=0; %default
712end
713PlotParamOut=PlotParam; %default
714if test_ima
715    % distinguish B/W and color images
716    np=size(A);%size of image
717    siz=numel(np);
718    if siz>3
719        errormsg=['unrecognized scalar type: ' num2str(siz) ' dimensions'];
720        return
721    end
722    if siz==3
723        if np(3)==1
724            siz=2;%B W image
725        elseif np(3)==3
726            siz=3;%color image
727        else
728            errormsg=['unrecognized scalar type in plot_field: considered as 2D field with ' num2str(np(3)) ' color components'];
729            return
730        end
731    end
732   
733    %set the color map
734    if isfield(PlotParam.Scalar,'CheckBW') && ~isempty(PlotParam.Scalar.CheckBW)
735        BW=PlotParam.Scalar.CheckBW; %BW=0 color imposed, else gray scale imposed.
736    else % BW imposed automatically chosen
737        BW=(siz==2) && (isa(A,'uint8')|| isa(A,'uint16'));% non color images represented in gray scale by default
738        PlotParamOut.Scalar.CheckBW=BW;
739    end
740    %case of grey level images or contour plot
741    if siz==2
742        if ~isfield(PlotParam.Scalar,'CheckFixScalar')
743            PlotParam.Scalar.CheckFixScalar=0;%default
744        end
745        if ~isfield(PlotParam.Scalar,'MinA')
746            PlotParam.Scalar.MinA=[];%default
747        end
748        if ~isfield(PlotParam.Scalar,'MaxA')
749            PlotParam.Scalar.MaxA=[];%default
750        end
751        Aline=[];
752        if ~PlotParam.Scalar.CheckFixScalar ||isempty(PlotParam.Scalar.MinA)||~isa(PlotParam.Scalar.MinA,'double')  %correct if there is no numerical data in edit box
753            Aline=reshape(A,1,[]);
754            Aline=Aline(~isnan(A));
755            if isempty(Aline)
756                errormsg='NaN input scalar or image in plot_field';
757                return
758            end
759            MinA=double(min(Aline));
760        else
761            MinA=PlotParam.Scalar.MinA;
762        end;
763        if ~PlotParam.Scalar.CheckFixScalar||isempty(PlotParam.Scalar.MaxA)||~isa(PlotParam.Scalar.MaxA,'double') %correct if there is no numerical data in edit box
764            if isempty(Aline)
765                Aline=reshape(A,1,[]);
766                Aline=Aline(~isnan(A));
767                if isempty(Aline)
768                    errormsg='NaN input scalar or image in plot_field';
769                    return
770                end
771            end
772            MaxA=double(max(Aline));
773        else
774            MaxA=PlotParam.Scalar.MaxA;
775        end;
776        PlotParamOut.Scalar.MinA=MinA;
777        PlotParamOut.Scalar.MaxA=MaxA;
778        % case of contour plot
779        if CheckContour
780            if ~isempty(hima) && ishandle(hima)
781                delete(hima)
782            end
783            if ~isfield(PlotParam.Scalar,'IncrA')
784                PlotParam.Scalar.IncrA=NaN;
785            end
786            if isempty(PlotParam.Scalar.IncrA)|| isnan(PlotParam.Scalar.IncrA)% | PlotParam.Scalar.AutoScal==0
787                cont=colbartick(MinA,MaxA);
788                intercont=cont(2)-cont(1);%default
789                PlotParamOut.Scalar.IncrA=intercont;
790            else
791                intercont=PlotParam.Scalar.IncrA;
792            end
793            B=A;
794            abscontmin=intercont*floor(MinA/intercont);
795            abscontmax=intercont*ceil(MaxA/intercont);
796            contmin=intercont*floor(min(min(B))/intercont);
797            contmax=intercont*ceil(max(max(B))/intercont);
798            cont_pos_plus=0:intercont:contmax;
799            cont_pos_min=double(contmin):intercont:-intercont;
800            cont_pos=[cont_pos_min cont_pos_plus];
801            sizpx=(AX(end)-AX(1))/(np(2)-1);
802            sizpy=(AY(1)-AY(end))/(np(1)-1);
803            x_cont=AX(1):sizpx:AX(end); % pixel x coordinates for image display
804            y_cont=AY(1):-sizpy:AY(end); % pixel x coordinates for image display
805            % axes(haxes)% set the input axes handle as current axis
806            txt=ver('MATLAB');
807            Release=txt.Release;
808            relnumb=str2double(Release(3:4));
809            if relnumb >= 14
810                vec=linspace(0,1,(abscontmax-abscontmin)/intercont);%define a greyscale colormap with steps intercont
811                map=[vec' vec' vec'];
812                colormap(map);
813                [var,hcontour]=contour(x_cont,y_cont,B,cont_pos);
814                set(hcontour,'Fill','on')
815                set(hcontour,'LineStyle','none')
816                hold on
817            end
818            [var_p,hcontour_p]=contour(x_cont,y_cont,B,cont_pos_plus,'k-');
819            hold on
820            [var_m,hcontour_m]=contour(x_cont,y_cont,B,cont_pos_min,':');
821            set(hcontour_m,'LineColor',[1 1 1])
822            hold off
823            caxis([abscontmin abscontmax])
824            colormap(map);
825            if isfield(PlotParam.Coordinates,'CheckFixAspectRatio') && isequal(PlotParam.Coordinates.CheckFixAspectRatio,1)
826                set(haxes,'DataAspectRatioMode','manual')
827                if isfield(PlotParam.Coordinates,'AspectRatio')
828                    set(haxes,'DataAspectRatio',[PlotParam.Coordinates.AspectRatio 1 1])
829                else
830                    set(haxes,'DataAspectRatio',[1 1 1])
831                end
832            end
833        end
834       
835        % set  colormap for  image display
836        if ~CheckContour
837            % rescale the grey levels with min and max, put a grey scale colorbar
838            B=A;
839            if BW
840                vec=linspace(0,1,255);%define a linear greyscale colormap
841                map=[vec' vec' vec'];
842                colormap(map);  %grey scale color map
843            else
844                colormap('default'); % standard faulse colors for div, vort , scalar fields
845            end
846        end
847       
848        % case of color images
849    else
850        if BW
851            B=uint16(sum(A,3));
852        else
853            B=uint8(A);
854        end
855        MinA=0;
856        MaxA=255;
857    end
858   
859    % display usual image
860    if ~CheckContour
861        % interpolate field to increase resolution of image display
862        test_interp=1;
863        if max(np) <= 64
864            npxy=8*np;% increase the resolution 8 times
865        elseif max(np) <= 128
866            npxy=4*np;% increase the resolution 4 times
867        elseif max(np) <= 256
868            npxy=2*np;% increase the resolution 2 times
869        else
870            npxy=np;
871            test_interp=0; % no interpolation done
872        end
873        if test_interp==1%if we interpolate
874            x=linspace(AX(1),AX(2),np(2));
875            y=linspace(AY(1),AY(2),np(1));
876            [X,Y]=meshgrid(x,y);
877            xi=linspace(AX(1),AX(2),npxy(2));
878            yi=linspace(AY(1),AY(2),npxy(1));
879            B = interp2(X,Y,double(B),xi,yi');
880        end
881        % create new image if there  no image handle is found
882        if isempty(hima)
883            tag=get(haxes,'Tag');
884            if MinA<MaxA
885                hima=imagesc(AX,AY,B,[MinA MaxA]);
886            else % to deal with uniform field
887                hima=imagesc(AX,AY,B,[MaxA-1 MaxA]);
888            end
889            % the function imagesc reset the axes 'DataAspectRatioMode'='auto', change if .CheckFixAspectRatio is
890            % requested:
891            set(hima,'Tag','ima')
892            set(hima,'HitTest','off')
893            set(haxes,'Tag',tag);%preserve the axes tag (removed by image fct !!!)
894            uistack(hima, 'bottom')
895            % update an existing image
896        else
897            set(hima,'CData',B);
898            if MinA<MaxA
899                set(haxes,'CLim',[MinA MaxA])
900            else
901                set(haxes,'CLim',[MinA MaxA+1])
902            end
903            set(hima,'XData',AX);
904            set(hima,'YData',AY);
905        end
906
907        % set the transparency to 0.5 if vectors are also plotted
908        if isfield(PlotParam.Scalar,'Opacity')&& ~isempty(PlotParam.Scalar.Opacity)
909            set(hima,'AlphaData',PlotParam.Scalar.Opacity)
910        else
911            if test_vec
912                set(hima,'AlphaData',0.5)%set opacity to 0.5 by default in the presence of vectors
913                PlotParamOut.Scalar.Opacity=0.5;
914            else
915                set(hima,'AlphaData',1)% full opacity (no transparency) by default
916            end
917        end
918    end
919    test_ima=1;
920   
921    %display the colorbar code for B/W images if Poscolorbar not empty
922    if siz==2 && exist('PosColorbar','var')&& ~isempty(PosColorbar)
923        if isempty(hcol)||~ishandle(hcol)
924            hcol=colorbar;%create new colorbar
925        end
926        if length(PosColorbar)==4
927            set(hcol,'Position',PosColorbar)
928        end
929        %YTick=0;%default
930        if MaxA>MinA
931            if CheckContour
932                colbarlim=get(hcol,'YLim');
933                scale_bar=(colbarlim(2)-colbarlim(1))/(abscontmax-abscontmin);
934                YTick=cont_pos(2:end-1);
935                YTick_scaled=colbarlim(1)+scale_bar*(YTick-abscontmin);
936                set(hcol,'YTick',YTick_scaled);
937            elseif (isfield(PlotParam.Scalar,'CheckBW') && isequal(PlotParam.Scalar.CheckBW,1))||isa(A,'uint8')|| isa(A,'uint16')%images
938                hi=get(hcol,'children');
939                if iscell(hi)%multiple images in colorbar
940                    hi=hi{1};
941                end
942                set(hi,'YData',[MinA MaxA])
943                set(hi,'CData',(1:256)')
944                set(hcol,'YLim',[MinA MaxA])
945                YTick=colbartick(MinA,MaxA);
946                set(hcol,'YTick',YTick)
947            else
948                hi=get(hcol,'children');
949                if iscell(hi)%multiple images in colorbar
950                    hi=hi{1};
951                end
952                set(hi,'YData',[MinA MaxA])
953                set(hi,'CData',(1:64)')
954                YTick=colbartick(MinA,MaxA);
955                set(hcol,'YLim',[MinA MaxA])
956                set(hcol,'YTick',YTick)
957            end
958            set(hcol,'Yticklabel',num2str(YTick'));
959        end
960    elseif ishandle(hcol)
961        delete(hcol); %erase existing colorbar if not needed
962    end
963else%no scalar plot
964    if ~isempty(hima) && ishandle(hima)
965        delete(hima)
966    end
967    if ~isempty(hcol)&& ishandle(hcol)
968        delete(hcol)
969    end
970    PlotParamOut=rmfield(PlotParamOut,'Scalar');
971end
972
973%%   vector plot %%%%%%%%%%%%%%%%%%%%%%%%%%
974if test_vec
975   %vector scale representation
976    if size(vec_U,1)==numel(vec_Y) && size(vec_U,2)==numel(vec_X); % x, y  coordinate variables
977        [vec_X,vec_Y]=meshgrid(vec_X,vec_Y);
978    end   
979    vec_X=reshape(vec_X,1,numel(vec_X));%reshape in matlab vectors
980    vec_Y=reshape(vec_Y,1,numel(vec_Y));
981    vec_U=reshape(vec_U,1,numel(vec_U));
982    vec_V=reshape(vec_V,1,numel(vec_V));
983     MinMaxX=max(vec_X)-min(vec_X);
984    if  isfield(PlotParam.Vectors,'CheckFixVectors') && isequal(PlotParam.Vectors.CheckFixVectors,1)&& isfield(PlotParam.Vectors,'VecScale')...
985               &&~isempty(PlotParam.Vectors.VecScale) && isa(PlotParam.Vectors.VecScale,'double') %fixed vector scale
986        scale=PlotParam.Vectors.VecScale;  %impose the length of vector representation
987    else
988        if ~test_false %remove false vectors   
989            indsel=1:numel(vec_X);%
990        end
991        if isempty(vec_U)
992            scale=1;
993        else
994            if isempty(indsel)
995                MaxU=max(abs(vec_U));
996                MaxV=max(abs(vec_V));
997            else
998                MaxU=max(abs(vec_U(indsel)));
999                MaxV=max(abs(vec_V(indsel)));
1000            end
1001            scale=MinMaxX/(max(MaxU,MaxV)*50);
1002            PlotParam.Vectors.VecScale=scale;%update the 'scale' display
1003        end
1004    end
1005   
1006    %record vectors on the plotting axes
1007    if test_C==0
1008        vec_C=ones(1,numel(vec_X));
1009    end
1010   
1011    %decimate by a factor 2 in vector mesh(4 in nbre of vectors)
1012    if isfield(PlotParam.Vectors,'CheckDecimate4') && PlotParam.Vectors.CheckDecimate4
1013        diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
1014        dy_thresh=max(abs(diffy))/2;
1015        ind_jump=find(abs(diffy) > dy_thresh); %indices with diff(vec_Y)> max/2, detect change of line
1016        ind_sel=1:ind_jump(1);%select the first line
1017        for i=2:2:length(ind_jump)-1
1018            ind_sel=[ind_sel (ind_jump(i)+1:ind_jump(i+1))];% select the odd lines
1019        end
1020        nb_sel=length(ind_sel);
1021        ind_sel=ind_sel(1:2:nb_sel);% take half the points on a line
1022        vec_X=vec_X(ind_sel);
1023        vec_Y=vec_Y(ind_sel);
1024        vec_U=vec_U(ind_sel);
1025        vec_V=vec_V(ind_sel);
1026        vec_C=vec_C(ind_sel);
1027        if ~isempty(ivar_F)
1028           vec_F=vec_F(ind_sel);
1029        end
1030        if ~isempty(ivar_FF)
1031           vec_FF=vec_FF(ind_sel);
1032        end
1033    end
1034   
1035    %get main level color code
1036    [colorlist,col_vec,PlotParamOut.Vectors]=set_col_vec(PlotParam.Vectors,vec_C);
1037   
1038    % take flags into account: add flag colors to the list of colors
1039    sizlist=size(colorlist);
1040    nbcolor=sizlist(1);
1041    if test_black
1042       nbcolor=nbcolor+1;
1043       colorlist(nbcolor,:)=[0 0 0]; %add black to the list of colors
1044       if ~isempty(ivar_FF)
1045          %  ind_flag=find(vec_F~=1 & vec_F~=0 & vec_FF==0);  %flag warning but not false
1046            col_vec(vec_F~=1 & vec_F~=0 & vec_FF==0)=nbcolor;
1047       else
1048            col_vec(vec_F~=1 & vec_F~=0)=nbcolor;
1049       end
1050    end
1051    nbcolor=nbcolor+1;
1052    if ~isempty(ivar_FF)
1053        if isfield(PlotParam.Vectors,'CheckHideFalse') && PlotParam.Vectors.CheckHideFalse==1
1054            colorlist(nbcolor,:)=[NaN NaN NaN];% no plot of false vectors
1055        else
1056            colorlist(nbcolor,:)=[1 0 1];% magenta color
1057        end
1058        col_vec(vec_FF~=0)=nbcolor;
1059    end
1060    %plot vectors:
1061    quiresetn(haxes,vec_X,vec_Y,vec_U,vec_V,scale,colorlist,col_vec);   
1062
1063else
1064    hvec=findobj(haxes,'Tag','vel');
1065    if ~isempty(hvec)
1066        delete(hvec);
1067    end
1068    PlotParamOut=rmfield(PlotParamOut,'Vectors');
1069end
1070
1071%listfields={'AY','AX','A','X','Y','U','V','C','W','F','FF'};
1072%listdim={'AY','AX',{'AY','AX'},'nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors'};
1073%Role={'coord_y','coord_x','scalar','coord_x','coord_y','vector_x','vector_y','scalar','vector_z','warnflag','errorflag'};
1074%ind_select=[];
1075nbvar=0;
1076
1077%store the coordinate extrema occupied by the field
1078if ~isempty(Data)
1079    XMin=[];
1080    XMax=[];
1081    YMin=[];
1082    YMax=[];
1083    fix_lim=isfield(PlotParam.Coordinates,'CheckFixLimits') && PlotParam.Coordinates.CheckFixLimits;
1084    if fix_lim
1085        if isfield(PlotParam.Coordinates,'MinX')&&isfield(PlotParam.Coordinates,'MaxX')&&isfield(PlotParam.Coordinates,'MinY')&&isfield(PlotParam.Coordinates,'MaxY')
1086            XMin=PlotParam.Coordinates.MinX;
1087            XMax=PlotParam.Coordinates.MaxX;
1088            YMin=PlotParam.Coordinates.MinY;
1089            YMax=PlotParam.Coordinates.MaxY;
1090        end  %else PlotParamOut.XMin =PlotParam.XMin...
1091    else
1092        if test_ima %both background image and vectors coexist, take the wider bound
1093            XMin=min(AX);
1094            XMax=max(AX);
1095            YMin=min(AY);
1096            YMax=max(AY);
1097            if test_vec
1098                XMin=min(XMin,min(vec_X));
1099                XMax=max(XMax,max(vec_X));
1100                YMin=min(YMin,min(vec_Y));
1101                YMax=max(YMax,max(vec_Y));
1102            end
1103        elseif test_vec
1104            XMin=min(vec_X);
1105            XMax=max(vec_X);
1106            YMin=min(vec_Y);
1107            YMax=max(vec_Y);
1108        end
1109    end
1110%     PlotParamOut.RangeX=[XMin XMax]; %range of x, to be stored in the user data of the plot axes
1111%     PlotParamOut.RangeY=[YMin YMax]; %range of x, to be stored in the user data of the plot axes
1112%     if ~fix_lim
1113        PlotParamOut.Coordinates.MinX=XMin;
1114        PlotParamOut.Coordinates.MaxX=XMax;
1115        PlotParamOut.Coordinates.MinY=YMin;
1116        PlotParamOut.Coordinates.MaxY=YMax;
1117        if XMax>XMin
1118            set(haxes,'XLim',[XMin XMax]);% set x limits of frame in axes coordinates
1119        end
1120        if YMax>YMin
1121            set(haxes,'YLim',[YMin YMax]);% set x limits of frame in axes coordinates
1122        end
1123%     end
1124    set(haxes,'YDir','normal')
1125    set(get(haxes,'XLabel'),'String',[XName ' (' x_units ')']);
1126    set(get(haxes,'YLabel'),'String',[YName ' (' y_units ')']);
1127    PlotParamOut.Coordinates.x_units=x_units;
1128    PlotParamOut.Coordinates.y_units=y_units;
1129end
1130        if isfield(PlotParam,'Coordinates') && isfield(PlotParam.Coordinates,'CheckFixAspectRatio') && isequal(PlotParam.Coordinates.CheckFixAspectRatio,1)
1131            set(haxes,'DataAspectRatioMode','manual')
1132            if isfield(PlotParam.Coordinates,'AspectRatio')
1133                set(haxes,'DataAspectRatio',[PlotParam.Coordinates.AspectRatio 1 1])
1134            end
1135        else
1136            set(haxes,'DataAspectRatioMode','auto')
1137        end
1138%-------------------------------------------------------------------
1139% --- function for plotting vectors
1140%INPUT:
1141% haxes: handles of the plotting axes
1142% x,y,u,v: vectors coordinates and vector components to plot, arrays withb the same dimension
1143% scale: scaling factor for vector length representation
1144% colorlist(icolor,:): list of vector colors, dim (nbcolor,3), depending on color #i
1145% col_vec: matlab vector setting the color number #i for each velocity vector
1146function quiresetn(haxes,x,y,u,v,scale,colorlist,col_vec)
1147%-------------------------------------------------------------------
1148%define arrows
1149theta=0.5 ;%angle arrow
1150alpha=0.3 ;%length arrow
1151rot=alpha*[cos(theta) -sin(theta); sin(theta) cos(theta)]';
1152%find the existing lines
1153h=findobj(haxes,'Tag','vel');% search existing lines in the current axes
1154sizh=size(h);
1155set(h,'EraseMode','xor');
1156set(haxes,'NextPlot','replacechildren');
1157
1158%drawnow
1159%create lines (if no lines) or modify them
1160if ~isequal(size(col_vec),size(x))
1161    col_vec=ones(size(x));% case of error in col_vec input
1162end
1163sizlist=size(colorlist);
1164ncolor=sizlist(1);
1165
1166for icolor=1:ncolor
1167    %determine the line positions for each color icolor
1168    ind=find(col_vec==icolor);
1169    xc=x(ind);
1170    yc=y(ind);
1171    uc=u(ind)*scale;
1172    vc=v(ind)*scale;
1173    n=size(xc);
1174    xN=NaN*ones(size(xc));
1175    matx=[xc(:)-uc(:)/2 xc(:)+uc(:)/2 xN(:)]';
1176    matx=reshape(matx,1,3*n(2));
1177    maty=[yc(:)-vc(:)/2 yc(:)+vc(:)/2 xN(:)]';
1178    maty=reshape(maty,1,3*n(2));
1179   
1180    %determine arrow heads
1181    arrowplus=rot*[uc;vc];
1182    arrowmoins=rot'*[uc;vc];
1183    x1=xc+uc/2-arrowplus(1,:);
1184    x2=xc+uc/2;
1185    x3=xc+uc/2-arrowmoins(1,:);
1186    y1=yc+vc/2-arrowplus(2,:);
1187    y2=yc+vc/2;
1188    y3=yc+vc/2-arrowmoins(2,:);
1189    matxar=[x1(:) x2(:) x3(:) xN(:)]';
1190    matxar=reshape(matxar,1,4*n(2));
1191    matyar=[y1(:) y2(:) y3(:) xN(:)]';
1192    matyar=reshape(matyar,1,4*n(2));
1193    %draw the line or modify the existing ones
1194%     tri=reshape(1:3*length(uc),3,[])';   
1195    isn=isnan(colorlist(icolor,:));%test if color NaN
1196    if 2*icolor > sizh(1) %if icolor exceeds the number of existing ones
1197        if ~isn(1) %if the vectors are visible color not nan
1198            if n(2)>0
1199                hold on
1200                line(matx,maty,'Color',colorlist(icolor,:),'Tag','vel');% plot new lines
1201                line(matxar,matyar,'Color',colorlist(icolor,:),'Tag','vel');% plot arrows
1202            end
1203        end
1204    else
1205        if isn(1)
1206            delete(h(2*icolor-1))
1207            delete(h(2*icolor))
1208        else
1209            set(h(2*icolor-1),'Xdata',matx,'Ydata',maty);
1210            set(h(2*icolor-1),'Color',colorlist(icolor,:));
1211            set(h(2*icolor-1),'EraseMode','xor');
1212            set(h(2*icolor),'Xdata',matxar,'Ydata',matyar);
1213            set(h(2*icolor),'Color',colorlist(icolor,:));
1214            set(h(2*icolor),'EraseMode','xor');
1215        end
1216    end
1217end
1218if sizh(1) > 2*ncolor
1219    for icolor=ncolor+1 : sizh(1)/2%delete additional objects
1220        delete(h(2*icolor-1))
1221        delete(h(2*icolor))
1222    end
1223end
1224
1225%-------------------------------------------------------------------
1226% ---- determine tick positions for colorbar
1227function YTick=colbartick(MinA,MaxA)
1228%-------------------------------------------------------------------
1229%determine tick positions with "simple" values between MinA and MaxA
1230YTick=0;%default
1231maxabs=max([abs(MinA) abs(MaxA)]);
1232if maxabs>0
1233ord=10^(floor(log10(maxabs)));%order of magnitude
1234div=1;
1235siz2=1;
1236while siz2<2
1237    values=-10:div:10;
1238    ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);%indices of 'values' such that MinA<ord*values<MaxA
1239    siz=size(ind);
1240    if siz(2)<4%if there are less than 4 selected values (4 levels)
1241        values=-9:0.5*div:9;
1242        ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);
1243    end
1244    siz2=size(ind,2);
1245    div=div/10;
1246end
1247YTick=ord*values(ind);
1248end
1249
1250% -------------------------------------------------------------------------
1251% --- 'proj_grid': project  fields with unstructured coordinantes on a regular grid
1252function [A,rangx,rangy]=proj_grid(vec_X,vec_Y,vec_A,rgx_in,rgy_in,npxy_in)
1253% -------------------------------------------------------------------------
1254if length(vec_Y)<2
1255    msgbox_uvmat('ERROR','less than 2 points in proj_grid.m');
1256    return;
1257end
1258diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
1259index=find(diffy);% find the indices of vec_Y after wich a change of horizontal line occurs(diffy non zero)
1260if isempty(index); msgbox_uvmat('ERROR','points aligned along abscissa in proj_grid.m'); return; end;%points aligned% A FAIRE: switch to line plot.
1261diff2=diff(diffy(index));% diff2 = fluctuations of the detected vertical grid mesh dy
1262if max(abs(diff2))>0.001*abs(diffy(index(1))) % if max(diff2) is larger than 1/1000 of the first mesh dy
1263    % the data are not regularly spaced and must be interpolated  on a regular grid
1264    if exist('rgx_in','var') & ~isempty (rgx_in) & isnumeric(rgx_in) & length(rgx_in)==2%  positions imposed from input
1265        rangx=rgx_in; % first and last positions
1266        rangy=rgy_in;
1267        dxy(1)=1/(npxy_in(1)-1);%grid mesh in y
1268        dxy(2)=1/(npxy_in(2)-1);%grid mesh in x
1269        dxy(1)=(rangy(2)-rangy(1))/(npxy_in(1)-1);%grid mesh in y
1270        dxy(2)=(rangx(2)-rangx(1))/(npxy_in(2)-1);%grid mesh in x
1271    else % interpolation grid automatically determined
1272        rangx(1)=min(vec_X);
1273        rangx(2)=max(vec_X);
1274        rangy(2)=min(vec_Y);
1275        rangy(1)=max(vec_Y);
1276        dxymod=sqrt((rangx(2)-rangx(1))*(rangy(1)-rangy(2))/length(vec_X));
1277        dxy=[-dxymod/4 dxymod/4];% increase the resolution 4 times
1278    end
1279    xi=[rangx(1):dxy(2):rangx(2)];
1280    yi=[rangy(1):dxy(1):rangy(2)];
1281    A=griddata_uvmat(vec_X,vec_Y,vec_A,xi,yi');
1282    A=reshape(A,length(yi),length(xi));
1283else
1284    x=vec_X(1:index(1));% the set of abscissa (obtained on the first line)
1285    indexend=index(end);% last vector index of line change
1286    ymax=vec_Y(indexend+1);% y coordinate AFTER line change
1287    ymin=vec_Y(index(1));
1288    y=vec_Y(index);
1289    y(length(y)+1)=ymax;
1290    nx=length(x);   %number of grid points in x
1291    ny=length(y);   % number of grid points in y
1292    B=(reshape(vec_A,nx,ny))'; %vec_A reshaped as a rectangular matrix
1293    [X,Y]=meshgrid(x,y);% positions X and Y also reshaped as matrix
1294
1295    %linear interpolation to improve the image resolution and/or adjust
1296    %to prescribed positions
1297    test_interp=1;
1298    if exist('rgx_in','var') & ~isempty (rgx_in) & isnumeric(rgx_in) & length(rgx_in)==2%  positions imposed from input
1299        rangx=rgx_in; % first and last positions
1300        rangy=rgy_in;
1301        npxy=npxy_in;
1302    else       
1303        rangx=[vec_X(1) vec_X(nx)];% first and last position found for x
1304          rangy=[max(ymax,ymin) min(ymax,ymin)];
1305        if max(nx,ny) <= 64 & isequal(npxy_in,'np>256')
1306            npxy=[8*ny 8*nx];% increase the resolution 8 times
1307        elseif max(nx,ny) <= 128 & isequal(npxy_in,'np>256')
1308            npxy=[4*ny 4*nx];% increase the resolution 4 times
1309        elseif max(nx,ny) <= 256 & isequal(npxy_in,'np>256')
1310            npxy=[2*ny 2*nx];% increase the resolution 2 times
1311        else
1312            npxy=[ny nx];
1313            test_interp=0; % no interpolation done
1314        end
1315    end
1316    if test_interp==1%if we interpolate
1317        xi=[rangx(1):(rangx(2)-rangx(1))/(npxy(2)-1):rangx(2)];
1318        yi=[rangy(1):(rangy(2)-rangy(1))/(npxy(1)-1):rangy(2)];
1319        [XI,YI]=meshgrid(xi,yi);
1320        A = interp2(X,Y,B,XI,YI);
1321    else %no interpolation for a resolution higher than 256
1322        A=B;
1323    end
1324end
Note: See TracBrowser for help on using the repository browser.