source: trunk/src/plot_field.m @ 530

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

new conventions for find_field_cells .

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