source: trunk/src/plot_field.m @ 537

Last change on this file since 537 was 537, checked in by sommeria, 9 years ago

various bugs fixed. Use of the free pair option '*-*' in series.

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