function test12
%TEST12 test cs_qr and compare with svd
%
% Example:
%   test12
% See also: testall

%   Copyright 2006-2007, Timothy A. Davis.
%   http://www.cise.ufl.edu/research/sparse

fprintf ('test 12\n') ;
rand ('state',0) ;
% A = rand (3,4)

for trial = 1:100
    m = fix (100 * rand (1)) ;
    n = fix (100 * rand (1)) ;
    d = .1 * rand (1) ;
    A = sprandn (m,n,d) ;
    fprintf ('m %d n %d nnz %d\n', m, n, nnz(A)) ;
    if (m < n)
        continue ;
    end
    if (m == 0 | n == 0)                                                    %#ok
        continue ;
    end
    % save A A
    fprintf ('[ ') ;
    [V,Beta,p,R] = cs_qr (A) ;
    % [Q,R] = svd (full(A)) ;
    fprintf (']\n') ;

    s1 = svd (full (A)) ;
    s2 = svd (full (R)) ;
    s2 = s2 (1:length(s1)) ;
    err = norm (s1-s2) ;
    if (length (s1) > 1)
        err = err / s1 (1) ;
    end
    fprintf ('err %g\n', err) ;
    if (err > 1e-12)
        error ('!') ;
    end
end


function [pnt,jac] = nrbdeval(nurbs, dnurbs, tt)
% Evaluation of the derivative NURBS curve or surface.
%
%     [pnt, jac] = nrbdeval(crv, dcrv, tt)
%     [pnt, jac] = nrbdeval(srf, dsrf, {tu tv})
%
% INPUTS:
%
%   crv    - original NURBS curve.
%
%   srf    - original NUBRS surface
%
%   dcrv   - NURBS derivative represention of crv
%
%   dsrf   - NURBS derivative represention of surface
%
%   tt     - parametric evaluation points
%            If the nurbs is a surface then tt is a cell
%            {tu, tv} are the parametric coordinates
%
%   pnt  - evaluated points.
%   jac  - evaluated first derivatives (Jacobian).
%
% Examples:
%
%   // Determine the first derivatives a NURBS curve at 9 points for 0.0 to
%   // 1.0
%   tt = linspace(0.0, 1.0, 9);
%   dcrv = nrbderiv(crv);
%   [pnts,jac] = nrbdeval(crv, dcrv, tt);

%  D.M. Spink
%  Copyright (c) 2000.

if ~isstruct(nurbs)
  error('NURBS representation is not structure!');
end

if ~strcmp(nurbs.form,'B-NURBS')
  error('Not a recognised NURBS representation');
end

[cp,cw] = nrbeval(nurbs, tt);

if iscell(nurbs.knots)

  % NURBS structure represents a surface
  temp = cw(ones(3,1),:,:);
  pnt = cp./temp;

  [cup,cuw] = nrbeval(dnurbs{1}, tt);
  tempu = cuw(ones(3,1),:,:);
  jac{1} = (cup-tempu.*pnt)./temp;

  [cvp,cvw] = nrbeval(dnurbs{2}, tt);
  tempv = cvw(ones(3,1),:,:);
  jac{2} = (cvp-tempv.*pnt)./temp;

else

  % NURBS is a curve
  temp = cw(ones(3,1),:);
  pnt = cp./temp;

  % first derivative
  [cup,cuw] = nrbeval(dnurbs,tt);
  temp1 = cuw(ones(3,1),:);
  jac = (cup-temp1.*pnt)./temp;

end


% Example using the k-means algorithm function on an image and clustering
% the letters as seperate clusters

test = imread('Example.bmp');
test = test>=100;
test = test(:,:,1);

imagesc(test); colormap('gray')

% initial guess
means = [100,100; 200, 200; 150, 300; 50, 300];

hold on

% before the first step
plot(means(:,2),means(:,1),'o','Color',[1,0,0],'MarkerSize',10,'LineWidth',4)

% one step
means = kmean(test,means);
plot(means(:,2),means(:,1),'o','Color',[0,1,0],'MarkerSize',10,'LineWidth',4)

% second step
means = kmean(test,means);
plot(means(:,2),means(:,1),'o','Color',[0,0,1],'MarkerSize',10,'LineWidth',4)


function [jj,tx,j,a,v,p,tt]=profile3(t,j,acc,plt)

% function [jj,tx,j,a,v,p,tt]=profile3(t,j,acc)
%
% Calculate symmetrical third order profiles from times:
%
%  Inputs:
%
%      t(1) = constant jerk phase duration
%      t(2) = constant acceleration phase duration (default 0)
%      t(3) = constant velocity phase duration (default 0)
%
%      j    = bound on jerk
%      acc  = continuous time: accuracy for profiles: t(1)*acc = minimal timestep
%             discrete time:   sample time
%
%  Outputs:
%
%      jj  = derivative of jerk profile suitable for simulink
%
%      tx  = time sequence for plotting profiles
%      j   = jerk profile
%      a   = acceleration profile
%      v   = velocity profile
%      p   = position profile
%
%      tt  = 8 switching times for profile:
%
%       0 1              6 7
%       .-.              .-.
%       | |              | |
%       | |  2 3    4 5  | |
%       '-'--.-.----.-.--' '--
%            | |    | |
%            | |    | |
%            '-'    '-'
%
%  Note: coinciding switching times are not removed

%
% Copyright 2004, Paul Lambrechts, The MathWorks, Inc.
%

if nargin < 3 || nargin > 4
    help profile3
    return
end
if nargin==3
    plt=1;
end

if length(t)==1  % min distance with max jerk
    tt=   [0 1 1 2 2 3 3 4 ]*t;

elseif length(t)==2 % constant acceleration phase
    tt=   [0 1 1 2 2 3 3 4 ]*t(1) ...
        + [0 0 1 1 1 1 2 2 ]*t(2);

elseif length(t)==3 % constant velocity phase
    tt=   [0 1 1 2 2 3 3 4 ]*t(1) ...
        + [0 0 1 1 1 1 2 2 ]*t(2) ...
        + [0 0 0 0 1 1 1 1 ]*t(3) ;
else
    return
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generate Simulink look-up table
jt=[];
for i=1:8
    jt =  [jt   [1 1] * tt(i) ]  ;
end
jt  = [jt 1.5*tt(8)];

jj  = [jt ; [ 0 j j 0 0 -j -j 0 0 -j -j 0 0 j j 0 0 ] ];

if plt==0  % no plot required
    tx=[];j=[];a=[];v=[];p=[];    % dummy outputs
    return
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generate profiles for plotting

% Determine continuous or discrete
if max(abs( round(t/acc)-t/acc )) > 1e-12 % continuous

   disp('Calculating continuous time profiles')
   step = t(1)*acc;
   tx=0:step:1.2*tt(8);
   x=[];
   for i=0:step:1.2*tt(8)
       j=find(i<=jj(1,:));
       x=[x ; jj(2,j(1))];
   end
   j=x;
   a=cumsum(j)*step;
   v=cumsum(a)*step;
   p=cumsum(v)*step;

else % discrete

   disp('Calculating discrete time profiles')
   Ts=acc;
   ttest=[tt 1.5*tt(8)];
   len = round(1.2*tt(8)/Ts + 1); % length of profiles
   xj = zeros(len,1);
   xa = xj;
   xv = xj;
   xp = xj;
   xj(1) = j;
   tx=0:Ts:1.2*tt(8)+Ts/2;
   for time=Ts:Ts:(1.2*tt(8)+Ts/2)
      i = find( (time + Ts/2) <= ttest ); i = i(1)-1;
      k = round(time/Ts);
      if i==1 || i==7
          xj(k+1) =  j;
      elseif i==3 || i==5
          xj(k+1) = -j;
      else
          xj(k+1) =  0;
      end
      xa(k+1) = xa(k) + xj(k)*Ts;
      xv(k+1) = xv(k) + xa(k)*Ts;
      xp(k+1) = xp(k) + xv(k)*Ts;
   end
   j=xj;a=xa;v=xv;p=xp;

end

%close all
%figure
subplot(411);plot(tx,j,'k','LineWidth',1.5);hold on;plot([0 0],[-1 1]*max(j),'k--',[1 1]*max(tt),[-1 1]*max(j),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-1.1 1.1]*max(j)]);
title('Third order trajectory profiles');ylabel('j [m/s3]');
subplot(412);plot(tx,a,'k','LineWidth',1.5);hold on;plot([0 0],[-1 1]*max(a),'k--',[1 1]*max(tt),[-1 1]*max(a),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-1.1 1.1]*max(a)]);
ylabel('a [m/s2]');
subplot(413);plot(tx,v,'k','LineWidth',1.5);hold on;plot([0 0],[0 1]*max(v),'k--',[1 1]*max(tt),[0 1]*max(v),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-0.1 1.1]*max(v)]);
ylabel('v [m/s]');
subplot(414);plot(tx,p,'k','LineWidth',1.5);hold on;plot([0 0],[0 1]*max(p),'k--',[1 1]*max(tt),[0 1]*max(p),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-0.1 1.1]*max(p)]);
xlabel('time [s]');ylabel('x [m]');
set(1,'position',[700 200 500 680])
set(1,'paperposition',[0 0 5 6.8])

subplot(411);
text(tt(1)+tt(8)/200,max(j)/5,'t_0');
text(tt(2)+tt(8)/200,max(j)/5,'t_1');
text(tt(3)          ,max(j)/5,'t_2');
text(tt(4)          ,max(j)/5,'t_3');
text(tt(5)          ,max(j)/5,'t_4');
text(tt(6)          ,max(j)/5,'t_5');
text(tt(7)+tt(8)/200,max(j)/5,'t_6');
text(tt(8)+tt(8)/200,max(j)/5,'t_7');


function scale_sample = extract_scale_sample(im, pos, base_target_sz, scaleFactors, scale_model_sz, use_mexResize)

% Get scale filter sample.

if nargin < 6
    use_mexResize = true;
end

nScales = length(scaleFactors);

% Downsample factor.
df = floor(min(scaleFactors));
if df > 1
    im = im(1:df:end,1:df:end,:);
    pos = (pos - 1) / df + 1;
    scaleFactors = scaleFactors / df;
end

for s = 1:nScales
    patch_sz = floor(base_target_sz * scaleFactors(s));

    xs = floor(pos(2)) + (1:patch_sz(2)) - floor(patch_sz(2)/2);
    ys = floor(pos(1)) + (1:patch_sz(1)) - floor(patch_sz(1)/2);

    %check for out-of-bounds coordinates, and set them to the values at
    %the borders
    xs(xs < 1) = 1;
    ys(ys < 1) = 1;
    xs(xs > size(im,2)) = size(im,2);
    ys(ys > size(im,1)) = size(im,1);

    %extract image
    im_patch = im(ys, xs, :);

    % resize image to model size
    if use_mexResize
        im_patch_resized = mexResize(im_patch, scale_model_sz, 'auto');
    else
        im_patch_resized = imresize(im_patch, scale_model_sz, 'bilinear', 'Antialiasing',false);
    end

    % extract scale features
    temp_hog = fhog(single(im_patch_resized), 4);

    if s == 1
        dim_scale = size(temp_hog,1)*size(temp_hog,2)*31;
        scale_sample = zeros(dim_scale, nScales, 'single');
    end

    scale_sample(:,s) = reshape(temp_hog(:,:,1:31), dim_scale, 1);
end


function markedElem = mark(elem,eta,theta,method)
% MARK mark element.
%
% markedElem = mark(elem,eta,theta) mark a subset of elements by Dorfler
% marking strategy. It returns an array of indices of marked elements
% markedElem such that sum(eta(markedElem)^2) > theta*sum(eta^2).
%
% markedElem = mark(elem,eta,theta,'max') choose markedElem such that
% eta(markedElem) > theta*max(eta).
%
% markedElem = mark(elem,eta,theta,'COARSEN') choose markedElem such that
% eta(markedElem) < theta*max(eta).
%
% Copyright (C) 2008 Long Chen. See COPYRIGHT.txt for details.

NT = size(elem,1); isMark = false(NT,1);
if ~exist('method','var'), method = 'L2'; end  % default marking is L2 based
switch upper(method)
    case 'MAX'
        isMark(eta>theta*max(eta))=1;
    case 'COARSEN'
        isMark(eta<theta*max(eta))=1;
    case 'L2'
        [sortedEta,idx] = sort(eta.^2,'descend');
        x = cumsum(sortedEta);
        isMark(idx(x < theta* x(NT))) = 1;
        isMark(idx(1)) = 1;
