source: trunk/src/plot_field.m @ 728

Last change on this file since 728 was 690, checked in by sommeria, 11 years ago

representation of ancillary data as table improved.

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