source: trunk/src/plot_field.m @ 625

Last change on this file since 625 was 625, checked in by sommeria, 8 years ago

system of object creation by mouse ilmproved

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