source: trunk/src/plot_field.m @ 389

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

several bugs corrected: object managing, tps filter...

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