end
markedElem = uint32(find(isMark==true));


% Data File EKIN1
% Oscillations of
% a mathematical pendulum
  Ek   = '1/2*m*qt^2'; % Kinetic energy
  N    = '-(k*qt + 9.81*sin(q))*qt'; % power
  q0   = '0.1';  % initial coordinate
  qt0  = '5';    % initial velocity
  Tend = 20;     % upper bound of integration
  eps  = 1e-10;  % desirable accuracy
  np   = 2;      % number of parameters
  P{1} = 'm';    % mass of the pendulum
  P{2} = 'k';    % coefficient of resistance


function [hy,model,Sigma] = ml_gpr(X,y,model,epsilon,rbf_var,method)
%ML_GP Gaussian Process Regression
%
%   Desired structure for ml_kcv ------------------------------------------
%
%  [hy,model] = f(X_train,labels_train,model) : used to train
%
%  hy         = f(X_test,[],model) : used to predict
%
%   input -----------------------------------------------------------------
%
%       o X         : (N x D), N input samples of dimension D.
%
%       o y         : (N x 1), N output predictions of dimension 1.
%
%       o model     : struct
%
%       o epsilon   : measurement noise
%
%       o rbf_var   : kernel width
%
%   output ----------------------------------------------------------------
%
%
%

Sigma = [];

if ~exist('method','var'), method='gpml'; end

if ~isempty(y)
% Train the model
    model.X_train = X;
    model.y_train = y;

    if strcmp(method,'gdc')

        [hy,Sigma] = gaussian_process(X,y,X,epsilon,rbf_var);

    elseif strcmp(method,'gpml')

        meanfunc     = {@meanZero};
        covfunc      = {@covSEiso};
        ell          = rbf_var;     % kernel width of RBF covariance function.
        sf           = 1;           % signal variance (not measurement noise)
        sn           = epsilon;      % measurement noise
        hyp          = [];
        hyp.cov      = log([ell; sf]);
        hyp.lik      = log(sn);
        [hy,Sigma]   = gp(hyp, @infExact, meanfunc, covfunc, @likGauss, X, y, X);

    else

        error(['No such method defined: ' method]);

    end

else
% Test the model

    if strcmp(method,'gdc')

        [hy,Sigma]    = gaussian_process(model.X_train,model.y_train,X,epsilon,rbf_var);

    elseif strcmp(method,'gpml')

        meanfunc     = {@meanZero};
        covfunc      = {@covSEiso};
        ell          = rbf_var;     % kernel width of RBF covariance function.
        sf           = 1;           % signal variance (not measurement noise)
        sn           = epsilon;      % measurement noise
        hyp          = [];
        hyp.cov      = log([ell; sf]);
        hyp.lik      = log(sn);

        [hy,Sigma]   = gp(hyp, @infExact, meanfunc, covfunc, @likGauss, model.X_train,model.y_train, X);

    else

        error(['No such method defined: ' method]);

    end

end

end


function im=seamcarving(im,k)
%% illustrative example of Seam carving for content aware image resizing
%
%
% usage: carvedimg=seamcarving(im,k)
%
% k is how many vertical seams to remove.
% im is the image.
%
% example:
%   img=imread('peppers.png')
%   carvedimg=seamcarving(img,50)
%   image([carvedimg img]);
%   axis equal;
%
% Author: Aslak Grinsted 2007...
% Based on ideas from Avidan & Shamir:
% http://video.google.com/videoplay?docid=-6221880321193117495
% Note i havent read their paper and they have probably lots of smart tricks
% for optimizations.
%

demo=nargout==0;
if nargin==0
    fex={'peppers.png' 'liftingbody.png' 'pears.png' 'trees.tif' 'football.jpg' 'onion.png'};
    fex=fex{ceil(rand*length(fex))};
    try
        [im,map]=imread(fex);
    catch
        [im,map]=imread('street1.jpg');
    end
    k=50;
end
im=im2double(im);

if demo
    close(findobj(0,'type','figure','tag','seam carving demo'));
    figure; set(gcf,'tag','seam carving demo','name','Seam Carving','NumberTitle','off')
    axes('position', [0 0 1 1]);
    if size(im,3)==1
        im=im/max(im(:));
        him=imagesc(im);
        colormap gray
    else
        him=image(im);
    end
    origim=im;
    axis equal
    axis off
end

for jj=1:k
    G=costfunction(im);
    %find shortest path in G
    Pot=G;
    for ii=2:size(Pot,1)
        pp=Pot(ii-1,:);
        ix=pp(1:end-1)<pp(2:end);
        pp([false ix])=pp(ix);
        ix=pp(2:end)<pp(1:end-1);
        pp(ix)=pp([false ix]);
        Pot(ii,:)=Pot(ii,:)+pp;
    end

    %Walk down hill
    pix=zeros(size(G,1),1);
    [mn,pix(end)]=min(Pot(end,:));
    pp=find(Pot(end,:)==mn);
    pix(end)=pp(ceil(rand*length(pp)));

    im(end,pix(end),:)=nan;
    for ii=size(G,1)-1:-1:1
        %[mn,gg]=min(Pot(ii,pix+(-1:1)));
        [mn,gg]=min(Pot(ii,max(pix(ii+1)-1,1):min(pix(ii+1)+1,end)));
        pix(ii)=gg+pix(ii+1)-1-(pix(ii+1)>1);
        im(ii,pix(ii),:)=bitand(ii,1);
%        G(ii,pix(ii))=1;
    end

    if demo
        set(him,'CDATA',im);
        %set(him,'CDATA',G,'CDataMapping','scaled');
        drawnow;
    end

    %remove seam from im & G:
    for ii=1:size(im,1)
%        G(ii,pix(ii):end-1)=G(ii,pix(ii)+1:end);
        im(ii,pix(ii):end-1,:)=im(ii,pix(ii)+1:end,:);
    end
    im(:,end,:)=[];
%    G(:,end)=[];

end

if demo
    set(him,'CDATA',[im origim])
    axis tight
end
if nargout==0
    clear im
end

    function G=costfunction(im) %%(xi,yi)
            G=zeros(size(im,1),size(im,2));
            for ii=1:size(im,3)
                %G=G+abs(filter2([1 0 -1],im(:,:,ii)))+abs(filter2([1;0;-1],im(:,:,ii)));
                G=G+(filter2([.5 1 .5; 1 -6 1; .5 1 .5],im(:,:,ii))).^2; %faster and reasonably good.
            end
    end
end


function [params, s_new] = denoise_pow3(params, s, state)
% Kurtosis based denoising function
%   [params, s_new] = denoise_pow3(params, s, state)
%     params  Function specific modifiable parameters
%     state   DSS algorithm state
%     s       Source signal estimate, matrix of row vector signals
%     s_new   Denoised signal estimate
%
%   Calculates third power of the signal. Equals kurtosis if source
%   signal has unit variance.

% Copyright (C) 2004, 2005 DSS MATLAB package team (dss@cis.hut.fi).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$

if nargin<3 | ~isstruct(state)
    params.name = 'Kurtosis based denoising';
    params.description = '';
    params.param = {};
    params.param_value ={};
    params.param_type = {};
    params.param_desc = {};
    params.param_type = {};
    params.approach = {'defl','symm'};
    params.alpha = {};
    params.beta = {'beta_global','beta_pow3'};
    return;
end

s_new = s.^3;


function [w1rp, Tau] = compute_w1rp(Pulse)
%compute_w1rms Compute the equivalent power of a rectangular pulse of
%duration of the FWHM of the shaped pulse

Trf = Pulse.Trf;
omega2 = Pulse.omega2;
if moxunit_util_platform_is_octave
    int = quad(omega2, 0, Trf);
else
    int = integral(omega2, 0, Trf);
end

if strcmp(Pulse.shape,'hard')
    Tau = Trf;
else
    x = 0:Trf/1000:Trf;
    y = omega2(x);
    Tau = fwhm(x,y);
end

w1rp = sqrt( int / Tau );

end


function xd = lagrange_interp_nd_grid ( m, n_1d, a, b, nd )

%*****************************************************************************80
%
%% LAGRANGE_INTERP_ND_GRID sets an M-dimensional Lagrange interpolant.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 September 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N_1D(M), the order of the 1D rule to be used
%    in each dimension.
%
%    Input, real A(M), B(M), the lower and upper interval endpoints in
%    each dimension.
%
%    Input, integer ND, the number of points in the product grid.
%
%    Output, real XD(M,ND), the points at which data was sampled.
%
    xd = zeros ( m, nd );
    for i = 1 : m
      n = n_1d(i);
      x_1d(1:n) = cc_compute_points ( n );
      x_1d(1:n) = 0.5 * ( ( 1.0 - x_1d(1:n) ) * a(i) ...
                        + ( 1.0 + x_1d(1:n) ) * b(i) );
      xd = r8vec_direct_product ( i, n, x_1d, m, nd, xd );
    end

  return
end


%SF_TRI_P5 Fifth order Lagrange shape functions for triangles (P5).
%
%   [ VBASE, NLDOF, XLDOF, SFUN ] = SF_TRI_P5( I_EVAL, N_SDIM, N_VERT, I_DOF, XI, AINVJAC, VBASE )
%   Evaluates conforming fifth order P5 Lagrange shape functions on 2D triangular elements
%   with values defined in the nodes, edges, and center. XI are Barycentric coordinates.
%
%       Input       Value/[Size]           Description
%       -----------------------------------------------------------------------------------
%       i_eval      scalar:  1             Evaluate function values
%                           >1             Evaluate values of derivatives
%       n_sdim      scalar: 2              Number of space dimensions
%       n_vert      scalar: 3              Number of vertices per cell
%       i_dof       scalar: 1-21           Local basis function to evaluate
%       xi          array [3,1]            Local coordinates of evaluation point
%       aInvJac     [n,6]                  Inverse of transformation Jacobian
%       vBase       [n]                    Preallocated output vector
%                                                                                .
%       Output      Value/[Size]           Description
%       -----------------------------------------------------------------------------------
%       vBase       [n]                    Evaluated function values
%       nLDof       [4]                    Number of local degrees of freedom on
%                                          vertices, edges, faces, and cell interiors
%       xLDof       [3,n_ldof]             Local coordinates of local dofs
%       sfun        string                 Function name of called shape function
%
%   See also SF_TRI_P1

% Copyright 2013-2022 Precise Simulation, Ltd.


filters = haar_filter_bank_2d_spatial;

% Initialize signal and meta
x = uiuc_sample;
U{1}.signal{1} = x;
U{1}.meta.j = zeros(0,1);
options.J = 5;

[A2, W2] = wavelet_layer_2d_pyramid(U{1}, filters, options)
U2 = modulus_layer(W2);

%%
clear
x = uiuc_sample;
filt_opt.type = 'haar';
scat_opt.J = 5;
scat_opt.M = 3;
Wop = wavelet_factory_2d_pyramid(filt_opt, scat_opt);
Sx = scat(x, Wop);


