% KDEDEMO1    Demonstrate UIControls with 1D Kernel Density Estimates.
%
%             Example: data=randn(500,1); (optional - defines data)
%                      kdedemo1    
%
%             Menus: (a) DATA - A choice of several 1D data sets.
%                    (b) PRINT STYLE - A choice of four print styles.
%                    (c) COLOUR - A choice of several print colours.
%
%             Pop-ups: (a) KERNEL - A choice of several well-known kernel functions.
%                      (b) HSELECT - A choice of several data-based h selection strategies.
%
%             Check-boxes: (a) ADAPTIVE - Turns adaptive method on/off.
%                          (b) HOLD - Holds the current plot allowing multiple
%                                     plots on the same axes.
%                          (c) FIX H - Fix the value of h for all subsequent plots.
%                          (d) ADD BUMPS - Add individual kernel bumps to the plot.
%                          (e) ADD MAX - Find local maxima.
%                          (f) CANONICAL KERNELS - Use canonical kernels.
%                          (g) CDF - Cumulative Density Function.
%                          (h) HIST - Display histogram.
%                          (i) REPLACE - Sample with replacement (when checked).
%
%             Push buttons: (a) END - Quit demonstration,
%                           (b) HELP - Output these comments.
%
%             Editable text: (a) H - Click here to enter a value for H.  Values 
%                                of H=0 cause the routine to use an 'optimal' 
%                                value.
%                            (b) BINS - No. of bins in histogram.
%                            (c) SSIZE - Sample size.
% 
%             Christian C. Beardah 1995/97

echo off

% Initialize

load kddata;

if exist('data')==0,
  data=lukesh1(:,1);
  import=0;
  else,
    data=data(:,1);
    import=1;
end;

temp=data;
col='y';
sym=['- ';'--';'-.';': '];

xmin=min(data);
xmax=max(data);
xrange=xmax-xmin;
ax=xmin-xrange/4;
bx=xmax+xrange/4;

fix=0;
kernel='knorm';
count=1;
sstr='-';
pstr=[col,sstr];
mesh=512;
adapt=0;
h=hns(data,kernel);

figure('Name','Uni-variate KDE demo');

