source: trunk/src/plot_field.m @ 535

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

various bugs fixed, in particular patch projection with color images

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