% Calculate Kendall coefficient of agreement from a winning matrix
% according to Wei-Sheng La et al. "A Comparative Study for Single Image
% Blind Deblurring", CVPR 2016
function u = coefficientOfAgreement(C)

    % Number of methods described by the winning matrix.
    numMethods = sum(sum(C + C', 2) > 0);
    % Number of observers for the winning matrix.
    numUsers = round(sum(C(:)) / nchoosek(numMethods, 2) );

    C = C(:);
    C = C(C > 1);
    w = 0;
    for i = 1:length(C)
        w = w + nchoosek(C(i), 2);
    end

    u = (2 * w) / ( nchoosek(numMethods, 2) * nchoosek(numUsers, 2) ) - 1;


function [out] = evap_23(p1,p2,S,Smax,Ep,dt)
% evap_23 combines evap_5 (evaporation) and evap_6 (transpiration)

% Copyright (C) 2021 Clara Brandes, Luca Trotter
% This file is part of the Modular Assessment of Rainfall-Runoff Models
% Toolbox (MARRMoT).
% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY
% WARRANTY. See <https://www.gnu.org/licenses/> for details.

% Flux function
% ------------------
% Description:  Transpiration from vegetation at the potential rate if
%               storage is above field capacity and scaled by relative
%               storage if not (similar to evap_6), addition of
%               Evaporation from bare soil scaled by relative storage
%               (similar to evap_5)
% Constraints:  Ea <= Ep
%               Ea <= S/dt
% @(Inputs):    p1   - fraction vegetated area [-] (0...1)
%               p2   - field capacity coefficient[-]
%               S    - current storage [mm]
%               Smax - maximum storage [mm]
%               Ep   - potential evapotranspiration rate [mm/d]
%               dt   - time step size [d]

out = min([p1.*Ep+(1-p1).*S./Smax.*Ep, p1*Ep*S./(p2*Smax)+(1-p1).*S./Smax.*Ep,S/dt]);

end


function cc_levels_minmax_animate ( )

%*****************************************************************************80
%
%% CC_LEVELS_MINMAX_ANIMATE displays the sequence of grids generated by CC_LEVELS_MINMAX.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 November 2006
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  timestamp ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CC_LEVELS_MINMAX_ANIMATE:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Display the sequence of nested 2D Clenshaw-Curtis grids\n' );
  fprintf ( 1, '  generated by CC_LEVELS_MINMAX.\n' );

  dim_num = 2;

  while ( 1 )
%
%  Get user input.
%
    fprintf ( 1, '\n' );
    level_max = input ( 'Enter LEVEL_MAX or RETURN to exit;' );

    if ( isempty ( level_max ) )
      break
    end

    grid_points_old = [];
    grid_points_old_num = 0;

    grid_points = [];
    grid_points_num = 0;

    for level = 0 : level_max

      if ( 0 < grid_points_num )

        grid_points_old(1:2,grid_points_old_num+1:grid_points_old_num+grid_points_num) = ...
          grid_points(1:2,1:grid_points_num);

        grid_points_old_num = grid_points_old_num + grid_points_num;

      end
%
%  Compute data.
%
      [ grid_num, point_num ] = cc_levels_minmax_size ( dim_num, ...
        level, level );

      [ grid_level, grid_order, grid_points ] = cc_levels_minmax ( dim_num, ...
        level, level,  grid_num, point_num );

      [ dim_num, grid_points_num ] = size ( grid_points );

      clf
%
%  We have to name the axes in order to control the grid.
%
      axes_handle = axes;
%
%  Plot the points.
%
      handle_new = scatter ( grid_points(1,:), grid_points(2,:), 'r', 'filled' );

      hold on

      if ( 0 < grid_points_old_num )
        handle_old = scatter ( grid_points_old(1,:), grid_points_old(2,:), 'b', 'filled' );
      end
%
%  Force the plotting region to be square, not rectangular.
%
      axis square
%
%  Request grid lines.
%
      grid on
%
%  Specify the location of the grid lines, and suppress labeling.
%
      set ( axes_handle, 'xtick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );
      set ( axes_handle, 'xticklabel', [] );
      set ( axes_handle, 'ytick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );
      set ( axes_handle, 'yticklabel', [] );
%
%  Make the plotting region slightly bigger than the data.
%
      axis ( [ -1.1, 1.1, -1.1, 1.1 ] )
%
%  Title
%
      s = sprintf ( '+LEVEL %d', level );
      title ( s );

      fprintf ( 1, '+LEVEL %d, Press return\n', level );
      pause

      hold off

    end

    fprintf ( 1, 'Press return to CLEAR the grid!\n' );
    pause
    clf

  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CC_LEVELS_MINMAX_ANIMATE:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function S = timestr(D,precision)
%timestr          String representation of time.   HH:MM:SS.SSSS
%
% TIMESTR(D) converts D, a serial date number (as returned by DATENUM)
% into a time string with the format HH:MM:SS.SSSS
%
% TIMESTR(D,precision) uses precision values to the right of the decimal

% Copyright 2003 The MathWorks, Inc

if nargin==1
    precision=4;
end;
totalwidth = precision + 3;         %2 to left of decimal, plus decimal
precision = num2str(precision);
totalwidth = num2str(totalwidth);

D = D(:);

% Obtain components of date number
[y,mo,d,h,min,s] = datevecmx(D,1.1);  mo(mo==0) = 1;

% Generate formatted string
% sw = floor(s);      %Whole
% sf = floor((s-sw)*1000);          %Fraction
% M = [h';min';sw';sf'];       %sprintf works columnwise
% fmt = '%02d:%02d:%02d.%04d';
M = [h';min';s'];       %sprintf works columnwise

% Figure out how long to make seconds format.
% Since we are building a string array, every element must be the same
% length
sw = floor(s);      %Whole
sf = floor((s-sw)*1000);          %Fraction

fmt = ['%02d:%02d:%' totalwidth '.' precision 'f'];
S = sprintf(fmt,M(:,1));
for ii=2:length(D)
    t= sprintf(fmt,M(:,ii));
    S = [S;t];
end;

% My formatting is a bit messed up.  I can't figure out how to add
% zeros when necessary for seconds - I end up with blanks.
% Replace blanks with 0
blnks = find(double(S)==32);        % 32 - ASCII for 0
S(blnks) = '0';


%% Converting sparse tensors to matrices and vice versa
% We show how to convert a sptensor to a matrix stored in _coordinate_
% format and with extra information so that it can be converted back to a
% sptensor.

%% Creating a sptenmat (sparse tensor as sparse matrix) object
% A sparse tensor can be converted to a sparse matrix. The matrix, however,
% is not stored as a MATLAB sparse matrix because that format is sometimes
% inefficient for converted sparse tensors. Instead, the row and column
% indices are stored explicitly.
%%
% First, we create a sparse tensor to be converted.
X = sptenrand([10 10 10 10],10) %<-- Generate some data.
%%
% All the same options for tenmat are available as for tenmat.
A = sptenmat(X,1) %<-- Mode-1 matricization.
%%
A = sptenmat(X,[2 3]) %<-- More than one mode is mapped to the columns.
%%
A = sptenmat(X,[2 3],'t') %<-- Specify column dimensions (transpose).
%%
A = sptenmat(X,1:4) %<-- All modes mapped to rows, i.e., vectorize.
%%
A = sptenmat(X,2) %<-- By default, columns are ordered as [1 3 4].
%%
A = sptenmat(X,2,[3 1 4]) %<-- Explicit column ordering.
%%
A = sptenmat(X,2,'fc') %<-- Foward cyclic.
%%
A = sptenmat(X,2,'bc') %<-- Backward cyclic.
%% Constituent parts of a sptenmat
A.subs %<-- Subscripts of the nonzeros.
%%
A.vals %<-- The corresponding nonzero values.
%%
A.tsize %<-- Size of the original tensor.
%%
A.rdims %<-- Dimensions that were mapped to the rows.
%%
A.cdims %<-- Dimensions that were mapped to the columns.
%% Creating a sptenmat from its constituent parts
B = sptenmat(A.subs,A.vals,A.rdims,A.cdims,A.tsize) %<-- Copies A
%%
B = sptenmat(double(A),A.rdims,A.cdims,A.tsize) %<-- More efficient to pass a matrix.
%% Creating a sptenmat with no nonzeros
A = sptenmat([],[],A.rdims,A.cdims,A.tsize) %<-- An empty sptenmat.
%% Creating an emtpy sptenmat
A = sptenmat %<-- A really empty sptenmat.
%% Use double to convert a sptenmat to a MATLAB sparse matrix
X = sptenrand([10 10 10 10],10); %<-- Create a tensor.
A = sptenmat(X,1) %<-- Convert it to a sptenmat
%%
B = double(A) %<-- Convert it to a MATLAB sparse matrix
%%
whos A B %<-- The storage for B (the sparse matrix) is larger than for A.
%%
C = B'; %<-- Transposing the result fixes the problem.
whos C
%% Use full to convert a sptenmat to a tenmat
B = sptenmat(sptenrand([3 3 3], 3), 1) %<-- Create a sptenmat
%%
C = full(B) %<-- Convert to a tenmat
%% Use sptensor to convert a sptenmat to a sptensor
Y = sptensor(A) %<-- Convert a sptenmat to a sptensor
%% Use size and tsize for the dimensions of a sptenmat
size(A) %<-- Matrix size
tsize(A) %<-- Corresponding tensor size
%% Subscripted reference for a sptenmat
% This is not supported beyond getting the constituent parts.
%% Subscripted assignment for a sptenmat
A(1:2,1:2) = ones(2) %<-- Replace part of the matrix.
%% Use end for the last index
% End is not supported.
%% Basic operations for sptenmat
norm(A) %<-- Norm of the matrix.
%%
+A %<-- Calls uplus.
%%
-A %<-- Calls uminus.
%% Use aatx to efficiently compute A * A' * x for a sptenmat
x = ones(10,1); %<-- Create vector
aatx(A,x) %<-- Compute A * A' * x
%%
double(A) * double(A)' * x %<-- Same as above but less efficient
%% Displaying a tenmat
% Shows the original tensor dimensions, the modes mapped to rows, the modes
% mapped to columns, and the matrix.
disp(A)


function [W] = kW2W(kW)
% Convert power from kilowatts to watts.
% Chad A. Greene 2012
W = kW*1000 ;


% Q = vgg_line3d_Ppv(P)  Transforms a camera matrix to use it with Pluecker vector 3d line representation.
%
% P ... double(3,4), ordinary camera matrix
% Q ... double(6,3), transformed camera matrix (quadratic function of elements of P)
%   such that the projection of a 3d line by the camera is given by
%
%     l = Q*L
%
% where l is 1-by-3 image line vector, and L is 1-by-6 Pluecker vector of the 3d line.

% T.Werner

function Q = vgg_line3d_Ppv(P)

K = size(P,1)/3;
i1 = 1:3:3*K;
i2 = 2:3:3*K;
i3 = 3:3:3*K;

Q(:,i1) = vgg_line3d_pv_from_XY(P(i2,:)',P(i3,:)')';
Q(:,i2) = vgg_line3d_pv_from_XY(P(i3,:)',P(i1,:)')';
Q(:,i3) = vgg_line3d_pv_from_XY(P(i1,:)',P(i2,:)')';

return


function [mi] = mm2mi(mm)
% Convert length from millimeters to miles.
% Chad A. Greene 2012
mi = mm*6.213711922373e-7;


function [hrf,p] = spm_hrf(RT,P,T)
% Haemodynamic response function
% FORMAT [hrf,p] = spm_hrf(RT,p,T)
% RT   - scan repeat time
% p    - parameters of the response function (two Gamma functions)
%
%                                                           defaults
%                                                          {seconds}
%        p(1) - delay of response (relative to onset)          6
%        p(2) - delay of undershoot (relative to onset)       16
%        p(3) - dispersion of response                         1
%        p(4) - dispersion of undershoot                       1
%        p(5) - ratio of response to undershoot                6
%        p(6) - onset {seconds}                                0
%        p(7) - length of kernel {seconds}                    32
%
% T    - microtime resolution [Default: 16]
%
% hrf  - haemodynamic response function
% p    - parameters of the response function
%__________________________________________________________________________
%
% The parameters p(1:4) correspond to the shape and scale parameters of two
% probability density functions of the Gamma distribution (see spm_Gpdf.m),
% one corresponding to the main response and the other one to the
% undershoot.
% Note that the mean of the Gamma distribution is shape*scale and its mode
% is (shape-1)*scale.  This means that with the default values of the
% parameters the peak of the heamodynamic response function will be around
% 5 seconds.
%__________________________________________________________________________
% Copyright (C) 1996-2019 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_hrf.m 7721 2019-11-27 13:03:32Z guillaume $

%-Parameters of the response function
%--------------------------------------------------------------------------
try
    p = spm_get_defaults('stats.fmri.hrf');
catch
    p = [6 16 1 1 6 0 32];
end
if nargin > 1
    p(1:length(P)) = P;
end

%-Microtime resolution
%--------------------------------------------------------------------------
if nargin > 2
    fMRI_T = T;
else
    fMRI_T = spm_get_defaults('stats.fmri.t');
end

%-Modelled haemodynamic response function - {mixture of Gammas}
%--------------------------------------------------------------------------
dt  = RT/fMRI_T;
u   = [0:ceil(p(7)/dt)] - p(6)/dt;
hrf = spm_Gpdf(u,p(1)/p(3),dt/p(3)) - spm_Gpdf(u,p(2)/p(4),dt/p(4))/p(5);
hrf = hrf([0:floor(p(7)/RT)]*fMRI_T + 1);
hrf = hrf'/sum(hrf);


% kaiserbeta() - Estimate Kaiser window beta
%
% Usage:
%   >> beta = pop_kaiserbeta(dev);
%
% Inputs:
%   dev       - scalar maximum passband deviation/ripple
%
% Output:
%   beta      - scalar Kaiser window beta
%
% References:
%   [1] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal
%       Processing: Principles, Algorithms, and Applications (3rd ed.).
%       Englewood Cliffs, NJ: Prentice-Hall
%
% Author: Andreas Widmann, University of Leipzig, 2005

%123456789012345678901234567890123456789012345678901234567890123456789012

% Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, widmann@uni-leipzig.de
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
%
% $Id$

function [ beta ] = kaiserbeta(dev)

devdb = -20 * log10(dev);

if devdb > 50
    beta = 0.1102 * (devdb - 8.7);
elseif devdb >= 21
    beta = 0.5842 * (devdb - 21)^0.4 + 0.07886 * (devdb - 21);
else
    beta = 0;
end

end


function M=Find_LCM(x)

%%%%%%%%%% This fucntion can find least common multiple between several
%%%%%%%%%% numbers.

temp=x(1);

for i=2:length(x)
     temp=lcm(temp,x(i));
end

M=temp;


function [atm] = mbar2atm(mbar)
% Convert pressure from millibars to atmospheres.
% Chad Greene 2012
atm = mbar*0.000986923;


vectors_file_name = add_data_dir_base('GoogleNews_vectors_norm.mat');

word2vec_sqrt = false;
if word2vec_sqrt
	vectors_file_name = fname_concat(vectors_file_name, '_sqrt');
end

is_sampled = true;
% without normalizing we had numeric problems in the LMM
normalize  = true;

if is_sampled
    vectors_file_name = fname_concat(vectors_file_name, '_sampled');
end

output(1, 'reading vectors file %s\n', vectors_file_name);
load(vectors_file_name);
output(1, 'done\n');

TargetDim = 300;

%desiredTrnSizeForICA = 512000;

output(1, 'Use ICA to reduce to dimension %d\n', TargetDim);

[icasig, A, trans_matrix] = fastica (vectors_, 'numOfIC', TargetDim);
vectors_ = trans_matrix * vectors_;

[dim, num_vectors] = size(vectors_)

if normalize
    % normalize
    output(1, 'normalizing...\n');
    for i = 1:num_vectors
      vectors_(:,i) = norma(vectors_(:,i));
    end
end

output(1, 'saving to file...\n');

post_fix = sprintf('_ica_%d', TargetDim);
ica_vectors_file_name = fname_concat(vectors_file_name, post_fix);
trans_matrix_file_name = add_data_dir_base(strcat('trans_matrix', post_fix));

save(ica_vectors_file_name, 'vectors_', '-v7.3');
output(1, 'saved to file: %s\n', ica_vectors_file_name);

save(trans_matrix_file_name, 'trans_matrix', '-v7.3');
output(1, 'saved to file: %s\n', trans_matrix_file_name);

clear vectors_;
clear trans_matrix;


function [theta,alpha,minError,vertices3d,vertices2d,inliers]= ...
    select_from_range_fig(hObject, eventdata, handles)
% -------------------------------------------------------------------------
% FUNCTION: select_from_range_fig
% INPUT:
%  hObject : handle to current figure
%  eventdata : from calling function
%  handles : data common to GUI
% OUTPUT:
%  theta,alpha: parameters of selected plane as per equation
%               theta'*x=alpha , alpha>0 , norm(theta)=1
%  minError   : min fitting error using tls_robust routine
%  vertices3d : 3d coords of points corresponding to vertices of selected
%               polgon
%  inliers    : 3d coords of points considered inliers to the selected
%               plane
% -------------------------------------------------------------------------

%* Author: Ranjith Unnikrishnan                                          *
%* Carnegie Mellon University, Vision and Mobile Robotics Laboratory       *
%* THE MATERIAL EMBODIED IN THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"     *
%* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,      *
%* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR      *
%* FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL CARNEGIE MELLON  *
%* UNIVERSITY BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,            *
%* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY         *
%* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,        *
%* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF     *
%* THIRD PARTIES, WHETHER OR NOT CARNEGIE MELLON UNIVERSITY HAS BEEN     *
%* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON        *
%* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE     *
%* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.                      *
%

% Restrict to data with far > y > near
scan=handles.current_scan;

% Prune based on distance
dist_sq = scan(:,1).*scan(:,1)+scan(:,2).*scan(:,2);
scan(dist_sq < handles.nearVal*handles.nearVal ...
    | dist_sq > handles.farVal*handles.farVal,:) = [];

if (isempty(scan))
    return;
end

% Project scan to viewing vectors (up,right,forward)
P = [handles.right_vector handles.forward_vector handles.up_vector];
scanp = scan * P;
% Compute angle swept by data in xy plane
theta = atan2(scanp(:,2),scanp(:,1));

% Assume the angle swept by the data is less than 180 degrees
% Find angle corresponding to vector pointing at the middle of the cloud
midtheta = 0.5*(min(theta) + max(theta));
if (max(theta)-min(theta) > pi)
    if (midtheta > 0)
        midtheta = midtheta - pi;
    else
        midtheta = midtheta + pi;
    end
end

% Rotate the data by pi/2 - midtheta to put everything in view
R = [ cos(pi/2 - midtheta) sin(pi/2 - midtheta) 0;...
    -sin(pi/2 - midtheta) cos(pi/2 - midtheta) 0;...
    0 0 1];
scanp = scanp * R;

% Perspective projection (x/y, z/y)
scanp_y = scanp(:,2);
scanp=[scanp(:,1)./scanp(:,2) scanp(:,3)./scanp(:,2)];
%scanp(:,1) = scanp(:,1)/scanp(:,2);
%scanp(:,3) = scanp(:,3)/scanp(:,2);

% X,Y bounds of projection
xBounds=[ min(scanp(:,1)) max(scanp(:,1))];
yBounds=[ min(scanp(:,2)) max(scanp(:,2))];

% Size of a square pixel
pixel_size=max([range(xBounds) range(yBounds)])/150;

% Choose size of grid that will serve as the range image (n_cols n_rows)
nx=ceil(range(xBounds)/pixel_size) + 1;
ny=ceil(range(yBounds)/pixel_size) + 1;
grid=zeros(ny,nx);

% Add points to grid
ix=floor( (scanp(:,1)-xBounds(1))/pixel_size ) + 1;
iy=floor( (yBounds(2)-scanp(:,2))/pixel_size ) + 1;
ii=sub2ind(size(grid),iy,ix);
grid(ii)=max(grid(ii),scanp_y);

grid=-grid;
% Set values of zero to minimum value
grid(grid==0) = min(grid(:));
colormap(jet);
axes(handles.range_image_axis);
imagesc(grid);
axis('equal'); axis off;
title(handles.current_scanfilename);
%colorbar

% Draw a polygon and get its vertices
[x_polygon,y_polygon]=selectPolygon;
vertices2d=[x_polygon y_polygon];

% Choose points whose projections in range image
% are inside the polygon
region=scan(inpolygon(ix,iy,x_polygon,y_polygon),:);

fprintf(1,'Selected %d points\n',size(region,1));
% Fit plane to points
[theta,alpha,minError]=tls_robust(region);

% Compute the 3d points corresponding to the vertices of the polygon
vertices3d=[];
for i=1:4
    temp=[ix iy]-repmat([x_polygon(i) y_polygon(i)],size(ix,1),1);
    [m,j]=min(sum(temp.^2,2));
    %[m,j]=min(sum((scanp-repmat([x_polygon(i) y_polygon(i)],size(scanp,1),1)).^2,2));
    vertices3d=[vertices3d; scan(j,:)];
end

% Compute inliers = points within median distance from plane
dist=abs(theta'*region'-alpha);
inliers=region(dist<median(dist),:);

return;


function Population = EnvironmentalSelection(Population,N,Z,Zmin)
% The environmental selection of NSGA-III

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    if isempty(Zmin)
        Zmin = ones(1,size(Z,2));
    end

    %% Non-dominated sorting
    [FrontNo,MaxFNo] = NDSort(Population.objs,Population.cons,N);
    Next = FrontNo < MaxFNo;

    %% Select the solutions in the last front
    Last   = find(FrontNo==MaxFNo);
    Choose = LastSelection(Population(Next).objs,Population(Last).objs,N-sum(Next),Z,Zmin);
    Next(Last(Choose)) = true;
    % Population for next generation
    Population = Population(Next);
end

function Choose = LastSelection(PopObj1,PopObj2,K,Z,Zmin)
% Select part of the solutions in the last front

    PopObj = [PopObj1;PopObj2] - repmat(Zmin,size(PopObj1,1)+size(PopObj2,1),1);
    [N,M]  = size(PopObj);
    N1     = size(PopObj1,1);
    N2     = size(PopObj2,1);
    NZ     = size(Z,1);

    %% Normalization
    % Detect the extreme points
    Extreme = zeros(1,M);
    w       = zeros(M)+1e-6+eye(M);
    for i = 1 : M
        [~,Extreme(i)] = min(max(PopObj./repmat(w(i,:),N,1),[],2));
    end
    % Calculate the intercepts of the hyperplane constructed by the extreme
    % points and the axes
    Hyperplane = PopObj(Extreme,:)\ones(M,1);
    a = 1./Hyperplane;
    if any(isnan(a))
        a = max(PopObj,[],1)';
    end
    % Normalization
    PopObj = PopObj./repmat(a',N,1);

    %% Associate each solution with one reference point
    % Calculate the distance of each solution to each reference vector
    Cosine   = 1 - pdist2(PopObj,Z,'cosine');
    Distance = repmat(sqrt(sum(PopObj.^2,2)),1,NZ).*sqrt(1-Cosine.^2);
    % Associate each solution with its nearest reference point
    [d,pi] = min(Distance',[],1);

    %% Calculate the number of associated solutions except for the last front of each reference point
    rho = hist(pi(1:N1),1:NZ);

    %% Environmental selection
    Choose  = false(1,N2);
    Zchoose = true(1,NZ);
    % Select K solutions one by one
    while sum(Choose) < K
        % Select the least crowded reference point
        Temp = find(Zchoose);
        Jmin = find(rho(Temp)==min(rho(Temp)));
        j    = Temp(Jmin(randi(length(Jmin))));
        I    = find(Choose==0 & pi(N1+1:end)==j);
        % Then select one solution associated with this reference point
        if ~isempty(I)
            if rho(j) == 0
                [~,s] = min(d(N1+I));
            else
                s = randi(length(I));
            end
            Choose(I(s)) = true;
            rho(j) = rho(j) + 1;
        else
            Zchoose(j) = false;
        end
    end
end


function [m2] = yd22m2(yd2)
% Convert area from square yards to square meters.
% Chad A. Greene 2012
m2 = yd2*0.83612736;


% This is material illustrating the methods from the book
% Financial Modelling  - Theory, Implementation and Practice with Matlab
% source
% Wiley Finance Series
% ISBN 978-0-470-74489-5
%
% Date: 02.05.2012
%
% Authors:  Joerg Kienitz
%           Daniel Wetterau
%
% Please send comments, suggestions, bugs, code etc. to
% kienitzwetterau_FinModelling@gmx.de
%
% (C) Joerg Kienitz, Daniel Wetterau
%
% Since this piece of code is distributed via the mathworks file-exchange
% it is covered by the BSD license
%
% This code is being provided solely for information and general
% illustrative purposes. The authors will not be responsible for the
% consequences of reliance upon using the code or for numbers produced
% from using the code.

function pathS = MC_VGCIR(S0,r,d,T,C,G,M,kappa,eta,...
    lambda,NTime,NSim,NBatches)
intNt = 20;                 % steps in between orginial grid points
allsteps = intNt * NTime;   % grid containing all necessary steps
dT = T / NTime;             % time step
daT = T/allsteps;           % time step
time = 0 : T/NTime : T;     % time for martingale correction

pathS = zeros(NSim,NTime+1,NBatches);% output
lnS = ones(NSim,NTime+1);            % used for each batch
lnS(:,1) = log(S0*exp(-d*T));        % set S(0) dividend adjusted

% precompute constants
psiVG = (-1i)*C*log(G*M/(G*M+(M-G)-1));   % char exp
gamma = sqrt(kappa^2-2*lambda^2*1i*psiVG);% CIR par
denom = ( cosh(0.5*gamma*time) ...        % denom
    + kappa*sinh(0.5*gamma*time)./gamma ).^(2*kappa*eta*lambda^(-2));
% coth is inf at 0
phiCIR(time>0) = kappa^2*eta*time(time>0)*lambda^(-2) ...
         + 2*1i*psiVG./(kappa+gamma.*coth(gamma*time(time>0)/2)) ...
         - log(denom(time>0));            % char func
phiCIR(1) = log(denom(1));                % char func start
omegaT = -phiCIR;                         % martingale correction
omegaT(1) = 0;                            % maringale correction in 0

deg = 4*eta*kappa/lambda^2;
fac1 = 4*kappa*exp(-kappa*daT)/lambda^2/(1-exp(-kappa*daT));
fac2 = lambda^2*(1-exp(-kappa*daT))/4/kappa;

Y = zeros(NSim,NTime);                   % Integrated clock

for l = 1 : NBatches                     % batch loop
   % Generating time change
   yy = ones(NSim,allsteps+1);              % stochastic clock
   for n = 1 : allsteps
       Nvec = poissrnd(0.5 * fac1 * yy(:,n));  % Poissonians
       yy(:,n+1) = fac2 * chi2rnd(deg+2*Nvec); % stochastic time
   end

   for m=1:NTime
        Y(:,m+1) = Y(:,m) + daT * sum(yy(:,1+(m-1)*intNt:m*intNt),2);
   end

   Intensity = C * (Y(:,2:end)-Y(:,1:end-1));           % intensity
   DGam = gamrnd(Intensity,1/M) - gamrnd(Intensity,1/G);% diff gamma proc
   diffomegaT = omegaT(2:end) - omegaT(1:end-1);        % Martingale correction

   for m=2:NTime+1                      % time loop
       lnS(:,m) = lnS(:,m-1) + (r-d)*dT + diffomegaT(m-1) + DGam(:,m-1);
   end
   pathS(:,:,1) = exp(lnS);
end


 function xs = l1_tv_restore1_fun(yi, A, varargin)
%function xs = l1_tv_restore1_fun(yi, A, varargin)
%|
%| Robust image restoration using a l1 data fit term and a TV-like regularizer.
%|
%| see l1_tv_restore1.m
%| min_x |yi - A(ti) * x|_1 + beta (|Cx x|_1 + |Cy x|_1)
%| where |.|_1 is approximated by a hyperbola
%|
%|
%| in
%|	yi	data
%|	A	system matrix
%|
%| option
%|	several - see code ...
%|
%| out
%|	xs	estimate(s)
%|
%| Copyright 2010-05-24, Jeff Fessler, University of Michigan

if nargin == 1 && streq(yi, 'test')
	l1_tv_restore1
	clear xs
return
end

if nargin < 2, help(mfilename), error(mfilename), end

arg.niter = 20;
arg.delta1 = 0.2; % round corner of |t| in data fit to approximate by hyperbola
arg.delta2 = 0.2; % round corner of |t| in penalty
arg.xinit = [];
arg.mask = [];
arg.l2b = -6;
arg.curvtype = 'oc';
arg.args = {};
arg = vararg_pair(arg, varargin);

if isempty(arg.xinit)
	arg.xinit = yi; % assume restoration
end

if isempty(arg.mask)
	arg.mask = true(size(yi));
end

% R = R_null; % null regularizer
R = Reg1(arg.mask, 'type_denom', 'matlab', ...
	'beta', 2^arg.l2b, 'pot_arg', {'hyper2', arg.delta2});

data = {yi(:), arg.delta1};
xs = pl_pcg_qs_ls(arg.xinit(:), A, data, ...
	@l1_tv_dercurv, R, 'niter', arg.niter, ...
	'curvtype', arg.curvtype, ...
	arg.args{:});

% l1_tv_dercurv()
function [deriv curv] = l1_tv_dercurv(data, yp, curvtype)
yi = data{1};
delta = data{2};
pot = potential_fun('hyper2', delta);
t = yp - yi;
switch curvtype
case 'pc'
	curv = 1;
	deriv = pot.dpot(t);
case 'oc'
	curv = pot.wpot(t);
	deriv = curv .* t;
otherwise
	fail('curvtype %s', curvtype)
end

% R_null()
function R = R_null;
R.dercurv = @R_null_dercurv;
R.C1 = 0;

% R_null_dercurv()
function [a b] = R_null_dercurv(arg1, arg2);
a = 0;
b = 0;


%% DEMO 03: Generate sample data and add realistic CT noise to it.
%
% This demo will show how to generate sample data for image reconstruction
%
%
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% This file is part of the TIGRE Toolbox
%
% Copyright (c) 2015, University of Bath and
%                     CERN-European Organization for Nuclear Research
%                     All rights reserved.
%
% License:            Open Source under BSD.
%                     See the full license at
%                     https://github.com/CERN/TIGRE/blob/master/LICENSE
%
% Contact:            tigre.toolbox@gmail.com
% Codes:              https://github.com/CERN/TIGRE/
% Coded by:           Ander Biguri
%--------------------------------------------------------------------------
%% Initialize
clear;
close all;
%% Geometry
geo=defaultGeometry();
%% Define angles of projection and load phatom image

% define projection angles (in radians)
angles=linspace(0,2*pi,100);
% load phatnom image
head=headPhantom(geo.nVoxel);

% Simulate forward projection.
% Strongly suggested to use 'iterpolated' option for more accurate
% projections. reduce geo.accuracy for better results
projections=Ax(head,geo,angles,'interpolated');

% Add realistic noise. Adds photon scattering noise ('Poisson') and
% electronic noise of the detector ('Gaussian').
%
% 'Poisson' is related to the maximum photon count in the detector. 1e5 is
% a standard clinical nuber, reduce it for more noise
% 'Gaussian' is related to possible electronic noise in the detector. mean
% of 0 and std of 10 is common in clinical scenario. Increase std for more
% noise.
noise_projections=addCTnoise(projections,'Poisson',1e5,'Gaussian',[0 10]);

% Plot Projections
plotProj(projections,angles)
% plot noise
plotProj(projections-noise_projections,angles)


function [tt]=tt_qfromfull(ff,s,d,eps,q)

% Approximates a full-format s-dimensional q^{d} x...x q^{d}-tensor
% full, indexed by
% i^{1}_{1} ,..., i^{d}_{1} ,...,..., i^{1}_{s} ,..., i^{d}_{s},
% by a QTT decomposition _tt_,
% k-th core of which is indexed by
% i^{k}_{1} ,..., i^{k}_{s},
% k=1,...,d
%
% August 11, 2011
% Vladimir Kazeev
% vladimir.kazeev@gmail.com
% INM RAS
% Moscow, Russia
%

if (nargin<4) || isempty (eps)
    eps=1.e-8;
end

if (nargin<5) || isempty (q)
    q=2;
end

ff=reshape(ff,[q*ones(1,s*d),1]);

prm = 1:s*d; prm = reshape(prm,[d,s]); prm = prm'; prm = reshape(prm,[1,d*s]);

ff=permute(ff,[prm,1+s*d]);
ff=reshape(ff,[q^s*ones(1,d),1]);

tt=core(tt_tensor(ff,eps));
if (numel(tt) > d)
	tt{d}=tt{d}*tt{d+1};
	tt=tt(1:d);
end

for k=1:d
	[~,p,r]=size(tt{k});
	tt{k}=reshape(tt{k},[q*ones(1,s),p,r]);
end

return
end


function [I,V,N]=integrateStochCubAdaptive(func,mu,SR,algorithm,epsVal2,NMax)
%%INTEGRATESTOCHCUBADAPTIVE Perform approximate Monte Carlo numerical
%                integration of a function times a Gaussian PDF using a
%                method that can be compared to importance sampling in that
%                random sets of approximate cubature points are generated
%                rather than more traditional Monte Carlo appraoches.
%
%INPUTS: func The handle to the function that is multiplies by a Gaussian
%             PDF before integration is performed. The function can take a
%             multidimensional input, but must produce a real univariate
%             output.
%          mu The numDimX1 mean of the Gaussian PDF.
%          SR The numDimXnumDim lower-triangular square root of the
%             covariance matrix of the Gaussian PDF.
%   algorithm An optional parameter specifying the algorithm to use.
%             Possible values are:
%             0 Use the first-order method of [1].
%             1 Use the third-order method of [1].
%             2 (The default if omitted or an empty matrix is passed) Use
%               the fifth-order method of [1].
%     epsVal2 An optional convergence bound based on the approximate
%             variance of the estimate. The default if this parameter is
%             omitted or an empty matrix is passed is 1e-2.
%        NMax The maximum number of iterations to perform. The default
%             value if this parameter is omitted or an empty matrix is
%             passed is 10e3.
%
%OUTPUTS: I The approximate scalar value of the integral.
%         V The approximate variance of the estimate.
%         N The number of iterations performed.
%
%All three algorithms arise from similar derivations in [1].
%
%EXAMPLE:
%Here, we choose a function whose true integral with a normal weighting
%function can be easily found. In this instance, we just choose a bivariate
%polynomial.
% f=@(x)(x(2)^4*(x(1)+1)^3-(x(1)+2)^2-(x(2)-4)^3);
% mu=[0;1/2];
% R=[2,-1;
%   -1, 2];
% SR=chol(R,'lower');
% algorithm=2;
% %The exact solution to the problem is known to be
% exactSol=1917/16
% [I,V,N]=integrateStochCubAdaptive(f,mu,SR,algorithm)
%One will find the result is relatively close, but not equal to the exact
%solution.
%
%REFERENCES:
%[1] A. Genz and J. Monahan, "Stochastic integration rules for infinite
%    regions," SIAM Journal on Scientific Computing, vol. 19, no. 2, pp.
%    426-439, Mar. 1998.
%
%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<6||isempty(NMax))
   NMax=10e3;
end

if(nargin<5||isempty(epsVal2))
   epsVal2=1e-2;
end

if(nargin<4||isempty(algorithm))
    algorithm=2;
end

numDim=length(mu);

%Deal with the distribution not being a standard normal distribution.
f=@(x)func(SR*x+mu);

switch(algorithm)
    case 0 %Degree 1 spherical-radial integration rule
        %Step 2
        N=0;
        I=0;
        V=0;
        while(1)
           %Step 3a
           N=N+1;

           %Step3b
           x=randn(numDim,1);

           %Step 3c
           SR=(f(-x)+f(x))/2;
           D=(SR-I)/N;
           I=I+D;
           V=(N-2)*V/N+D^2;

           if(V<epsVal2||N==NMax)
               break;
           end
        end

        %V is approximate sample variance....
    case 1 %Degree 3 spherical-radial integration rule
        %Step 2
        N=0;
        I=0;
        V=0;
        F0=f(zeros(numDim,1));
        e=zeros(numDim,1);
        while(1)
            %Step 3a
            N=N+1;
            SR=0;
            %Step 3b
            Q=randOrthoMat(numDim);
            %Step 3c

            rho=ChiD.rand(1,numDim+2);

            %Step 3d
            for j=1:numDim
                e(j)=1;
                x=rho*Q*e;

                SR=SR+f(-x)+f(x);
                e(j)=0;
            end

            %Step 3e
            SR=F0*(1-numDim/rho^2)+SR/(2*rho^2);
            D=(SR-I)/N;
            I=I+D;
            V=(N-2)*V/N+D^2;

            if(V<epsVal2||N==NMax)
                break;
            end
        end
    case 2%Degree 5 spherical-radial integration rule
        m=numDim;
        %Step 2
        N=0;
        I=0;
        V=0;
        F0=f(zeros(m,1));

        v=regularNSimplexCoords(m);
        while(1)
            %Step 3a
            N=N+1;
            %Step 3b
            Q=randOrthoMat(m);
            vTilde=Q*v;
            %Step 3c
            r=ChiD.rand(1,2*m+7);
            q=BetaD.rand(1,m+2,3/2);
            rho=r*sin(asin(q)/2);
            delta=r*cos(asin(q)/2);
            Fv=0;
            Fy=0;

            %Step 3d
            for j=1:(m+1)
                x1=rho*vTilde(:,j);
                x2=delta*vTilde(:,j);

                Fv=Fv+(m+2-delta^2)*(f(-x1)+f(x1))/(rho^2*(rho^2-delta^2))...
                     +(m+2-rho^2)*(f(-x2)+f(x2))/(delta^2*(delta^2-rho^2));

                for i=1:(j-1)
                    y=(vTilde(:,j)+vTilde(:,i))/norm(vTilde(:,j)+vTilde(:,i));

                    x1=rho*y;
                    x2=delta*y;

                    Fy=Fy+(m+2-delta^2)*(f(-x1)+f(x1))/(rho^2*(rho^2-delta^2))...
                         +(m+2-rho^2)*(f(-x2)+f(x2))/(delta^2*(delta^2-rho^2));
                end
            end

            %Step 3e
            SR=F0*(1-m*(rho^2+delta^2-(m+2))/(rho^2*delta^2))+(Fv*(7-m)*m^2+4*Fy*(m-1)^2)/(2*(m+1)^2*(m+2));
            D=(SR-I)/N;
            I=I+D;
            V=(N-2)*V/N+D^2;

            if(V<epsVal2||N==NMax)
                break;
            end
        end
    otherwise
        error('Unknown algorithm specified.')
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


% DEMO_MGP ─ A practical example of the multivariate Gaussian process model
%            with different probabilistic models
%
% Description :
%
%   For many biological real-case scenarios two (or more)
%   animal populations can be strongly interwoven. The way in
%   which species dependent on each other are manifold. For instance,
%   predator-prey relationship, competition, symbiosis, etc.
%
%   It is fundamental to develop mechanistic understanding on the
%   underlying processes that governs the natural growth of the population.
%   However this goal is sometimes difficult and often the models are too
%   complex to derive from first principles. Nowadays, there are many
%   mechanistic models which are developed from first principles and that they
%   are able to describe the population dynamics in a very accurate manner
%   (system of ODEs or PDEs). Nevertheless, in many practical applications
%   it is easier to acquire data from the realization of such underlying biological
%   processes and infer their most probable form. Therefore Bayesian
%   nonparametric models become useful tools.
%
%   The example presented here uses a classical data-set from two animal
%   populations in Canada. The Lynx (Lynx canadensis) and the snowshoe hare
%   (Lepus americanus). The lynx population rise and fall according to the
%   variations in the populations of snowshoe hares over time. That is it, when
%   hares are abundant, lynx populations expand, and when the density of hares is
%   low, the population of lynx shrinks (there are many reasons why).
%   This is know as the predator-prey interaction.
%
%   In this example we want exemplify the joint modelling of the two species
%   population (abundance) aforementioned when data is missing in different
%   time intervals (for both species) and how one species can inform the
%   abundance of each another.
%
%   We assume that the number of lynx and hares follow the
%   negative-binomial distribution given unknown latent values (function
%   values of some unspecified function form for the regression), i.e.,
%
%       N1(t)|f1(t) ~ Neg-Binomial(exp(f1(t)), r1)  (hare)
%       N2(t)|f2(t) ~ Neg-Binomial(exp(f2(t)), r2)  (lynx)
%
%   and that N1(t)|f1(t) is independent of N2(t)|f2(t). The expression exp(f1(t))
%   is the expected value of N1 given f1 and exp(f2(t)) is the expected value
%   of N2 given f2. The correlation is now introduced through the multivariate
%   Gaussian process prior assuming the linear model of coregionalization, i.e.,
%
%       [f1(t), f2(t')] ~ MGP(0, K)
%
%   where K is a full covariance matrix formed by covariance function
%
%       k(fj(t), fj'(t')) = Sig_(c = 1, 2) u_c(j, j') k_c(t, t')
%
%   with u_c(j, j') the (j, j') entry of the matrix U_c = Lc Lc^T, where Lc
%   is cth column of the Cholesky decomposition of the coregionalization
%   matrix (covariance matrix) {Sig}j,j' = sig_j sig_j' rho_{j, j'}. We use the
%   analytical approximation expectation-propagation to carry out the inference
%   over the latent values f1, f2 and then calcule the unconditional expected values
%   of N1 and N2, i.e, E[N1(t)|Y1 = y1, Y2 = y2] and E[N2(t)|Y1 = y1, Y2 = y2].
%
% Additional references :
%
%   Murray, J, D (2002). Mathematical biology. Third Edition. Springer
%    Series.
%
%   Gelfand et al. (2004). Nonstationary multivariate process modelling
%     through spatially varying coregionalization.
%
%   Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian
%    Processes for Machine Learning. The MIT Press.
%
%   Bernardo, J and Smith, A (2008). Bayesian Theory. Wiley series in
%    probability and statistics
%
% -------------- Marcelo Hartmann

%%
% ------- data analysis with the multivariate Gaussian process model

% download the data
S = which('demo_multivariategp');
L = strrep(S, 'demo_multivariategp.m', 'demodata/predpreydata.txt');
data = importdata(L);

% colors;
col = [0 0 1; 1 0 0];

% all time points (yearly)
t = data.data(:, 1);

% full data
yy = [round(data.data(:, 2)); round(data.data(:, 3))];

% take sparse data (you can change the years);
yr1 = [1870, 1900];
% yr1 = [1846,  1935]; one observation
indt1 = ~logical((t >= yr1(1)) .* (t <= yr1(2)));
t1 = t(indt1);

yr2 = [1850, 1870];
% yr2 = [1845, 1934]; one observation
indt2 = ~logical((t >= yr2(1)) .* (t <= yr2(2)));
t2 = t(indt2);

% hare (thousands)
y1 = round(data.data(indt1, 2));

% lynx (thousands)
y2 = round(data.data(indt2, 3));

% predator-prey data;
y = [y1; y2];

% create species markers
c = [ones(size(t1)); 2*ones(size(t2))];

% data gp-format - species markers in the last column
x = [[t1; t2] c];
z = [ones(size(x, 1), 1) c];

% likelihood structure for each species (the likelihood can also be distinct)
lik1 = lik_negbin;
lik2 = lik_negbin;
likS = {lik1 lik2};
lik = lik_liks('likelihoods', likS, 'classVariables', 2);

% correlation function for each species (the correlation functions can also be distinct)
k1 = gpcf_sexp('magnSigma2', 1, 'magnSigma2_prior', prior_fixed, 'selectedVariables', 1);
k2 = gpcf_sexp('magnSigma2', 1, 'magnSigma2_prior', prior_fixed, 'selectedVariables', 1);

% the linear model of coregionalization (multivariate Gaussian process model)
k = gpcf_covar('numberClass', 2, 'classVariables', 2, ...
    'R_prior', prior_corrunif('nu', 3), 'corrFun', {k1 k2});

% set gp structure
% for the EP approximation
gp = gp_set('lik', lik, 'cf', k, 'latent_method', 'EP');

% For the Laplace approximation
%gp = gp_set('lik', lik, 'cf', k, 'latent_method', 'Laplace');

% optimzation options
opt = optimset('TolFun', 1e-3, 'TolX', 1e-5, 'Display', 'iter');

% random initialization (this is important ...)
% wini = 2.* randn(size(gp_pak(gp))); gp = gp_unpak(gp, wini);

% map ─ type-II maximum likelihood
gp = gp_optim(gp, x, y, 'z', z, 'opt', opt);

% check the gradient ...
% gp_g(gp_pak(gp), gp, x, y, 'z', z)';

% take the parameters, hyperparameters estimates
[th ss] = gp_pak(gp);

% correlation matrix estimate
%rho = k.fh.RealToRho(th(end - 2 - 2), 1, [])
Corr = gp.cf{1}.fh.sigma(gp.cf{1}, 'corr');
Corr{1}

% prediction
np = 200;
xp = repmat(linspace(min(x(:, 1)), max(x(:, 1)), np)', 2, 1);
xp = [xp repelem((1:2), np)'];
zp = ones(size(xp, 1), 1);

% leave-one-out
[~, ~, lpyt] = gp_loopred(gp, x, y,'z', z);

% prediction for new observations
[Ef, Varf, ~, Ey, Vary] = gp_pred(gp, x, y, xp, 'z', z, 'zt', [zp xp(:, 2)]);

% --- visualize predictions

figure; hold on;

subplt = subplot(2, 1, 1); hold on
subplt.XLim = [min(xp(:, 1)), max(xp(:, 1))];
psubplt = get(subplt, 'pos');
psubplt(4) = psubplt(4) + 0.03;
psubplt(3) = psubplt(3) + 0.04;
psubplt(1) = psubplt(1) - 0.04;
set(subplt, 'pos', psubplt);

for j = 1:2
    indj = xp(:, 2) == j;
    indX = xp(indj, 1);

    pl(j) = plot(xp(indj, 1), Ey(indj), 'color', col(j, :), 'LineWidth', 2);
 end

% visualize observed (training) predator-pray data
pl(3) = plot(t1(t1 <= yr1(1)), y1(t1 <= yr1(1)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :));
plot(t1(t1 >= yr1(2)), y1(t1 >= yr1(1)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :));
pl(4) = plot(t2(t2 <= yr2(1)), y2(t2 <= yr2(1)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :));
plot(t2(t2 >= yr2(2)), y2(t2 >= yr2(2)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :));

xlabel('years'); ylabel('Population size');
title('multivariate Gaussian process model');

legend(pl, 'E[N_1(t_*)|N_1 = n_1, N_2 = n_2]', 'E[N_2(t_*)|N_1 = n_1, N_2 = n_2]', ...
    'hare-data', 'lynx-data', 'Location', 'northeast');

%%
% -------- data analysis with independent Gaussian process model

EfI = {}; VarfI = {}; EyI = {}; VaryI = {};
gpI = {};

subplt = subplot(2, 1, 2); hold on
subplt.XLim = [min(xp(:, 1)), max(xp(:, 1))];
psubplt = get(subplt, 'pos');
psubplt(4) = psubplt(4) + 0.05;
psubplt(3) = psubplt(3) + 0.04;
psubplt(1) = psubplt(1) - 0.03;
set(subplt, 'pos', psubplt);

for j = 1:2
    inddj = x(:, 2) == j;
    cf = gpcf_sexp('selectedVariables', 1);

    gpI{j} = gp_set('lik', likS{j}, 'cf', cf);
    gpI{j} = gp_optim(gpI{j}, x(inddj, :), y(inddj), 'opt', opt);

    indj = xp(:, 2) == j;
    indX = xp(indj, 1);

    [EfI{j}, VarfI{j}, lpyt, EyI{j}, VaryI{j}] = ...
        gp_pred(gpI{j}, x(inddj, :), y(inddj), xp(indj, :));

    pl(j) = plot(xp(indj, 1), EyI{j}, 'color', col(j, :), 'LineWidth', 1.7);
end

% visualize observed (training) predator-pray data
pl(3) = plot(t1(t1 <= yr1(1)), y1(t1 <= yr1(1)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :));
plot(t1(t1 >= yr1(2)), y1(t1 >= yr1(1)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :));
pl(4) = plot(t2(t2 <= yr2(1)), y2(t2 <= yr2(1)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :));
plot(t2(t2 >= yr2(2)), y2(t2 >= yr2(2)), '.', ...
    'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :));

xlabel('years'); ylabel('Population size');
title('independent Gaussian process models');

legend(pl, 'E[N1(t)|Y1 = y1, Y2 = y2]', 'E[N2(t)|Y1 = y1, Y2 = y2]', ...
    'hare-data', 'lynx-data', 'Location', 'northeast');

%%
% ------ all measurements (compare the difference ...)

figure; hold on;

for j = 1:2
    indj = x(:, 2) == j;
    plot(x(indj, 1), y(indj), '.', 'MarkerSize', 13, 'color', col(j, :))
    pd(j) =  plot(t, yy((j - 1) * 91 + [1:91]), '.-', ...
        'color', col(j, :), 'MarkerSize', 23, 'LineWidth', 2);
end

xlabel('years'); ylabel('Population size');
title('full data');

legend(pd, 'hare-data', 'lynx-data', 'Location', 'northeast');


function bernoulli_poly_values_test ( )

%*****************************************************************************80
%
%% BERNOULLI_POLY_VALUES_TEST demonstrates the use of BERNOULLI_POLY_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BERNOULLI_POLY_VALUES_TEST\n' );
  fprintf ( 1, '  BERNOULLI_POLY_VALUES stores values of\n' );
  fprintf ( 1, '  the Bernoulli polynomials.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      N            X            FX\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, n, x, fx ] = bernoulli_poly_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %6d  %12f  %24.16f\n', n, x, fx );

  end

  return
end


function rule_test ( rule_fun, rule_title )

%*****************************************************************************80
%
%% RULE_TEST tests a rule simply by printing out some examples of it.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 February 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameter:
%
%    Input, function pointer [ X, W ] = RULE_FUN ( N );
%
%    Input, string RULE_TITLE, a description of the rule.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'RULE_TEST\n' );
  fprintf ( 1, '  Compute and display points and weights of a rule.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Rule is %s\n', rule_title );

  for n = 1 : 8
    [ x, w ] = rule_fun ( n );
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Order = %d\n', n );
    fprintf ( 1, '\n' );
    for i = 1 : n
      fprintf ( 1, '  %2d  %10f  %10f\n', i, x(i), w(i) );
    end

  end

  return
end


function [y, dzdg, dzdb] = vl_nngnorm(x, g, b, varargin)
%VL_NNGNORM CNN group normalization.
%   Y = VL_NNGNORM(X,G,B) applies group normalization
%   to the input X with shape HxWxCxN. Group normalization is defined as:
%
%      Y(i,j,k,t) = G(k',t) * X_HAT(i,j,k,t) + B(k',t)
%
%   where
%      k' = group_idx(k,C,G), where N_G is the number of groups and
%        group_idx(k,C,G) := floor(k / (C/N_G)).
%      X_HAT(i,j,k,t) = (X_HAT(i,j,k,t) - mu(k',t)) / sigma(k',t)
%      mu(k',t) = mean_ijk'' X(i,j,k'',t),
%      sigma2(k',t) = mean_ijk'' (X(i,j,k'',t) - mu(k'',t))^2,
%      sigma(k',t) = sqrt(sigma2(k) + EPSILON)
%        where k'' takes values such that group_idx(k'',C,G) == group_idx(k,C,G)
%
%   VL_NNGNORM(..., 'option', value, ...) takes the following option:
%
%   `numGroups`:: 32
%    The number of groups used to split the channels when computing
%    normalization statistics.
%
%   `epsilon`:: 1e-4
%    A parameter to add stability to the normalization operation.
%
%   Notes: GroupNorm is introduced in the paper:
%      `Group Normalization, Yuxin Wu, Kaiming He,
%      arXiv preprint arXiv:1803.08494 (2018)
%
% Copyright (C) 2018 Samuel Albanie
% All rights reserved.

  opts.numGroups = 32 ;
  opts.epsilon = 1e-4 ;
  [opts,dzdy] = vl_argparsepos(opts, varargin) ;

  bsize = size(x, 4) ;
  expectedSz = [1 1 size(x,3) 1] ;
  sg = size(g) ; sb = size(b) ;
  assert(all(expectedSz(1:numel(sg)) == sg), 'GAINS have unexpected size') ;
  assert(all(expectedSz(1:numel(sb)) == sb), 'BIASES have unexpected size') ;

  szX = size(x) ; % store original shape

  % compute statistics per group for current minibatch and normalize
  x = reshape(x, size(x,1), size(x,2), [], opts.numGroups, bsize) ;

  mu = groupAvg(x) ;
  sigma2 = groupAvg(bsxfun(@minus, x, mu).^ 2) ;
  sigma = sqrt(sigma2 + opts.epsilon) ;
  x_hat = bsxfun(@rdivide, bsxfun(@minus, x, mu), sigma) ;

  if isempty(dzdy)
    x_hat_ = reshape(x_hat, szX) ;
    y = bsxfun(@times, g, x_hat_) ; % apply gain
    y = bsxfun(@plus, y, b) ; % add bias
  else
    dzdy = dzdy{1} ;
    dzdb = chanSum(dzdy) ;
    x_hat_ = reshape(x_hat, szX) ; dzdg = chanSum(x_hat_ .* dzdy) ;
    dzdy = reshape(dzdy, size(x,1), size(x,2), [], opts.numGroups, bsize) ;

    g_ = reshape(g, 1, 1, size(dzdy, 3), []) ;
    dzdx_hat = bsxfun(@times, dzdy, g_) ;
    t1 = bsxfun(@minus, x, mu) ;
    m = prod([size(x,1) size(x,2) size(x,3)]) ;
    dzdsigma = groupSum((-1/2) * dzdx_hat .* bsxfun(@rdivide, t1, sigma.^3)) ;

    dzdmu = groupSum(bsxfun(@rdivide, dzdx_hat, -sigma)) + ...
                bsxfun(@times, dzdsigma, -2 * groupAvg(t1)) ;

    t4 = bsxfun(@rdivide, dzdx_hat, sigma) + ...
         bsxfun(@times, dzdsigma,  (2 / m) * t1) ;
    dzdx = bsxfun(@plus, t4, dzdmu * (1/m)) ;
    y = reshape(dzdx, szX) ;
  end

% ----------------------------------------
function avg = groupAvg(x)
% ----------------------------------------
  avg = mean(mean(mean(x, 1), 2), 3) ;

% -----------------------
function res = groupSum(x)
% -----------------------
  res = sum(sum(sum(x, 1), 2), 3) ;

% -----------------------
function res = chanSum(x)
% -----------------------
  res = sum(sum(sum(x, 1), 2), 4) ;


% Fig. 9.12  Feedback Control of Dynamic Systems, 5e
%             Franklin, Powell, Emami
% script to generate figure 9.12
% using the general simulation nonlin
N=1;
a=2;
r=0;
num=[1 2 1];
den=[1 0 0 0];
rlocus(num,den)
axis([-6 2 -3 3])
title('Root locus for the system of Figure 9.12')
 z=0:.1:.9;
 wn= 1:6;
 sgrid(z, wn)
 hold off


function showboundary(node,elem,expr,varargin)
%% SHOWBOUNDARY boundary mesh plot
%
%    showboundary(node,elem) displays the boundary surface mesh of a
%    3-dimensional tetrahderon mesh given by node and elem matrices. The
%    boundary is found by the function findboundary3.
%
%    showboundary(node,elem,expr) displays the boundary of parts of the
%    mesh specificed by the expression. For example,
%    showboundary3(node,elem,'~(x>=0 & y>=0 & z>=0)') only shows the boundary
%    mesh for tetrahedrons not in the first quadrant.
%
%    showboundary(node,elem,expr,viewangle) changes the display angle. The
%    deault view angle is view(3).
%
%    showboundary(node,elem,expr,'param','value','param','value'...)
%    allows additional patch param/value pairs to be used when displaying
%    the mesh. For example, the default transparency parameter is set to
%    0.5. You can overwrite this value by using the param pair
%    ('FaceAlpha', value). The value has to be a number between 0 and 1.
%    Other parameters include: 'Facecolor', 'Edgecolor' etc.
%
%    To display the tetrahedron mesh in 3-d, use showmesh3. Notice that the
%    3-d graphical visulization is slow for large mesh data.
%
%   Example:
%     node = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1];
%     elem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];
%     [node,elem] = uniformbisect3(node,elem);
%     subplot(1,2,1);
%     showboundary3(node,elem);
%     subplot(1,2,2);
%     showboundary3(node,elem,'~(x>=0 & y>=0 & z>=0)',[59,20]);
%
%   See also showboundary, showsolution3, showmesh.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

if (nargin >= 3) && (any(expr))
    x = node(:,1);  y = node(:,2);  z = node(:,3); %#ok<*NASGU>
    incl = find(eval(expr));
    elem = elem(any(ismember(elem,incl),2),:);
end
[bdNode, bdFace] = findboundary3(elem); %#ok<*ASGLU>
if isempty(varargin)
    showmesh(node,bdFace);
else
    showmesh(node,bdFace,varargin{1:end});
end


function geometry_test0325 ( )

%*****************************************************************************80
%
%% TEST0325 tests ICOS_SIZE, ICOS_SHAPE, SHAPE_PRINT_3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST0325\n' );
  fprintf ( 1, '  For the icosahedron,\n' );
  fprintf ( 1, '  ICOS_SIZE returns dimension information;\n' );
  fprintf ( 1, '  ICOS_SHAPE returns face and order information.\n' );
  fprintf ( 1, '  SHAPE_PRINT_3D prints this information.\n' );

  [ point_num, edge_num, face_num, face_order_max ] = icos_size ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of points =   %d\n', point_num );
  fprintf ( 1, '  Number of edges =    %d\n', edge_num );
  fprintf ( 1, '  Number of faces =    %d\n', face_num );
  fprintf ( 1, '  Maximum face order = %d\n', face_order_max );

  [ point_coord, edge_point, face_order, face_point ] = icos_shape ( ...
    point_num, edge_num, face_num, face_order_max );

  shape_print_3d ( point_num, face_num, face_order_max, ...
    point_coord, face_order, face_point );

  return
end


function out = DatesOption(fo_year,lo_year,frequency,fo_period,lo_period)
% =======================================================================
% For given initial observation, final observation and frequency this
% function computes the number of observations between them and creates a
% cell aray with the dates (of the type 1979M2).
% =======================================================================
% out = DatesOption(fo_year,lo_year,frequency,fo_period,lo_period)
% -----------------------------------------------------------------------
% INPUT
%	- fo_year: initial year of the timeline
%	- lo_year: final year of the timeline
%	- frequency: quarterly 'q' [def], monthly 'm', yearly 'y'
% -----------------------------------------------------------------------
% OPTIONAL INPUT
%   - fo_period: initial quarter/month of the timeline (not for
%       yearly frequency)
%   - lo_period: last quarter/month of the timeline (not for yearly
%       frequency)
% -----------------------------------------------------------------------
% OUTPUT
%	- out: structuree with all info
% =======================================================================
% Ambrogio Cesa Bianchi, March 2015
% ambrogio.cesabianchi@gmail.com

% Check inputs
if ~exist('frequency','var')
    frequency = 'q';
end

if strcmp(frequency,'m')
    if ~exist('fo_period','var'), error('You need to provide first period'), end
    if ~exist('lo_period','var'), error('You need to provide last period'), end
    fo = fo_year + fo_period*(1/12);
    lo = lo_year + lo_period*(1/12);
    aux = fo:(1/12):lo;
    nobs = length(aux);
elseif strcmp(frequency,'q')
    if ~exist('fo_period','var'), error('You need to provide first period'), end
    if ~exist('lo_period','var'), error('You need to provide last period'), end
    fo = fo_year + fo_period*(1/4);
    lo = lo_year + lo_period*(1/4);
    aux = fo:(1/4):lo;
    nobs = length(aux);
elseif strcmp(frequency,'y')
    fo = fo_year;
    lo = lo_year;
    aux = fo:lo;
    nobs = length(aux);
end

% Get first
if strcmp(frequency,'y')
    [out.dates, out.dates_short] = DatesCreate(fo_year,nobs,frequency);
else
    [out.dates, out.dates_short] = DatesCreate(fo_year,nobs,frequency,fo_period);
end

out.nobs = nobs;
out.fo_year = fo_year;
out.lo_year = lo_year;
out.frequency = frequency;
out.fo_period = fo_period;
out.lo_period = lo_period;


function x = quasigeometric_cdf_inv ( cdf, a, b )

%*****************************************************************************80
%
%% QUASIGEOMETRIC_CDF_INV inverts the Quasigeometric CDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real CDF, the value of the CDF.
%    0.0 <= CDF <= 1.0
%
%    Input, real A, the probability of 0 successes.
%    0.0 <= A <= 1.0.
%
%    Input, real B, the depreciation constant.
%    0.0 <= B < 1.0.
%
%    Output, integer X, the corresponding value of X.
%
  if ( cdf < 0.0 | 1.0 < cdf )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'QUASIGEOMETRIC_CDF_INV - Fatal error!\n' );
    fprintf ( 1, '  CDF < 0 or 1 < CDF.\n' );
    error ( 'QUASIGEOMETRIC_CDF_INV - Fatal error!' );
  end

  if ( cdf < a )
    x = 0;
  elseif ( b == 0.0 )
    x = 1;
  else
    x = 1 + floor ( ( log ( 1.0 - cdf ) - log ( 1.0 - a ) ) / log ( b ) );
  end

  return
end


function ex5bvp
%EX5BVP  Example 5 of the BVP tutorial.
%   Falkner-Skan BVPs are discussed in T. Cebeci and H.B. Keller,
%   Shooting and parallel shooting methods for solving the Falkner-Skan
%   boundary-layer equation, J. Comp. Phy., 7 (1971) 289-300.  This is
%   the positive wall shear case for which the parameter beta is known
%   and the problem is to be solved for a range of the parameter.  This
%   is the hardest case of the table in the paper.
%
%   The problem is posed on [0 infinity).  As in the paper cited, the
%   boundary condition at infinity is imposed at a finite point, here
%   called 'infinity'.  It is best to start with a relatively small value
%   and increase it until consistent results are obtained.  A value of 6
%   appears to be satisfactory.  Starting with a "large" value is tempting,
%   but not a good tactic because the code will fail with the crude guess
%   and default tolerances used here.

% Copyright 1999, The MathWorks, Inc.

%  'infinity' is a variable to facilitate experimentation.
infinity = 6;

%  The constant guess for the solution satisfies the boundary conditions.
solinit = bvpinit(linspace(0,infinity,5),[0 0 1]);

options = bvpset('stats','on');

sol = bvp4c(@ex5ode,@ex5bc,solinit,options);
eta = sol.x;
f = sol.y;

fprintf('\n');
fprintf('Cebeci & Keller report f''''(0) = 0.92768.\n')
fprintf('Value computed here is f''''(0) = %7.5f.\n',f(3,1))

clf reset
plot(eta,f(2,:));
axis([0 infinity 0 1.4]);
title('Falkner-Skan equation, positive wall shear, \beta = 0.5.')
xlabel('\eta')
ylabel('df/d\eta')
shg

% --------------------------------------------------------------------------

function dfdeta = ex5ode(eta,f)
%EX5ODE  ODE function for Example 5 of the BVP tutorial.
beta = 0.5;
dfdeta = [ f(2)
           f(3)
          -f(1)*f(3) - beta*(1 - f(2)^2) ];

% --------------------------------------------------------------------------

function res = ex5bc(f0,finf)
%EX5BC  Boundary conditions for Example 5 of the BVP tutorial.
res = [f0(1)
       f0(2)
       finf(2) - 1];


function butterfly
% BUTTERFLY Visualize payoff schedule of option strategy
% PURPOSE : The function aims to assist students and instructors of
%           finance in visualizing payoffs of simple option strate-
%           gies. Portfolios of n < 9 securities including a stock,
%           a zero-coupon bond,  a forward contract, and a European
%           call or  put option, are allowed. Terminal  payoff  and
%           terminal payoff adjusted for accrued time-0 expense are
%           plotted. Discounting and valuation follow Black-Scholes.
% EXAMPLE : buttefly (Oh, the FEX code metrics..)
% AUTHOR  : Dimitri Shvorob, dimitri.shvorob@vanderbilt.edu, 11/5/07

fw = 560;     fh = 350;
bx = .62*fw;  by = .07*fh;
ew = .08*fw;  eh = .5*ew;
tx = .1*ew;   ty = .25*eh;
bw = 2*ew+tx; bh = .25*bw;
wy = 1.5*bh;
x2 = bx+bw+tx;
x3 = x2+ew+tx;

n = 8;  % max number of securities
st = {' Stock', ...
      ' Bond', ...
      ' Forward', ...
      ' Call option', ...
      ' Put option'};
pT = {'S', ...
      'K', ...
      '(S-K)', ...
      'max(S-K,0)', ...
      'max(K-S,0)'};
p0 = {'(-S0)', ...
      '(-exp(-R*T)*K)', ...
      '(exp(-R*T)*K-S0)', ...
      '(-blscall(S0,K,R,T,sigma))', ...
      '(-blsput(S0,K,R,T,sigma))'};

ax = setupAxisAndButtons;
hp = setupParameterSelection;
[hs,hk,hn] = setupSecuritySelection;
clearSecuritySelection

function[ax] = setupAxisAndButtons
ax = .05; ay = (by + bh + wy)/fh;
ah = .7;  aw = (bx - ew)/fw;
figure('Name','Butterfly: visualize payoffs of an option strategy', ...
       'NumberTitle','off', 'Position',[232 246 fw fh], ...
       'Color','white','Resize','off','MenuBar','none');
ax = axes('Position' ,[ax ay aw ah],'FontSize',8);
guiinput('pushbutton',[bx by bw bh],'Plot' ,@evalSecuritySelection);
guiinput('pushbutton',[x2 by bw bh],'Reset',@clearSecuritySelection);
end

function[h] = setupParameterSelection
tw = .75*bw;
iw = .75*ew;
tt = .10*ew;
v = {'90' ,'100','0.05';
     '110','0.1','1'};
l = {'xmin','Stock price','Interest rate';
     'xmax','Volatility','Time to expiry'};
h = nan(2,3);
for i = 1:2
   y = .4*by + (i-1)*(eh + ty);
   for j = 1:3
       x = (j-1)*(tw + tx + iw + tt);
       guilabel([x y-4 tw eh],l{i,j});
       h(i,j) = guiinput('edit',[x+tw+tx y iw eh],v{i,j},@checkIfPositive);
   end
end
end

function[hs,hk,hn] = setupSecuritySelection
bx = .62*fw;
by = .07*fh;
[hs,hk,hn] = deal(nan(n,1));
for i = 1:n
    y = by + bh + wy + (i-1)*(eh + ty);
    hs(i) = guiinput('popupmenu',[bx y-3 bw eh+2],st,'');
    hk(i) = guiinput('edit',[x2 y ew eh],'',@checkIfPositive);
    hn(i) = guiinput('edit',[x3 y ew eh],'',@checkIfNumber);
end
y = y + ty + 1.2*eh;
guilabel([bx y bw eh],'Security type')
guilabel([x2 y-10 ew 2*eh],{'Strike /','Face value'})
guilabel([x3 y ew eh],'Units')
end

function[h] = guiinput(style,position,string,callback)
h = uicontrol('Style',style,'Position',position,'BackgroundColor','white',...
              'FontSize',8,'String',string,'Callback',callback);
end

function guilabel(position,string)
guiinput('text',position,string,'');
end

function checkIfPositive(hObject,eventdata)      %#ok
i = str2double(get(hObject,'String'));
if isnan(i) || i < 0, beep, end
end

function checkIfNumber(hObject,eventdata)        %#ok
i = str2double(get(hObject,'String'));
if isnan(i), beep, end
end

function evalSecuritySelection(hObject,eventdata)%#ok
cla(ax)
[p,e] = evalSchedule;
plotSchedule(p,e)
end

    function[p,e] = evalSchedule
    p = ''; e = '';
    for i = 1:n
        m = get(hn(i),'String');
        if ~isempty(m)
           if strcmp(m(1),'-')
              m = ['(' m ')'];
           end
           s = get(hs(i),'Value');
           k = get(hk(i),'String');
           p = [p '+(' m '*'           strrep(pT{s},'K',k)  ')'];
           e = [e '+(exp(R*T)*(' m '*' strrep(p0{s},'K',k) '))'];
        end
    end
    v = {'S0','R'; 'sigma','T'};
    for i = 1:2
        for j = 1:2
            m = get(hp(i,j+1),'String');
            p = strrep(p,v{i,j},m);
            e = strrep(e,v{i,j},m);
        end
    end
    end

    function plotSchedule(p,e)
    try
       a = str2double(get(hp(1,1),'String'));
       b = str2double(get(hp(2,1),'String'));
       x = linspace(a,b,100);
       p = feval(eval(['@(S) ' p]),x);
       e = feval(eval(['@(S) ' e]),x);
       plot(ax,x,p  ,'Color',[.1 .1 .1],'LineWidth',1.5); hold on
       plot(ax,x,p+e,'Color',[.8 .8 .8],'LineWidth',1.5); hold on
       legend(ax,'\pi_{\itT}','\pi_{\itT} + \ite^{rT}\rm\pi_{0}','Location','Best')
       legend('boxoff')
       plot(ax,[a b],[0 0],'k:')
    catch
       beep
    end

end

function clearSecuritySelection(hObject,eventdata) %#ok
% Clear/initialize security selections
m = fliplr([1:5 4 4 5]);
for i = 1:n
    set(hn(i),'String','')
    set(hk(i),'String','')
    set(hs(i),'Value',m(i))
end
cla(ax)
end

function[c] = blscall(S,K,r,T,sigma)
% Black-Scholes call price
d = (log(S/K) + (r + [1 -1]*sigma^2/2)*T)/(sigma*sqrt(T));
c = S*normcdf(d(1)) - K*exp(-r*T)*normcdf(d(2));
end

function[p] = blsput(S,K,r,T,sigma)
% Black-Scholes put price
d = -(log(S/K) + (r + [1 -1]*sigma^2/2)*T)/(sigma*sqrt(T));
p = K*exp(-r*T)*normcdf(d(2)) - S*normcdf(d(1));
end

end


function F=scarsplslda(X,y,A,K,method,num,OPT)
%+++ This is the simplified version of CARS, only retaining the EDF element.
%+++ num: the number of Monte Carlo Sampling.
%+++ A:   the maximal number of PLS components to extract.
%+++ fold: number of folds for cross validation.
%+++ method: pretreat method, 'center' or 'autoscaling'.
%+++ OPT: 1: Plot. 0: No plot.
%+++ Advisor: Yizeng Liang, yizeng_liang@263.net.
%+++ Hongdong Li, Jan.3, 2009.
%+++ Reference: Hongdong Li, Yizeng Liang, Qingsong Xu and Dongsheng Cao,
%         Key wavelengths screening using competitive adaptive reweighted sampling method
%         for multivariate calibration J?. Anal. Chim. Acta, 2009, 648 (1): 77-84

%+++ Initial settings.
if nargin<7;OPT=1;end;  %+++ OPT==1: then figure output.
if nargin<6;num=50;end
if nargin<5;method='autoscaling';end
if nargin<4;K=5;end
if nargin<3;A=2;end

[Mx,Nx]=size(X);
A=min([Mx Nx A]);
index=1:Nx;

r0=1;
r1=2/Nx;
Vsel=1:Nx;

W=zeros(num,Nx);
Ratio=zeros(1,num);

%+++ Parameter of exponentially decreasing function.
b=log(r0/r1)/(num-1);  a=r0*exp(b);

%+++ Main Loop
for iter=1:num

     LDA=plslda(X(:,Vsel),y,A,method);    %+++ PLS model
     w=zeros(Nx,1);coef=LDA.coef_lda_origin(1:end-1);
     w(Vsel)=coef;W(iter,:)=w;
     w=abs(w);                                  %+++ weights
     [ws,indexw]=sort(-w);                      %+++ sort weights

     ratio=a*exp(-b*(iter+1));                      %+++ Ratio of retained variables.
     Ratio(iter)=ratio;
     K=round(Nx*ratio);

     w(indexw(K+1:end))=0;                      %+++ Eliminate some variables with small coefficients.

     Vsel=find(w~=0);
     fprintf('The %dth variable sampling finished.\n',iter);    %+++ Screen output.
 end

%+++  Cross-Validation to choose an optimal subset;
RMSEP=zeros(1,num);
Rpc=zeros(1,num);
for i=1:num
   vsel=find(W(i,:)~=0);
   CV=plsldacv(X(:,vsel),y,A,10,method,0);
   RMSEP(i)=min(CV.cv);
   Rpc(i)=CV.optPC;
   fprintf('The %dth subset finished.\n',i);
end
Rmin=min(RMSEP);
indexOPT=find(RMSEP==Rmin);
indexOPT=indexOPT(end);

%+++ output
F.method=method;
F.nPC=A;
F.W=W;
F.vim=sum(W,2);
F.cv=RMSEP;
F.minCV=Rmin;
F.iterOPT=indexOPT;
F.optPC=Rpc(indexOPT);
F.ratio=Ratio;
F.vsel=find(W(indexOPT,:)~=0)';
F.vim=abs(sum(W));

%+++ Plot
 if OPT==1;plotcars(F);end;
%+++ END