source: trunk/src/plot_field.m @ 644

Last change on this file since 644 was 644, checked in by sommeria, 8 years ago

various improvements: resize GUI uvmat, projection on lines

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