source: trunk/src/plot_field.m @ 575

Last change on this file since 575 was 569, checked in by sommeria, 11 years ago

many corrections; introduction of browse_data to scan the whole set of data, used also to replicate data in calibration mode

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