black=[0 0 0];
set(gcf,'color',black');
gcfpos = zeros(1,4);

[x,y]=kdfft1(data,kernel,mesh,h,0,[ax,bx]);
plot(x,y,'y-');
title(['h = ',num2str(h)]);
xlabel('x values');
ylabel('Density');

% Callback strings

helps = 'help kdedemo1;';

ends = 'close; clear global; clear; load kddata;';

hoffs = ['hold off; set(holdh,''value'',0);'];

hons = ['hold on; set(holdh,''value'',1);'];

holds = ['if get(holdh,''value'')==1, hold on; else,', hoffs ,'end;'];

cdfoffs = ['set(cdfh,''value'',0);'];

ranges = ['xmin=min(data); xmax=max(data); xrange=xmax-xmin; ax=xmin-xrange/4; bx=xmax+xrange/4; xinc=xrange/mesh;'];

fixhs = ['if get(fixhh,''value'')==1, fix=1; else, fix=0; end;'];

replaces = ['if get(replaceh,''value'')==1, rep=1; else, rep=0; end;'];

canons = ['if get(canonh,''value'')==1, kernel(1)=''c''; else, kernel(1)=''k''; end; '];

titles = ['if exist(''yd''), title([''Absolute error = '',num2str(xinc*sum(abs(y(:)-yd(:)))),''; Squared error = '',num2str(xinc*sum((y(:)-yd(:)).^2))]);',...
          'xlabel(''x values''); ylabel(''Density''); else, title([''h = '',num2str(h)]); xlabel(''x values''); ylabel(''Density''); end;',...
          'if get(cdfh,''value'')==1, title([''h = '',num2str(h)]); xlabel(''x values''); ylabel(''Cumulative Density''); end;'];

calcs = ['if adapt==0, [x,y]=kdfft1(data,kernel,mesh,h,0,[ax,bx]); else, [x,z,y,h,hl]=kdplot(data,kernel,mesh,adapt,h,0); end;',...
        'if exist(''yd''), plot(x,yd,''c''); hold on; end; pstr=[col,sstr]; plot(x,y,pstr);', holds];

plotbumps = ['n=length(data); hold on; for i=1:n, if adapt==0, yb=feval(kernel,(x-data(i))/h)/(n*h); else,',...
             'yb=feval(kernel,(x-data(i))/hl(i))/(n*hl(i)); end; plot(x,yb,''w--''); end;', holds];

plotmaxs = ['[pmax,cmax]=bump1(x,y,0.01); pmax, hold on; plot(pmax(:,1),pmax(:,2),''cx'');', holds];

plothists = [cdfoffs, 'n=length(data); plot(x,y,pstr); hold on; if exist(''yd''), plot(x,yd,''c''); end;bins=str2num(get(binsh,''string''));',...
             '[hn,hx]=hist(data,bins); hn=hn/((hx(2)-hx(1))*n); bar(hx,hn,''w--'');',...
             'if get(histh,''value'')==0, set(histh,''value'',1); end;',...
             'v=get(bumpsh,''value''); if v==1,', plotbumps, 'end;',...
             'v=get(maxh,''value''); if v==1,', plotmaxs, 'end;'];

bmhs = ['v=get(bumpsh,''value''); if v==1,', plotbumps, 'end;',...
        'v=get(maxh,''value''); if v==1,', plotmaxs, 'end;',...
        'v=get(histh,''value''); if v==1,', plothists, 'end;'];

plots = [ranges, cdfoffs, canons, calcs, titles, bmhs];

hvals = ['h=str2num(get(hvalh,''string'')); if h<0, disp(''ERROR - negative h''); else,',plots,'end;', holds];

bumps = ['v=get(bumpsh,''value''); if v==1 & get(cdfh,''value'')==0,', plotbumps, 'else,', plots ,'end;', holds];

maxs = ['v=get(maxh,''value''); if v==1 & get(cdfh,''value'')==0,', plotmaxs, 'else,', plots ,'end;', holds];

hists = ['v=get(histh,''value''); if v==1,', plothists, 'else,', plots ,'end;', holds];

adapts = ['if get(adapth,''value'')==1, adapt=1; else, adapt=0; end;', hvals;];

cdfs = ['pstr=[col,sstr]; if get(cdfh,''value'')==1,', hoffs ,'cy=cdf(x,y); plot(x,cy,pstr),',...
        'else, if exist(''yd''), plot(x,yd,''c''); hold on; end; plot(x,y,pstr);',bmhs,'end;', titles];

hselects = ['v=get(hselecth,''value'');',...
           'if v==1 & kernel(1)==''k'', h=hns(data,kernel);',...
           'elseif v==2 & kernel==''knorm'', h=hdpi(data,kernel,1);',...
           'elseif v==3 & kernel==''knorm'', h=hdpi(data,kernel,2);',...
           'elseif v==4 & kernel==''knorm'', h=hdpi(data,kernel,3);',...
           'elseif v==5 & kernel==''knorm'', h=hste(data,kernel);',...
           'elseif v==8 & kernel==''knorm'', h=hlscv(data,kernel);',...
           'elseif v==7 & kernel==''knorm'', h=hbcv(data,kernel);',...
           'elseif v==6 & kernel==''knorm'', h=hscv(data,kernel);',...
           'else, kernel(1)=''k''; h=hns(data,kernel); set(hselecth,''value'',1);',...
           'set(canonh,''value'',0); end;',...
           'set(hvalh,''string'',num2str(h));', plots];

ssvals = [replaces,'ss=str2num(get(ssvalh,''string'')); set(ssvalh,''string'',num2str(ss)),',...
          'if ss<=0 | ss>length(temp), disp(''ERROR - illegal sample size''); ss=length(temp);',...
          'set(ssvalh,''string'',num2str(ss)); else, data=sample(temp,ss,rep);',fixhs,'if fix==0,',hselects,'else,',plots,'end; end;'];

kerpops = ['v=get(kerpoph,''value''); if v==1, kernel=''knorm'';',...
           'elseif v==2, kernel=''kepan'';',...
           'elseif v==3, kernel=''krect'';',...
           'elseif v==4, kernel=''ktria'';',...
           'elseif v==5, kernel=''kbiwe'';',...
           'elseif v==6, kernel=''ktriw'';',...
           'elseif v==7, kernel=''klapl'';',...
           'elseif v==8, kernel=''klogi'';',...
           'end;',fixhs,'if fix==0,',hselects,'else,',plots,'end;'];

% Frames

frame1h = uicontrol('style','frame','units','normal','pos',[.84 .73 .15 .2]);

frame2h = uicontrol('style','frame','units','normal','pos',[.84 .53 .15 .13]);

frame3h = uicontrol('style','frame','units','normal','pos',[.84 .39 .15 .13]);

frame4h = uicontrol('style','frame','units','normal','pos',[.84 .31 .15 .07]);

% Check boxes

adapth = uicontrol('style','checkbox','units','normal','pos',[.85 .86 .13 .05],...
  'string','Adaptive','call',adapts);

holdh = uicontrol('style','checkbox','units','normal','pos',[.85 .74 .09 .05],...
  'string','Hold','call',holds);

canonh = uicontrol('style','checkbox','units','normal','pos',[.83 .02 .15 .035],...
  'string','C Kernels','call',canons);

fixhh = uicontrol('style','checkbox','units','normal','pos',[.02 .02 .15 .035],...
  'string','Fix h','call',fixhs);

bumpsh = uicontrol('style','checkbox','units','normal','pos',[.2 .02 .15 .035],...
  'string','Add bumps','call',bumps);

maxh = uicontrol('style','checkbox','units','normal','pos',[.65 .02 .15 .035],...
  'string','Add max','call',maxs);

replaceh = uicontrol('style','checkbox','units','normal','pos',[.85 .54 .13 .05],...
  'string','Replace','call',replaces);

histh = uicontrol('style','checkbox','units','normal','pos',[.85 .4 .13 .05],...
  'string','Hist.','call',hists);

cdfh = uicontrol('style','checkbox','units','normal','pos',[.85 .32 .13 .05],...
  'string','CDF','call',cdfs);

% Pop-up menus

kerpoph = uicontrol('style','popupmenu','units','normal','pos',[.8 .91 .19 .08],...
  'string','Normal|Epanechnikov|Rectangular|Triangular|Biweight|Triweight|Laplace|Logistic','call',kerpops);   

hselecth = uicontrol('style','popupmenu','units','normal','pos',[.8 .64 .19 .08],...
  'string','Normal Scale*|DPI,1|DPI,2|DPI,3|STE,2|SmoothedCV|BiasedCV|LSCV','call',hselects);   

datamenus = ['set(suich,''checked'',''off''),',...
             'set(geysh,''checked'',''off''),',...
             'set(snowh,''checked'',''off''),',...
             'set(pinsh,''checked'',''off''),',...
             'set(cupdh,''checked'',''off''),',...
             'set(glass5h,''checked'',''off''),',...
             'set(glass8h,''checked'',''off''),',...
             'set(n01h,''checked'',''off''),',...
             'set(nmdah,''checked'',''off''),',...
             'set(nmdbh,''checked'',''off''),',...
             'set(nmdch,''checked'',''off''),',...
             'set(smallh,''checked'',''off''),',...
             'set(diamh,''checked'',''off'');'];

% Menus

datamenuh = uimenu(gcf,'label','Data');

suich = uimenu(datamenuh,'label','Suicide Time (86)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=suicide;',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(suich,''checked'',''on'')']);
geysh = uimenu(datamenuh,'label','Old Faithful (107)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=geyser;',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(geysh,''checked'',''on'')']);
snowh = uimenu(datamenuh,'label','Buffalo Snowfall (63)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=snowfall;',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(snowh,''checked'',''on'')']);
diamh = uimenu(datamenuh,'label','Pot Diameters (81)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=maddiam;',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(diamh,''checked'',''on'')']);
pinsh = uimenu(datamenuh,'label','Hairpin Lengths (224)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=pins10(:,1);',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(pinsh,''checked'',''on'')']);
cupdh = uimenu(datamenuh,'label','Cup Diameters (60)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=lukesh1(:,1);',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(cupdh,''checked'',''on'')']);
glass5h = uimenu(datamenuh,'label','Nickel (361)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=glass(:,5);',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(glass5h,''checked'',''on'')']);
glass8h = uimenu(datamenuh,'label','Manganese (361)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=glass(:,8);',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(glass8h,''checked'',''on'')']);
smallh = uimenu(datamenuh,'label','Small (7)','callback',...
  [hoffs,'clear yd; set(hvalh,''string'',num2str(h)); data=small;',ranges,'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(smallh,''checked'',''on'')']);
n01h = uimenu(datamenuh,'label','(D) N(0,1) (500)','callback',...
  ['check=get(n01h,''checked''); if check(2)==''f'',',hoffs,'end; set(hvalh,''string'',num2str(h)); data=randn(500,1);', ranges,...
   'x=linspace(ax,bx,mesh); yd=npdf(x)''; plot(x,yd,''c''); hold on; set(holdh,''value'',1);',...
   'temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(n01h,''checked'',''on'')']);
nmdah = uimenu(datamenuh,'label','(D) Mixture Density A (500)','callback',...
  ['check=get(nmdah,''checked''); if check(2)==''f'',',hoffs,'end; set(hvalh,''string'',num2str(h));',...
   'data=snmd(500,[0.75 0.25]'',[1 1/3]'',[0 3/2]'');',ranges,'x=linspace(ax,bx,mesh); yd=nmdplot(x,[0.75 0.25]'',[1 1/3]'',[0 3/2]'')'';',...
   'hold on; set(holdh,''value'',1); temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(nmdah,''checked'',''on'')']);
nmdbh = uimenu(datamenuh,'label','(D) Mixture Density B (500)','callback',...
  ['check=get(nmdbh,''checked''); if check(2)==''f'',',hoffs,'end; set(hvalh,''string'',num2str(h));',...
   'data=snmd(500,[1/3 1/3 1/3]'',[1/2 1/3 1/2]'',[-3/2 0 3/2]'');',ranges,'x=linspace(ax,bx,mesh); yd=nmdplot(x,[1/3 1/3 1/3]'',[1/2 1/3 1/2]'',[-3/2 0 3/2]'')'';',...
   'hold on; set(holdh,''value'',1); temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(nmdbh,''checked'',''on'')']);
nmdch = uimenu(datamenuh,'label','(D) Mixture Density C (500)','callback',...
  ['check=get(nmdch,''checked''); if check(2)==''f'',',hoffs,'end; set(hvalh,''string'',num2str(h));',...
   'data=snmd(500,[0.25 0.25 0.25 0.25]'',[1/4 1/2 1 7/4]'',[-3/4 -1/4 2/3 5/2]'');',ranges,'x=linspace(ax,bx,mesh); yd=nmdplot(x,[0.25 0.25 0.25 0.25]'',[1/4 1/2 1 7/4]'',[-3/4 -1/4 2/3 5/2]'')'';',...
   'hold on; set(holdh,''value'',1); temp=data; set(ssvalh,''string'',num2str(length(data)));', hselects,...
   'if get(fixhh,''value'')==1, set(fixhh,''value'',0); end;',...
   'if get(canonh,''value'')==1, set(canonh,''value'',0); end;', datamenus,...
   'set(nmdch,''checked'',''on'')']);

sstrmenus = ['set(solidh,''checked'',''off''),',...
             'set(dashh,''checked'',''off''),',...
             'set(dotdashh,''checked'',''off''),',...
             'set(doth,''checked'',''off'');'];

sstrmenuh = uimenu(gcf,'label','Print style');

solidh = uimenu(sstrmenuh,'label','Solid','callback',...
  ['sstr=''-'';', sstrmenus, 'set(solidh,''checked'',''on'')']);
dashh = uimenu(sstrmenuh,'label','Dashed','callback',...
  ['sstr=''--'';', sstrmenus, 'set(dashh,''checked'',''on'')']);
dotdashh = uimenu(sstrmenuh,'label','Dash-dotted','callback',...
  ['sstr=''-.'';', sstrmenus, 'set(dotdashh,''checked'',''on'')']);
doth = uimenu(sstrmenuh,'label','Dotted','callback',...
  ['sstr='':'';', sstrmenus, 'set(doth,''checked'',''on'')']);

set(solidh,'checked','on');

colmenus = ['set(yellowh,''checked'',''off''),',...
            'set(redh,''checked'',''off''),',...
            'set(whiteh,''checked'',''off''),',...
            'set(blueh,''checked'',''off''),',...
            'set(magentah,''checked'',''off''),',...
            'set(cyanh,''checked'',''off''),',...
            'set(greenh,''checked'',''off'');'];

colmenuh = uimenu(gcf,'label','Colour');

yellowh = uimenu(colmenuh,'label','Yellow','callback',...
  ['col=''y'';', colmenus, 'set(yellowh,''checked'',''on'')']);
redh = uimenu(colmenuh,'label','Red','callback',...
  ['col=''r'';', colmenus, 'set(redh,''checked'',''on'')']);
whiteh = uimenu(colmenuh,'label','White','callback',...
  ['col=''w'';', colmenus, 'set(whiteh,''checked'',''on'')']);
blueh = uimenu(colmenuh,'label','Blue','callback',...
  ['col=''b'';', colmenus, 'set(blueh,''checked'',''on'')']);
magentah = uimenu(colmenuh,'label','Magenta','callback',...
  ['col=''m'';', colmenus, 'set(magentah,''checked'',''on'')']);
cyanh = uimenu(colmenuh,'label','Cyan','callback',...
  ['col=''c'';', colmenus, 'set(cyanh,''checked'',''on'')']);
greenh = uimenu(colmenuh,'label','Green','callback',...
  ['col=''g'';', colmenus, 'set(greenh,''checked'',''on'')']);

set(yellowh,'checked','on');

if import==0,
  set(cupdh,'checked','on');
end;

% Push buttons

endh = uicontrol('style','push','units','normal','pos',[.91 .19 .08 .06],...
        'string','End','call',ends);
helph = uicontrol('style','push','units','normal','pos',[.91 .11 .08 .06],...
        'string','Help','call',helps);

% Editable text

hvalh = uicontrol('style','edit','units','normal','pos',[.91 .8 .05 .04],...
        'string',num2str(h),'min',0,'call',hvals);
hvalt = uicontrol('style','text','units','normal','pos',[.85 .8 .05 .04],...
     'string','h:');
ssvalh = uicontrol('style','edit','units','normal','pos',[.93 .6 .05 .04],...
     'string',num2str(length(data)),'min',1,'call',ssvals);
ssvalt = uicontrol('style','text','units','normal','pos',[.85 .6 .07 .04],...
     'string','Ssize:');
binsh = uicontrol('style','edit','units','normal','pos',[.93 .46 .05 .04],...
     'string','10','min',1,'call',plots);
binst = uicontrol('style','text','units','normal','pos',[.85 .46 .07 .04],...
     'string','Bins:');