function [vals, pos] = minandmax(f)
%MINANDMAX   Global minimum and maximum of the SINGFUN F on [-1,1].
%   VALS = MINANDMAX(F) returns a 2-vector VALS = [MIN(F); MAX(F)] with the
%   global minimum and maximum of the SINGFUN F on [-1,1].
%
%   [VALS, POS] = MINANDMAX(F) returns also the 2-vector POS where the minimum
%   and maximum of F occur.
%
% See also MIN, MAX.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

tol = chebfunpref().blowupPrefs.exponentTol;

if ( ~any(f.exponents) || all(abs(f.exponents) < tol) )

    % The function is actually smooth!
    [vals, pos] = minandmax(f.smoothPart);

else

    % Initialise:
    minF = [];
    maxF = [];
    minLoc = [];
    maxLoc = [];

    % Look for blow up at the left:
    if ( f.exponents(1) < -tol ) % Singularity at the left end.
        fVal = feval(f, -1);
        if ( fVal == inf )
            maxF = inf;
            maxLoc = -1;
        elseif ( fVal == -inf )
            minF = -inf;
            minLoc = -1;
        else
            % NaNs may occur and then we can not conclude anything.
            error('CHEBFUN:SINGFUN:minandmax:boundedness', ...
            ['Function has a singularity but isn''t infinite at the left ' ...
             'endpoint']);
        end
    end

    % Look for blow up at the right:
    if ( f.exponents(2) < -tol ) % Singularity at the right end.
        fVal = feval(f, 1);
        if ( fVal == inf )
            maxF = inf;
            maxLoc = 1;
        elseif ( fVal == -inf )
            minF = -inf;
            minLoc = 1;
        else
            % NaNs may occur and then we can not conclude anything.
            error('CHEBFUN:SINGFUN:minandmax:boundedness', ...
            ['Function has a singularity but isn''t infinite at the right ' ...
             'endpoint']);
        end
    end

    % If min or max is empty, then we need to do more work:
    if ( isempty(minF) || isempty(maxF) )
        % Find the roots of the derivative for local minima:
        fp = diff(f);
        r = roots(fp);
        % Append the end points and remove duplicates:
        r = unique([-1 ; r ; 1]);
        if ( isempty(maxF) )
            % Take the maximum of the local maxima:
            [maxF, maxIndex] = max(feval(f, r));
            maxLoc = r(maxIndex);
        end
        if ( isempty(minF) )
            % Take the minimum of the local minima:
            [minF, minIndex] = min(feval(f, r));
            minLoc = r(minIndex);
        end
    end
    vals = [ minF; maxF ];
    pos = [ minLoc; maxLoc ];

end

end


%% Copyright (C) 2016 Abhinav Tripathi
%% Copyright (C) 2016, 2018-2019, 2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 3 of the License,
%% or (at your option) any later version.
%%
%% This software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod @@sym chebyshevU (@var{n}, @var{x})
%% Find the nth symbolic Chebyshev polynomial of the second kind.
%%
%% If @var{n} is a vector then it returns a vector with Chebyshev polynomials
%% of the second kind for each element of @var{n}.
%%
%% Examples:
%% @example
%% @group
%% syms x
%% chebyshevU(1, x)
%%   @result{} (sym) 2⋅x
%% chebyshevU(2, x)
%%   @result{} (sym)
%%          2
%%       4⋅x  - 1
%% syms n
%% chebyshevU(n, x)
%%   @result{} (sym) chebyshevu(n, x)
%% @end group
%% @end example
%%
%% The inputs can be vectors, for example:
%% @example
%% @group
%% syms x
%% chebyshevU([0 1 2], x)
%%   @result{} (sym 1×3 matrix)
%%       ⎡           2    ⎤
%%       ⎣1  2⋅x  4⋅x  - 1⎦
%% @end group
%% @end example
%%
%% @seealso{@@sym/chebyshevT, @@double/chebyshevU}
%% @end defmethod

function y = chebyshevU(n, x)
  if (nargin ~= 2)
    print_usage ();
  end
  y = elementwise_op ('chebyshevu', sym(n), sym(x));
end

%!error chebyshevU (sym(1))
%!error chebyshevU (sym(1), 2, 3)

%!assert (isequaln (chebyshevU (2, sym(nan)), sym(nan)))

%!shared x
%! syms x

%!assert(isequal(chebyshevU(0, x), sym(1)))
%!assert(isequal(chebyshevU(1, x), 2*x))
%!assert(isequal(chebyshevU(2, x), 4*x*x - 1))
%!assert(isequal(chebyshevU([0 1 2], x), [sym(1) 2*x (4*x*x-1)]))

%!test
%! % round trip
%! syms n z
%! f = chebyshevU (n, z);
%! h = function_handle (f, 'vars', [n z]);
%! A = h (1.1, 2.2);
%! B = chebyshevU (1.1, 2.2);
%! assert (A, B)


%% ggremesh
% Below is a demonstration of the features of the |ggremesh| function

%% Syntax
% |[Fn,Vn]=ggremesh(F,V,optionStruct)|

%% Description
% This function uses the external library Geogram to remesh the input
% triangulation defined by the faces F and the vertices V. In particular
% the code "vorpalite" is used. An additional option structure may be
% provided where users can set particular parameters for Geogram.
%
% Below the options and defaults are provided:
% optionStruct.nb_pts=size(V,1); %number of points
% optionStruct.anisotropy=0; %Use anisotropy (~=0) to capture geometry or favour isotropic triangles (=0)
% optionStruct.pre.max_hole_area=100; %Max hole area for pre-processing step
% optionStruct.pre.max_hole_edges=0; %Max number of hole edges for pre-processing step
% optionStruct.post.max_hole_area=100; %Max hole area for post-processing step
% optionStruct.post.max_hole_edges=0; %Max number of hole edges for post-processing step
% optionStruct.disp_on=1; %Turn on/off displaying of Geogram text
%
% Instead of nb_pts users can also specify a pointSpacing to be used
% instead of nb_pts. This is not a Geogram feature but a GIBBON option
% which is translated to the number of points for Geogram remeshing. This
% is and example for a desired point spacing of 4:
% optionStruct.pointSpacing=4
%
% Geogram website:
% http://alice.loria.fr/index.php/software/4-library/75-geogram.html
%
% Geogram license:
% http://alice.loria.fr/software/geogram/doc/html/geogram_license.html
%
% Lévy B., Bonneel N. (2013) Variational Anisotropic Surface Meshing with
% Voronoi Parallel Linear Enumeration. In: Jiao X., Weill JC. (eds)
% Proceedings of the 21st International Meshing Roundtable. Springer,
% Berlin, Heidelberg. https://doi.org/10.1007/978-3-642-33573-0_21
%
% See also:
% http://alice.loria.fr/publications/papers/2012/Vorpaline_IMR/vorpaline.pdf
% https://www.ljll.math.upmc.fr/hecht/ftp/ff++days/2013/BrunoLevy.pdf

%% Examples

%%
clear; close all; clc;

%%
% Plot settings
fontSize=15;
faceColor='b';
faceAlpha=1;
edgeColor='k';
edgeWidth=0.5;

%% Example 1: Remeshing a triangulated surface isotropically

%%
% Get example geometry
[F,V]=graphicsModels(5); % Get surface

%%
% Remesh using ggremesh

[Fn,Vn]=ggremesh(F,V);

%%
% Visualiza patch data

cFigure;
subplot(1,2,1); hold on;
title('Input mesh');
gpatch(F,V,'w','k');
axisGeom;
view(-75,-36);
camlight headlight; axis off;

subplot(1,2,2); hold on;
title('Geogram remeshed');
gpatch(Fn,Vn,'gw','k',1,1);
axisGeom;
view(-75,-36);
camlight headlight; axis off;

gdrawnow;

%% Example 2: Remeshing a triangulated surface with desired number of points

%%
% Get example geometry
[F,V]=graphicsModels(1); % Get surface

%%
% Remesh using ggremesh

optionStruct1.nb_pts=500; %Set desired number of points
[Fn,Vn]=ggremesh(F,V,optionStruct1);

%%
% Visualiza patch data

cFigure;
subplot(1,2,1); hold on;
title('Input mesh');
gpatch(F,V,'w','k');
axisGeom;
camlight headlight; axis off;

subplot(1,2,2); hold on;
title('Geogram remeshed');
gpatch(Fn,Vn,'gw','k',1,1);
axisGeom;
camlight headlight; axis off;

gdrawnow;

%% Example 3: Remeshing a triangulated surface with desired point spacing

%%
% Get example geometry
[F,V]=graphicsModels(11); % Get surface

%%
% Remesh using ggremesh

optionStruct2.pointSpacing=4; %Set desired point spacing
optionStruct2.disp_on=1; % Turn off command window text display
[Fn,Vn]=ggremesh(F,V,optionStruct2);

%%
% Visualiza patch data

cFigure;
subplot(1,2,1); hold on;
title('Input mesh');
gpatch(F,V,'w','k');
axisGeom;
camlight headlight;

subplot(1,2,2); hold on;
title('Geogram remeshed');
gpatch(Fn,Vn,'gw','k',1,1);
axisGeom;
camlight headlight;

gdrawnow;

%% Example 4: Setting pre- and prost-processing settings e.g. to close holes

%%
% Get example geometry

inputStruct.cylRadius=1;
inputStruct.numRadial=15;
inputStruct.cylHeight=3;
inputStruct.numHeight=11;
inputStruct.meshType='tri';

% Derive patch data for a cylinder
[F,V]=patchcylinder(inputStruct);

%%
% Remesh using ggremesh
optionStruct3.nb_pts=size(V,1); %Set desired number of points
optionStruct3.disp_on=0; % Turn off command window text display
optionStruct3.pre.max_hole_area=10; %Max hole area for pre-processing step
optionStruct3.pre.max_hole_edges=20; %Max number of hole edges for pre-processing step
% optionStruct3.post.max_hole_area=10; %Max hole area for post-processing step
% optionStruct3.post.max_hole_edges=20; %Max number of hole edges for post-processing step

[Fn,Vn]=ggremesh(F,V,optionStruct3);

% Visualiza patch data
Eb=patchBoundary(F);
cFigure;
subplot(1,2,1); hold on;
title('Input mesh with holes');
gpatch(F,V,'w','k');
gpatch(Eb,V,'none','b',1,2);
axisGeom;
camlight headlight;

subplot(1,2,2); hold on;
title('Geogram remeshed and closed');
gpatch(Fn,Vn,'gw','k',1,1);
axisGeom;
camlight headlight;

gdrawnow;

%% Example 5: Setting pre- and prost-processing settings e.g. to avoid closure of holes

%%
% Get example geometry

inputStruct.cylRadius=1;
inputStruct.numRadial=15;
inputStruct.cylHeight=3;
inputStruct.numHeight=11;
inputStruct.meshType='tri';

% Derive patch data for a cylinder
[F,V]=patchcylinder(inputStruct);

%%
% Remesh using ggremesh
optionStruct3.nb_pts=size(V,1); %Set desired number of points
optionStruct3.disp_on=1; % Turn off command window text display
optionStruct3.pre.max_hole_area=100; %Max hole area for pre-processing step
optionStruct3.pre.max_hole_edges=0; %Max number of hole edges for pre-processing step

[Fn,Vn]=ggremesh(F,V,optionStruct3);

% Visualiza patch data
Eb=patchBoundary(F);
cFigure;
subplot(1,2,1); hold on;
title('Input mesh with holes');
gpatch(F,V,'w','k');
gpatch(Eb,V,'none','b',1,2);
axisGeom;
camlight headlight;

subplot(1,2,2); hold on;
title('Geogram remeshed with holes');
gpatch(Fn,Vn,'gw','k',1,1);
axisGeom;
camlight headlight;

gdrawnow;

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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 3 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, see <http://www.gnu.org/licenses/>.


function h = hesschek(net, x, t)
%HESSCHEK Use central differences to confirm correct evaluation of Hessian matrix.
%
%	Description
%
%	HESSCHEK(NET, X, T) takes a network data structure NET, together with
%	input and target data matrices X and T, and compares the evaluation
%	of the Hessian matrix using the function NETHESS and using central
%	differences with the function NETERR.
%
%	The optional return value H is the Hessian computed using NETHESS.
%
%	See also
%	NETHESS, NETERR
%

%	Copyright (c) Ian T Nabney (1996-2001)

w0 = netpak(net);
nwts = length(w0);
h = nethess(w0, net, x, t);

w = w0;
hcent = zeros(nwts, nwts);
h1 =  0.0; h2 =  0.0; h3 =  0.0; h4 = 0.0;
epsilon = 1.0e-4;
fprintf(1, 'Checking Hessian ...\n\n');
for k = 1:nwts;
  for l = 1:nwts;
    if(l == k)
      w(k) = w0(k) + 2.0*epsilon;
      h1 = neterr(w, net, x, t);
      w(k) = w0(k) - 2.0*epsilon;
      h2 = neterr(w, net, x, t);
      w(k) = w0(k);
      h3 = neterr(w, net, x, t);
      hcent(k, k) = (h1 + h2 - 2.0*h3)/(4.0*epsilon^2);
    else
      w(k) = w0(k) + epsilon;
      w(l) = w0(l) + epsilon;
      h1 = neterr(w, net, x, t);
      w(k) = w0(k) - epsilon;
      w(l) = w0(l) - epsilon;
      h2 = neterr(w, net, x, t);
      w(k) = w0(k) + epsilon;
      w(l) = w0(l) - epsilon;
      h3 = neterr(w, net, x, t);
      w(k) = w0(k) - epsilon;
      w(l) = w0(l) + epsilon;
      h4 = neterr(w, net, x, t);
      hcent(k, l) = (h1 + h2 - h3 - h4)/(4.0*epsilon^2);
      w(k) = w0(k);
      w(l) = w0(l);
    end
  end
end

fprintf(1, '   analytical    numerical       delta\n\n');
temp = [h(:), hcent(:), (h(:) - hcent(:))];
fprintf(1, '%12.6f  %12.6f  %12.6f\n', temp');


%########################################################################
%
%	- PPGI Toolbox -
%   A MATLAB toolbox for Photoplethysmography Imaging (PPGI)
%
% Author   : Christian S. Pilz
% Company  : The Nature of Space of Time
% Date     : 07.05.2019
%
% Contact  : cpi@partofthestars.com
% Web Page : www.partofthestars.com
%
% Version  : beta0.1
%
%########################################################################
%
%	local_group_invariance.m:
%
% Description:
%
%   Implements the Local Group Invariance algorithm.
%   NOTE: the implementation considers the translation invariance solely.
%
% References:
%
%   Christian S. Pilz, S. Zaunseder, J. Krajewski, V. Blazek,
%   Local Group Invariance for Heart Rate Estimation from Face Videos in the Wild,
%   The IEEE Conference on Computer Vision and Pattern Recognition (CVPR) Workshops,
%   pp.1254-1262, Salt Lake City, 2018
%

classdef local_group_invariance

   properties

   end

   methods

       function obj = local_group_invariance()

       end

       function [pulse, obj] = get(obj,skin_pixels)

           pulse=[];
           frames=size(skin_pixels,2);
           C=[];

           for f=1:frames
               x=skin_pixels{f};
               C(f,:)=[mean(x(:,1)); mean(x(:,2)); mean(x(:,3));];
           end

           [U,E,V]=svd(C');

           S=U(:,1)';
           P=eye(3)-S'*S;%rank 1

           F(1:frames,3)=0;
           for f=1:frames
              F(f,:)=(P*C(f,:)')';
           end

           pulse=double(F(:,2));
       end
   end
end


function [vol,dist] = volume(psi,radius,dist)

if nargin < 3
  N = 60;
  dist = zeros(numel(radius),N);
  for i = 1:length(radius)

    if radius(i) + 5 * psi.halfwidth < pi
      dist(i,1:N-9) = linspace(0,radius(i) + 5 * psi.halfwidth,N-9);
      dist(i,N-9:end) = linspace(radius(i) + 5 * psi.halfwidth,pi,10);
    else
      dist(i,:) = linspace(0,pi,N);
    end

  end

end

% make radius square as well
radius = repmat(radius(:),1,size(dist,2));

% weight function
weight = @(rot_angle,quat_dist,volume_radius) (max(0,min(4*pi,2*pi*(1-(cos(volume_radius/2) - ...
  cos(quat_dist/2) * cos(rot_angle/2))./...
  (sin(quat_dist/2) * sin(rot_angle/2))))) ...
  + max(0,min(4*pi,2*pi*(1-(cos(volume_radius/2) + ...
  cos(quat_dist/2) * cos(rot_angle/2))./...
  (sin(quat_dist/2) * sin(rot_angle/2))))))./pi./4;

% integrant
KV = @(rot_angle,quat_dist,volume_radius) weight(rot_angle,quat_dist,volume_radius) ...
  .* sin(rot_angle ./2).^2 .* psi.eval(cos(rot_angle./2)) ./pi.*2 ;

% perform quadrature
%vol = zeros(size(dist));
%for j = 1:length(dist)
%  vol(j) = quad(@(rot_angle) KV(rot_angle,dist(j),radius),0,min(pi,5*k.hw),1e-6);
%end

%vol = quadv(@(rot_angle) KV(rot_angle,dist,radius),0,min(pi,5*psi.halfwidth),1e-7);
vol = integral(@(rot_angle) KV(rot_angle,dist,radius),0,min(pi,5*psi.halfwidth),'AbsTol',1e-7,'ArrayValued',true);


function [ccf,pst] = spm_csd2ccf(csd,Hz,dt)
% Converts cross spectral density to cross covariance function
% FORMAT [ccf,pst] = spm_csd2ccf(csd,Hz,dt)
%
% csd  (n,:,:)          - cross spectral density (cf, mar.P)
% Hz   (n x 1)          - vector of frequencies (Hz)
% dt                    - samping interval (default = 1/(2*Hz(end)))
%
% ccf                   - cross covariance functions
% pst  (N,1)            - vector of lags for evaluation (seconds)
%
% Note that because this scheme uses FFT one can only change dt.
%
% See also:
%  spm_ccf2csd.m, spm_ccf2mar, spm_csd2ccf.m, spm_csd2mar.m, spm_mar2csd.m,
%  spm_csd2coh.m, spm_Q.m, spm_mar.m and spm_mar_spectral.m
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_csd2ccf.m 6395 2015-03-26 15:05:04Z adeel $

% Nyquist
%--------------------------------------------------------------------------
if nargin < 3, dt  = 1/(2*Hz(end)); end

% unpack cells
%--------------------------------------------------------------------------
if iscell(csd)
    for i = 1:length(csd)
       [ccfi,pst] = spm_csd2ccf(csd{i},Hz,dt);
       ccf{i}     = ccfi;
    end
    return
end

% unpack time bins (for time-frequency responses)
%--------------------------------------------------------------------------
if ndims(csd) == 4
    for i = 1:size(csd,1)
       [ccfi,pst]   = spm_csd2ccf(squeeze(csd(i,:,:,:)),Hz,dt);
       ccf(i,:,:,:) = ccfi;
    end
    return
end

% indices for FFT
%--------------------------------------------------------------------------
dw    = Hz(2) - Hz(1);
Hz    = Hz/dw;
ns    = 1/dt;
N     = ceil(ns/2/dw);
gj    = find(Hz > 0 & Hz < (N + 1));
gi    = gj + ceil(Hz(1)) - 1;
g     = zeros(N,1);

% Fourier transform cross-spectral density
%==========================================================================
for i = 1:size(csd,2)
    if ismatrix(csd)
        g(gi)      = csd(gj,i);
        f          = ifft([0; g; flipud(conj(g))]);
        ccf(:,i)   = real(fftshift(f))*N*dw;
    else
        for j = 1:size(csd,3)
            g(gi)      = csd(gj,i,j);
            f          = ifft([0; g; flipud(conj(g))]);
            ccf(:,i,j) = real(fftshift(f))*N*dw;
        end
    end
end

% Compute time bins
%--------------------------------------------------------------------------
pst = dt*(-N:N);


                    function rot
% ***************************************************************
%                   P r o g r a m   ROT
% ***************************************************************
%
%  PURPOSE:
%     Resolve numerically differential equation of rotational motion
%     of a body
%                      Jz*d2f/dt2 = Mz(t,f,w)
%     and plots graphics of coordinate, velocity and phase plane.
%     If possible, the program could solve the problem analytically.
%
%  INPUT DATA:
%     Jz   - moment of inertia of the body ;
%     Mz   - rotational moment  Mz = Mz(t,f,w);
%     f0   - initial value of the coordinate ;
%     w0   - initial value of the angular velocity ;
%     Tend - upper bound of the integration ;
%     eps  - precision of the integration ;
%     np   - number of parameters .
%     P{1}, P{2}, ..., P{np} - names of the parameters (array of cells);
%
%  NOTES:
%   1. The coordinate is designed by the symbol 'f' and velocity by 'w';
%   2. The physical names of the parameters are assigned to the
%      cells of the array P like this: P{1}='Jz', P{2}='c',...;
%   3. For analytical solution the values of Tend, eps, np and P are not
%      needed.
%   4. The parameters Jz, f0 and w0 have to be entered only as
%      strings, even though they represent numbers!
%   5. All the data can be input from file or in interactive mode.
%
%  EXAMPLE of DATA FILE:
%   % Data File for problem ...
%     Jz   = 'Jz'; ( or Jz = '0.15';)
%     Mz   = '-k*w - c*f'; % k, c - parameters
%     f0   = 'f0'; ( or f0 = '0.33';)
%     w0   = 'w0'; ( or w0 = '7';)
%     Tend = 20;
%     eps  = 1.e-8;
%     np   = 3;
%     P{1} = 'Jz';
%     P{2} = 'k';
%     P{3} = 'c';

% ---------------------------------------------------------
%               DATA INPUT OF THE PROBLEM
% =========================================================

 clear
 disp(' ');
 disp(' How will you input the data ?    ');
 disp('     1. From a data file;         ');
 disp('     2. In interactive mode.      ');
 ans = input(' Number of Your choice : '  );
 flag = 0;
 if ans == 1
    while 1
       disp(' ');
       indat = input(' Input the name of the data file :', 's');
       if exist([cd,'\',indat]) % Search only in current directory
          eval(indat);
          flag = 1; break  % Successful
        else               % Unsuccessful
          disp(' ');
          disp([' File ',indat,' not exist!'])
          disp(' You have to:')
          disp(' 1. Enter another DATA file name, or')
          disp(' 2. Input the DATA interactively !')
          ans2 = input(' Your choice, please: ');
          if ans2 == 2, break , end
       end
    end
 end
if flag == 0
    %Input of the data in-line mode
    disp(' ');
    Jz   = input(' Moment of inertia of the body Jz : ','s'      );
    Mz   = input(' Expression of the rotational moment Mz : ','s');
    f0   = input(' Initial coordinate f0 : '                     );
    w0   = input(' Initial velocity w0 : '                       );
    Tend = input(' Upper bound of the integration Tend : '       );
    eps  = input(' Precision of the calculations eps : '         );
    np   = input(' Number of parameters  np : '                  );
    % Asigning names of the parameters
    if np > 0
       disp(' ');
       disp(' Enter names of the parameters:')
       for i = 1:np
           ii = num2str(i);
           P{i} = input([' Name of parameter P',ii,': '],'s');
       end
    end
 end

% ---------------------------------------------------------
%            Differential Equation of Motion
% =========================================================

                 syms f w D2f
                 Mz = subs(Mz, 'w', 'Df');
                 deq = Jz*D2f - Mz;

% ---------------------------------------------------------
%                  ANALYTICAL SOLUTION
% =========================================================

 disp(' ');
 ans = input(' Would you like analytical solution? (Y/N): ','s');
 if ans =='Y' | ans == 'y'
    if ~isstr(f0), f0 = num2str(f0); end % Repairing user
    if ~isstr(w0), w0 = num2str(w0); end % input errors!
    syms f
    inicond = ['f(0)=',f0,',Df(0)=',w0];
    f = dsolve(char(deq), inicond, 't');
    if ~isempty(f)
        disp(' ');
        disp('   Low of Motion   ');
        disp(' ***************** ');
        disp(' ');
        disp('f = '); pretty(f)
        disp(' ');
        fname = input(' Name of file to write solution: ','s');
        save(fname, 'f');
    end
       disp(' ');
       ans = input(' Would you like numerical solution? (Y/N): ','s');
       if ans == 'N' | ans == 'n', return, end
       f = 'f'; % Clear contents of f
 end

% ---------------------------------------------------------
%                  NUMERICAL SOLUTION
% =========================================================

% Input the name of the file-function
disp(' ');
fname = input(' Name of the File-function to be generated: ','s');
flag1 = 'Y';
if exist([cd,'\',fname]) % Search only in current directory!
    disp(' ');
    disp([' A file-function with name ',fname,' already exist !'])
    flag1 = input(' Overwrite it ? (Y/N): ', 's');
end

% ---------------------------------------------------------
%              GENERATING THE FILE-FUNCTION
% ---------------------------------------------------------

if ( flag1 == 'Y' | flag1 == 'y' )
   Mz = subs(Mz,{'f','Df'},{'y(1)','y(2)'});
% Opening the file for writing file-function
   [Fid,mes] = fopen([fname,'.m'],'wt');
% Generating the string with physical parameters: Jz, c ...
   strpar = '';
   for j = 1:np
      strpar = [strpar,',',P{j}];
   end
   titl = input(' Denomination of the Problem: ','s');
%       Writing the headline of the File-function
   fprintf(Fid,['function yt = ',fname,'(t,y',strpar,')\n']);
   fprintf(Fid,['%% ',titl]);
%       Writing the first derivatives
   fprintf(Fid,'\n%% The first derivatives\n');
   fprintf(Fid, '  yt(1) = y(2); \n');
   fprintf(Fid,['  yt(2) = ',char(Mz/Jz),'; \n']);
   fprintf(Fid,'  yt = yt'';\n');
   fprintf(Fid,['%% *** End of File-function ',fname,' ***']);
   fclose(Fid);
   edit(fname)
end

% ---------------------------------------------------------
%        INTEGRATION AND VISUALIZATION OF THE REZULTS
% ---------------------------------------------------------

flag2 = 0;
% Initial entering values of the parameters and generating
% the string with parameters 'P{1}, P{2}, ..., P{np}' to be
% passed to the File-function as actual arguments
if np > 0
   PP = P; % Saving the physical names of the parameters in PP
   parameters = ' ';
   disp(' ');
   disp(' Input the numerical values of the parameters: ')
   for i = 1:np
       i = num2str(i);
       eval(['P{',i,'}=input([''   '',P{',i,'},'' = '']);']);
       parameters = [parameters,',P{',i,'}'];
   end
else
    parameters = [];
end
% Check-up type of f0 and w0 and correct
% it if needed
if ischar(f0)
    f0 = str2num(f0);
    if isempty(f0), f0 = input(' f0 = '); end
end
if ischar(w0)
    w0 = str2num(w0);
    if isempty(w0), w0 = input(' w0 = '); end
end
while 1
    if flag2 == 1
        disp(' ');
        eps  = input(' Precision of the computations eps: ');
        Tend = input(' Upper bound of the integration Tend: ');
        f0   = input(' Initial coordinate f0: ');
        w0   = input(' Initial velocity w0: ');
        if np > 0
          P = PP; % Restoring the names of the parameters !
          disp(' ');
          disp(' Input the numerical values of the parameters: ')
          for i = 1:np
              i = num2str(i);
              eval(['P{',i,'}=input([''   '',P{',i,'},'' = '']);']);
          end
        end
    end
    y0 = [f0 w0]; % initial conditions
    options = odeset('AbsTol',eps,'RelTol',100*eps);
    % Choosing of the Solver
    disp('                                        ');
    disp('      Choose the proper Solver:         ');
    disp('  -------------------------------       ');
    disp(' A. Non stiff differential equations    ');
    disp('   1. ode45   - middle precision;       ');
    disp('   2. ode23   - low precision;          ');
    disp('   3. ode113  - from low to upper.      ');
    disp('                                        ');
    disp(' B. Stiff differential equations        ');
    disp('   1. ode15s  - from low to upper;      ');
    disp('   2. ode23s  - low precision;          ');
    disp('   3. ode23t  - middle precision;       ');
    disp('   4. ode23tb - low precision.          ');
    disp('                                        ');
    solver = input(' The name of the Solver: ','s');

    % Integration of the Differential Equations

    eval(['[t,y] = feval(solver,eval([''@'',fname]),',...
                  '[0 Tend],y0,options',parameters,');']);
    % Plotting graphs

    tmin  = min(t);
    tmax  = max(t);
    y1min = min(y(:,1));
    y1max = max(y(:,1));
    y2min = min(y(:,2));
    y2max = max(y(:,2));
    dy1   = y1max - y1min;
    dy2   = y2max - y2min;
    xmin  = y1min - 0.1*dy1;
    xmax  = y1max + 0.1*dy1;
    ymin  = y2min - 0.1*dy2;
    ymax  = y2max + 0.1*dy2;
    % Coordinate f = f(t)
    figure % 1
    comet(t,y(:,1))
    plot(t,y(:,1),[tmin tmax],[0 0],'k'), grid on
    axis([tmin, tmax, xmin, xmax]);
    set(gca,'FontName','Arial Cyr','FontSize',12);
    title('Low of motion {\phi} = {\phi}({\itt})')
    xlabel('{\itt}'); ylabel('{\phi}'); pause
    % Angular velocity w = w(t)
    figure % 2
    comet(t,y(:,2))
    plot(t,y(:,2),[tmin tmax],[0 0],'k'), grid on
    axis([tmin, tmax, ymin, ymax]);
    set(gca,'FontName','Arial','FontSize',12);
    title('Angular velocity {\omega} = {\omega}({\itt})')
    xlabel('{\itt}'); ylabel('{\omega}'); pause
    % Coordinate and Velocity
    figure % 3
    subplot(2,1,1), plot(t,y(:,1),[tmin tmax],[0 0],'k')
    grid on, axis([tmin, tmax, xmin, xmax]);
    set(gca,'FontName','Arial','FontSize',12);
    title('Low of motion {\phi} = {\phi}(t)')
    subplot(2,1,2), plot(t,y(:,2),[tmin tmax],[0 0],'k')
    grid on, axis([tmin, tmax, ymin, ymax]);
    set(gca,'FontName','Arial','FontSize',12);
    title('Angular velocity {\omega} = {\omega}(t)')
    pause
    % Phase Plane
    figure % 4
    subplot(1,1,1)
    comet(y(:,1),y(:,2))
    plot(y(:,1),y(:,2), [xmin,xmax],[0 0],'k',...
                  [0 0],[ymin,ymax],'k'), grid on
    axis([xmin, xmax, ymin, ymax]);
    set(gca,'FontName','Arial Cyr','FontSize',12);
    title(' Phase Plane {\omega} = {\omega}({\phi})')
    xlabel('{\phi}'), ylabel('{\omega}'), pause
    flag2 = 1;
    % close all
    disp(' ');
    ans = input(' Would you like to continue? (Y/N): ','s');
    if ans == 'n' | ans == 'N', break, end
end

%  ***************** End of Program ROT ********************


function r8vec_convolution_circ_test ( )

%*****************************************************************************80
%
%% R8VEC_CONVOLUTION_CIRC_TEST tests R8VEC_CONVOLUTION_CIRC
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  n = 4;

  x = [ 1.0, 2.0, 3.0, 4.0 ];
  y = [ 1.0, 2.0, 4.0, 8.0 ];
  z_correct = [ 37.0, 44.0, 43.0, 26.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8VEC_CONVOLUTION_CIRC_TEST\n' );
  fprintf ( 1, '  R8VEC_CONVOLUTION_CIRC computes the circular convolution\n' );
  fprintf ( 1, '  of two vectors.\n' );

  r8vec_print ( n, x, '  The factor X:' );
  r8vec_print ( n, y, '  The factor Y:' );

  z = r8vec_convolution_circ ( n, x, y );

  r8vec_print ( n, z, '  The circular convolution z = xCCy:' );

  r8vec_print ( n, z_correct, '  Correct answer:' );

  return
end


function [A B X E] = slr_iteration(D, labels, lambda, tau, eta, delta, epsilon, maxIter, maxOut)

% Dec 2014
%
% by Jian Lai, jlai1@ntu.edu.sg
% solve the equation (17) the supervised low rand decomposition in our PAMI paper
% min ||A||_* + \lambda ||B||_* + \tau ||X||_F^2 + \eta ||E||_1 s.t. D = A + BX + E.

% input
% D: training data, each column is a atom, with the size m*n
% labels: the training labels of D, with the size n*1
% lambda, tau and eta: the balancing parameters in equation (17)
% delta: the balancing parameter of T in equation (20) and (23)
% epsilon: the tolerance of the convergent checking
% maxIter: max iteration within each subproblem
% maxOut: max iteration of outer loop (defaul value is 4)

% output
% A: the class-specific dictionary
% B: the nonclass-specific dictionary
% X: the coefficient matrix of B
% E: the error matrix

% input checking
if nargin < 6
    error('Too few arguments') ;
end

if nargin < 7
    epsilon = 1e-4;
end

if nargin < 8
    maxIter = 1000;
end

if nargin < 9
    maxIter = 4;
end

% initializate A_i as (19) in our PAMI paper
unilabel = unique(labels);
numlabel = size(unilabel,2);
for classindex = 1:numlabel
    classid = unilabel(classindex);
    Di = D(:,classid==labels);
    [U S V] = svd(Di, 'econ');
	Ai{classindex} = U(:, 1) * diag(S(1,1)) * V(:, 1)';
end

% initialize of A
A = [];
for classindex = 1:numlabel
    A = [A Ai{classindex}];
end

% initialize X to an identity matrix
X = eye(size(A,2));

% initialize B to a zero matrix
B = zeros(size(D));

for outiter = 1:maxOut

    fprintf('The %d iteration of SLR\n', outiter);

    % solve the subproblem (20) in our PAMI paper
    [B, T] = slr_BT_ialm(D, A, X, lambda, delta, epsilon, maxIter);

    % solve the subproblem (23) in our PAMI paper
    [X, T] = slr_XT_ialm(D, A, B, tau, delta, epsilon, maxIter);

    % solve the subproblem (25) in our PAMI paper
    [A, E] = slr_AE_ialm(D, B, X, eta, epsilon, maxIter);

end


function  [CQcc, LogP_absCQT, TimeVec, FreqVec, Ures_LogP_absCQT, Ures_FreqVec] = ...
    cqcc(x, fs, B, fmax, fmin, d, cf, ZsdD)

%   Constant Q cepstral coefficients
%   Usage:  CQcc = cqcc(x, fs, B, fmax, fmin, d, cf, ZsdD)
%
%   Input parameters:
%         x        : input signal
%         fs       : sampling frequency
%         B        : number of bins per octave [default = 96]
%         fmax     : highest frequency to be analyzed [default = Nyquist frequency]
%         fmin     : lowest frequency to be analyzed [default = ~20Hz to fullfill an integer number of octave]
%         d        : number of uniform samples in the first octave [default 16]
%         cf       : number of cepstral coefficients excluding 0'th coefficient [default 19]
%         ZsdD     : any sensible combination of the following  [default ZsdD]:
%                      'Z'  include 0'th order cepstral coefficient
%                      's'  include static coefficients (c)
%                      'd'  include delta coefficients (dc/dt)
%                      'D'  include delta-delta coefficients (d^2c/dt^2)
%
%   Output parameters:
%         CQcc              : constant Q cepstral coefficients (nCoeff x nFea)
%         LogP_absCQT       : log power magnitude spectrum of constant Q trasform
%         TimeVec           : time at the centre of each frame [sec]
%         FreqVec           : center frequencies of analysis filters [Hz]
%         Ures_LogP_absCQT  : uniform resampling of LogP_absCQT
%         Ures_FreqVec      : uniform resampling of FreqVec [Hz]
%
%   See also:  cqt
%
%
%   References:
%     M. Todisco, H. Delgado, and N. Evans. A New Feature for Automatic
%     Speaker Verification Anti-Spoofing: Constant Q Cepstral Coefficients.
%     Proceedings of ODYSSEY - The Speaker and Language Recognition
%     Workshop, 2016.
%
%     C. Sch�rkhuber, A. Klapuri, N. Holighaus, and M. D�fler. A Matlab
%     Toolbox for Efficient Perfect Reconstruction log-f Time-Frequecy
%     Transforms. Proceedings AES 53rd Conference on Semantic Audio, London,
%     UK, Jan. 2014. http://www.cs.tut.fi/sgn/arg/CQT/
%
%     G. A. Velasco, N. Holighaus, M. D�fler, and T. Grill. Constructing an
%     invertible constant-Q transform with non-stationary Gabor frames.
%     Proceedings of DAFX11, Paris, 2011.
%
%     N. Holighaus, M. D�fler, G. Velasco, and T. Grill. A framework for
%     invertible, real-time constant-q transforms. Audio, Speech, and
%     Language Processing, IEEE Transactions on, 21(4):775-785, April 2013.
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (C) 2016 EURECOM, France.
%
% This work is licensed under the Creative Commons
% Attribution-NonCommercial-ShareAlike 4.0 International
% License. To view a copy of this license, visit
% http://creativecommons.org/licenses/by-nc-sa/4.0/
% or send a letter to
% Creative Commons, 444 Castro Street, Suite 900,
% Mountain View, California, 94041, USA.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Authors: Massimiliano Todisco {todisco [at] eurecom [dot] fr}
%          Hector Delgado {delgado [at] eurecom [dot] fr}
%
% Version: 1.0
% Date: 22.01.16
%
% User are requested to cite the following paper in papers which report
% results obtained with this software package.
%
%     M. Todisco, H. Delgado, and N. Evans. A New Feature for Automatic
%     Speaker Verification Anti-Spoofing: Constant Q Cepstral Coefficients.
%     Proceedings of ODYSSEY - The Speaker and Language Recognition
%     Workshop, 2016.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% CHECK INPUT PARAMETERS
if nargin < 2
    warning('Not enough input arguments.'), return
end

%%% DEFAULT INPUT PARAMETERS
if nargin < 3; B = 96; end
if nargin < 4; fmax = fs/2; end
if nargin < 5; oct = ceil(log2(fmax/20)); fmin = fmax/2^oct; end
if nargin < 6; d = 16; end
if nargin < 7; cf = 19; end
if nargin < 8; ZsdD = 'ZsdD'; end
gamma = 228.7*(2^(1/B)-2^(-1/B));

%%% CQT COMPUTING
Xcq = cqt(x, B, fs, fmin, fmax, 'rasterize', 'full', 'gamma', gamma);

%%% LOG POWER SPECTRUM
absCQT = abs(Xcq.c);
TimeVec = (1:size(absCQT,2))*Xcq.xlen/size(absCQT,2)/fs;
FreqVec = fmin*(2.^((0:size(absCQT,1)-1)/B));
LogP_absCQT = log(absCQT.^2 + eps);

%%% UNIFORM RESAMPLING
kl = (B*log2(1+1/d));
[Ures_LogP_absCQT, Ures_FreqVec] = resample(LogP_absCQT,...
    FreqVec,1/(fmin*(2^(kl/B)-1)),1,1,'spline');

%%% DCT
CQcepstrum = dct(Ures_LogP_absCQT);

%%% DYNAMIC COEFFICIENTS
if strfind(ZsdD, 'Z'); scoeff = 1; else scoeff = 2; end
CQcepstrum_temp = CQcepstrum(scoeff:cf+1,:);
f_d = 3; % delta window size
if strcmp(strrep(ZsdD,'Z',''), 'sdD')
    CQcc = [CQcepstrum_temp; Deltas(CQcepstrum_temp,f_d); ...
        Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];
elseif strcmp(strrep(ZsdD,'Z',''), 'sd')
    CQcc = [CQcepstrum_temp; Deltas(CQcepstrum_temp,f_d)];
elseif strcmp(strrep(ZsdD,'Z',''), 'sD')
    CQcc = [CQcepstrum_temp; Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];
elseif strcmp(strrep(ZsdD,'Z',''), 's')
    CQcc = CQcepstrum_temp;
elseif strcmp(strrep(ZsdD,'Z',''), 'd')
    CQcc = Deltas(CQcepstrum_temp,f_d);
elseif strcmp(strrep(ZsdD,'Z',''), 'D')
    CQcc = Deltas(Deltas(CQcepstrum_temp,f_d),f_d);
elseif strcmp(strrep(ZsdD,'Z',''), 'dD')
    CQcc = [Deltas(CQcepstrum_temp,f_d); Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];
end
end

function D = Deltas(x,hlen)

% Delta and acceleration coefficients
%
% Reference:
%   Young S.J., Evermann G., Gales M.J.F., Kershaw D., Liu X., Moore G., Odell J., Ollason D.,
%   Povey D., Valtchev V. and Woodland P., The HTK Book (for HTK Version 3.4) December 2006.

win = hlen:-1:-hlen;
xx = [repmat(x(:,1),1,hlen),x,repmat(x(:,end),1,hlen)];
D = filter(win, 1, xx, [], 2);
% D = D(:,hlen+1:(end - hlen));
D = D(:,hlen*2+1:end);
D = D./(2*sum((1:hlen).^2));
end


classdef SOP_F19 < PROBLEM
% <single> <real> <expensive/none>
% Hartman's family

%------------------------------- Reference --------------------------------
% X. Yao, Y. Liu, and G. Lin, Evolutionary programming made faster, IEEE
% Transactions on Evolutionary Computation, 1999, 3(2): 82-102.
%------------------------------- 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".
%--------------------------------------------------------------------------

    methods
        %% Default settings of the problem
        function Setting(obj)
            obj.M = 1;
            obj.D = 3;
            obj.lower    = zeros(1,obj.D);
            obj.upper    = ones(1,obj.D);
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            a = [3 10 30;0.1 10 35;3 10 30;0.1 10 35];
            c = [1;1.2;3;3.2];
            p = [0.3689 0.1170 0.2673;0.4699 0.4387 0.7470;0.1091 0.8732 0.5547;0.03815 0.5743 0.8828];
            PopObj = zeros(size(PopDec,1),1);
            for i = 1 : size(PopDec,1)
                PopObj(i) = -sum(c.*exp(-sum(a.*(repmat(PopDec(i,:),4,1)-p).^2,2)));
            end
        end
        %% Generate the minimum objective value
        function R = GetOptimum(obj,N)
            R = -3.863;
        end
    end
end


function[S] = adaptMedian_colfilt(I, w_max)
%
%

if nargin < 2
  w_max = 9;
end

[Nrows Ncols depth] = size(I);
S = uint8(zeros(Nrows, Ncols, depth));

for d = 1:depth,

% Get plane d
Ib = I(:,:,d);

% Initialization
w = 1;
p = 3;
cond = uint8(1);    % zero --> noiseless pixel

for l = w+2:2:w_max

  Imed = medfilt2(Ib, [p p]);
  Imin = colfilt(Ib, [p p], 'sliding', @(x) min(x));
  Imax = colfilt(Ib, [p p], 'sliding', @(x) max(x));

  m1 = uint8( ((Imin < Imed) .* (Imed < Imax)) );
  m2 = uint8( ((Imin < Ib) .* (Ib < Imax)) );

  if(l == w)
    S(:,:,d) =  m1.*(1-m2).*l;
  else
    S(:,:,d) = cond.*( m1.*(1-m2).*l ) + (1-cond).*S(:,:,d);
  end

  cond = cond.*(1-m1); % pixel that need further evaluation

  p = p+2;

end % _END_ FOR(l)

S(:,:,d) = cond.*(w_max+2) + (1-cond).*S(:,:,d);

end % _END_ FOR(d)

S = double(S);


%% Analyzing Investment Strategies with CVaR Portfolio Optimization in MATLAB
%
% Robert Taylor
% The MathWorks, Inc.

% Copyright (C) 2012 The MathWorks, Inc.

%% Introduction

% This script is a "superscript" that organizes the scripts for the webinar "Analyzing Investment
% Strategies with CVaR Portfolio Optimization in MATLAB." It describes what each script does and
% shows the order in which the scripts should be examined.

%% Instructions

% The file structure for these scripts has a top-level folder that contains these scripts and should
% have two folders 'data' and 'source' with data and analytics. To add these folders to the path,
% start in the folder with the scripts and execute the commands

setlocalpaths

% The script cvarwebinar_scenarios.m, which simulates scenarios, must be run before subsequent
% scripts can be run because it generates a file BuyWriteScenarios.mat that is needed for these
% scripts. The script to generate scenarios can take about one hour on a typical computer and
% requires that the computer be a 64-bit machine. It creates a 12MB file in the ./data folder. Make
% sure that the script to generate scenarios is run in the folder that contains this script so that
% the scenarios file ends up in the correct data folder.

%% Theory

% This script illustrates basic features of covered-call strategies and provides a theoretical
% analysis of issues regarding slippage due to assignment and re-investment.

cvarwebinar_theory

%% From Theory to Reality

% This script illustrates an event-driven simulation of total returns for uncovered and covered
% positions based on a single realization of an underlying stock. It moves from the simplicity of
% theory to the messiness of reality as it models and simulates various contributions to slippage.

cvarwebinar_reality

%% Calibration

% This script is the first of the sequence of scripts to illustrate a complete workflow to analyze a
% covered-call strategy for a universe of 26 stocks. Given total return price data, this script
% illustrates maximum likelihood calibration of the assumed geometric Brownian motion process for
% the universe of stocks.

cvarwebinar_calibration

%% Scenario Generation

% This script is the second of the sequence of scripts that generates scenarios for uncovered and
% covered positions to be used for subsequent portfolio optimization and analysis. This is the
% slowest script since it generates scenarios by simulation of investment actions during the course
% of an investment period.

cvarwebinar_scenarios

%% Normality Tests

% This script is the third of the sequence of scripts that examines the statistical properties of
% the scenarios. As the probability of early exercise increases during an investment period, the
% distribution of the log of covered-call returns becomes increasingly non-normal.

cvarwebinar_normality

%% Optimization

% This script is the final of the sequence of scripts that performs several portfolio optimization
% steps with both CVaR and mean-variance portfolio optimization. The difference in results between
% the two types of optimization is examined to provide greater insights into the normative
% implications of covered-call strategies.

cvarwebinar_optimization

%% References
%
% # P. Bernstein (1998), _Against the Gods: The Remarkable Story of Risk_, Wiley.
% # F. Black (1975), "Fact and Fantasy in the Use of Options," _Financial Analysts Journal_, Vol. 31,
% No. 4, pp. 36-41 and 61-72.
% # P. Glassermann (1991), _Monte Carlo Methods in Financial Engineering_, Springer.
% # I. Karatzas and S. Shreve (1991), _Brownian Motion and Stochastic Calculus_, 2nd ed., Springer.
% # H. Markowitz (1952), "Portfolio Selection," _Journal of Finance_, Vol. 7, No. 1, pp. 77-91.
% # R. Merton, M. Scholes, and M. Gladstein (1978), "The Returns and Risk of Alternative Call Option
% Portfolio Investment Strategies," _Journal of Business_, Vol. 51, No. 2, pp. 183-242.
% # R. T. Rockafellar and S. Uryasev (2002). "Conditional Value-at-Risk for General Loss
% Distributions," _Journal of Banking and Finance_, Vol. 26, pp. 1443-1471.


function G =  getGroupNonOverlapColor(row, col)

   % N = (row-2)*(col-2);
 N =  row * col ;
    g = sparse(zeros(N,1));
    g = diag(g);
    groupCount = 0;

    %% build non-overlapping group
    for i=2:3:col-1
        for j=2:3:row-1
            groupCount = groupCount+1;

            g(groupCount, (i-2)*row+j-1 ) = 1;
            g(groupCount, (i-2)*row+j   ) = 1;
            g(groupCount, (i-2)*row+j+1 ) = 1;
            g(groupCount, (i-1)*row+j-1 ) = 1;
            g(groupCount, (i-1)*row+j   ) = 1;
            g(groupCount, (i-1)*row+j+1 ) = 1;
            g(groupCount, i*row+j-1 ) = 1;
            g(groupCount, i*row+j   ) = 1;
            g(groupCount, i*row+j+1 ) = 1;

        end
    end

    g= g';

    g =g(:, 1:groupCount);

    G = sparse(3*N, 3*groupCount);

    G(1:N, 1:groupCount) = g;
    G(N+1:2*N, groupCount+1:2*groupCount) =g;
    G(2*N+1:3*N, 2*groupCount+1:3*groupCount) =g;

end


function [LE,J]=CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots)
% Substrate: Parallel, impermeable cylinders with one radius in an empty
%            background.
% Pulse sequence: Pulsed gradient spin echo
% Signal approximation: Gaussian phase distribution.
%
% [LE,J] = CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots)
%
% returns the log signal attenuation in perpendicular direction (LePerp) for
% EACH RADIUS specified in R according to the Neuman model and the Jacobian J
% of LePerp with respect to the parameters.
%
% The Jacobian DOES NOT include derivates with respect to the fibre direction.
%
% d is the diffusivity of the material inside the cylinders.
%
% R is the list of the radii of the cylinders. It has size [1 m] where m is the
% number of radii.
%
% G, delta and smalldel are the gradient strength, pulse separation and
% pulse length of each measurement in the protocol.  Each has
% size [N 1].
%
% roots contains solutions to the Bessel function equation from function
% BesselJ_RootsCyl.
%
% author: Daniel C Alexander (d.alexander@ucl.ac.uk)
%         Gary Hui Zhang     (gary.zhang@ucl.ac.uk)
%

% When R=0, no need to do any calculation
if (R == 0.00)
    LE = zeros(size(G,1), size(R,2));
    J = zeros([size(LE), 2]);
	 J(:,:,:) = 0;
    return;
end

% Check the roots array is correct
if(abs(roots(1) - 1.8412)>0.0001)
    error('Looks like the roots array is wrong.  First value should be 1.8412, but is %f', roots(1));
end

% Radial wavenumbers
GAMMA = 2.675987E8;

% number of gradient directions, i.e. number of measurements
l_q=size(G,1);
l_a=numel(R);
k_max=numel(roots);

R_mat=repmat(R,[l_q 1]);
R_mat=R_mat(:);
R_mat=repmat(R_mat,[1 1 k_max]);
R_matSq=R_mat.^2;

root_m=reshape(roots,[1 1 k_max]);
alpha_mat=repmat(root_m,[l_q*l_a 1 1])./R_mat;
amSq=alpha_mat.^2;
amP6=amSq.^3;

deltamx=repmat(delta,[1,l_a]);
deltamx_rep = deltamx(:);
deltamx_rep = repmat(deltamx_rep,[1 1 k_max]);

smalldelmx=repmat(smalldel,[1,l_a]);
smalldelmx_rep = smalldelmx(:);
smalldelmx_rep = repmat(smalldelmx_rep,[1 1 k_max]);

Gmx=repmat(G,[1,l_a]);
GmxSq = Gmx.^2;

% Perpendicular component (Neuman model)
sda2 = smalldelmx_rep.*amSq;
bda2 = deltamx_rep.*amSq;
emdsda2 = exp(-d*sda2);
emdbda2 = exp(-d*bda2);
emdbdmsda2 = exp(-d*(bda2 - sda2));
emdbdpsda2 = exp(-d*(bda2 + sda2));

sumnum1 = 2*d*sda2;
% the rest can be reused in dE/dR
sumnum2 = - 2 + 2*emdsda2 + 2*emdbda2;
sumnum2 = sumnum2 - emdbdmsda2 - emdbdpsda2;
sumnum = sumnum1 + sumnum2;

sumdenom = d^2*amP6.*(R_matSq.*amSq - 1);

% Check for zeros on top and bottom
%sumdenom(find(sumnum) == 0) = 1;
sumterms = sumnum./sumdenom;

testinds = find(sumterms(:,:,end)>0);
test = sumterms(testinds,1)./sumterms(testinds,end);
if(min(test)<1E4)
    warning('Ratio of largest to smallest terms in Neuman model sum is <1E4.  May need more terms.');
end

s = sum(sumterms,3);
s = reshape(s,[l_q,l_a]);
if(min(s)<0)
    warning('Negative sums found in Neuman sum.  Setting to zero.');
    s(find(s<0))=0;
end

LE = -2*GAMMA^2*GmxSq.*s;

% Compute the Jacobian matrix
if(nargout>1)

    % dLE/dd
    sumnumD = 2*sda2;
    sumnumD = sumnumD - 2*sda2.*emdsda2;
    sumnumD = sumnumD - 2*bda2.*emdbda2;
    sumnumD = sumnumD + (bda2 - sda2).*emdbdmsda2;
    sumnumD = sumnumD + (bda2 + sda2).*emdbdpsda2;
    sumtermsD = sumnumD./sumdenom;

    sD = sum(sumtermsD,3);
    sD = reshape(sD,[l_q,l_a]);

    dLEdd = -2*GAMMA^2*GmxSq.*(sD - 2*s/d);

    % dLE/dR
    sumtermsR = (6*sumterms - 2*d*sumtermsD)./R_mat;

    sR = sum(sumtermsR,3);
    sR = reshape(sR,[l_q,l_a]);

    dLEdr = -2*GAMMA^2*GmxSq.*sR;

    % Construct the jacobian matrix.
    J = zeros([size(LE), 2]);
    J(:,:,1) = dLEdd;
    J(:,:,2) = dLEdr;
end


function lp = wishpdfln(X,a,B,inverse)
%WISHPDFLN    Logarithm of Wishart probability density function.
%  See WISHPDF for argument description.

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

if nargin < 3
  B = [];
end
if nargin < 4
  inverse = 0;
end

if inverse
  X = inv(X);
end
if isempty(B)
  XB = X;
  logDetB = 0;
else
  XB = X*B;
  logDetB = logdet(B);
end
d = rows(X);
d2 = (d+1)/2;
if inverse
  d2 = -d2;
end
logDetXB = (a-d2)*logdet(XB);
lp = logDetXB - trace(XB) + d2*logDetB - gammaln(a,d);


function pred = knnpred2(Xtest,X,class,class_exp,K,dist_type,pret_type)

% prediction of new samples with calculated model
%
% pred = knnpred(Xtest,X,class,K,dist_type,pret_type)
%
% ------------ INPUT ---------------------------------------------------
% Xtest:        dataset to be predicted [n_test x p] n objects, p variables
% X:            training data matrix (n x p)
% class:        training class vector (n x 1)
% K:            number of neighbors
% dist_type:    'euclidean' Euclidean distance
%               'mahalanobis' Mahalanobis distance
%               'cityblock' City Block metric
%               'minkowski' Minkowski metric
%               'sm' Sokal-Michener
%               'jt' Jaccard Tanimoto
%               'gle' Gleason-Dice
%               'ct4' Consonni-Todeschini
%               'ac' Austin-Colwell
% pret_type:    'cent' cenering
%               'scal' variance scaling
%               'auto' for autoscaling (centering + variance scaling)
%               'rang' range scaling (0-1)
%               'fp'   fingerprints
%
% ------------ OUTPUT --------------------------------------------------
% pred is a structure conyaining
% class_pred    predicted class vector [n_test x 1]
% neighbors     list of k neighbors for each predicted sample [n_test x k]
%
% version 1.0 - september 2009
% Davide Ballabio
% Milano Chemometrics and QSAR Research Group
% www.disat.unimib.it/chm

% version 2.0 - February 2012
% Kamel Mansouri
% Milano Chemometrics and QSAR Research Group
% www.disat.unimib.it/chm

% data check
if length(class)~=size(X,1)
    disp('the class input should be for the training set')
    %class_tr=input('class tr');
    %class=evalin(WS,);
    %keyboard
end

[n,p] = size(Xtest);
[X_scal_train,param] = data_pretreatment(X,pret_type);
X_scal = test_pretreatment(Xtest,param);
Xd = [X_scal;X_scal_train];
% D = pdist(Xd,model.set.dist_type);
% D = squareform(D);
D = knn_calc_dist(X_scal_train,X_scal,dist_type,pret_type);
neighbors = zeros(n,K);
w=zeros(n,K);
class_exp(find(isnan(class_exp)))=class(find(isnan(class_exp)));
for i=1:n
    D_in = D(i,:);
    [d_tmp,n_tmp] = sort(D_in);
    neighbors(i,:) = n_tmp(1:K);
    d_neighbors = d_tmp(1:K);
    if d_neighbors(1)<1e-5 %&& d_neighbors(2)>d_neighbors(1)
        d_neighbors(1)=0;
    end
    if d_neighbors(1)==0 %&& isnan(class_exp(neighbors(i,1)))%&& d_neighbors(2)~=0
        class_calc(i) = knnclass2(class(neighbors(i,:)),d_neighbors,max(class),K);
        class_calc_weighted(i)=class(neighbors(i,1));
        w(i,1)=1;
    else
        %class(find(~isnan(class_exp)))=class_exp(find(~isnan(class_exp)));
        class_calc(i) = knnclass2(class_exp(neighbors(i,:)),d_neighbors,max(class_exp),K);
        [yc(i),class_calc_weighted(i),w(i,:)] = nnrcalcy2(class_exp(neighbors(i,:)),d_neighbors,K);
        class_calc_weighted(i)=round(class_calc_weighted(i));
    end

    dc(i,:)=d_neighbors;
end

pred.neighbors  = neighbors;
pred.class_pred = class_calc';
pred.class_pred_w = class_calc_weighted';
pred.w=w;
pred.D=D;
pred.dc=dc;


function A = hmf(A,n)

%HMF Hybrid median filtering.
%   B = HMF(A,N) performs hybrid median filtering of the matrix A using a
%   NxN box. Hybrid median filtering preserves edges better than a NxN
%   square kernel-based median filter because data from different spatial
%   directions are ranked separately. Three median values are calculated in
%   the NxN box: MR is the median of horizontal and vertical R pixels, and
%   MD is the median of diagonal D pixels. The filtered value is the median
%   of the two median values and the central pixel C: median([MR,MD,C]).
%   For N = 5:
%        |D  *  R  *  D|
%        |*  D  R  D  *|
%        |R  R  C  R  R|
%        |*  D  R  D  *|
%        |D  *  R  *  D|
%
%   B = HMF(A) uses N = 5 (default value).
%
%   A can be a 2-D array or an RGB image. If A is an RGB image, hybrid
%   median filtering is performed in the HSV color space.
%
%   Notes
%   -----
%   1) N must be odd. If N is even then N is incremented by 1.
%   2) The Image Processing Toolbox is required.
%   3) If the function NANMEDIAN exists (Statistics Toolbox), NaN are
%      treated as missing values and are ignored.
%
%   Examples
%   --------
%     % -- original grayscale image --
%     I = imread('eight.tif');
%     % noisy image
%     J = imnoise(I,'salt & pepper',0.03);
%     % hybrid median filtering
%     K = hmf(J);
%     % figures
%     subplot(121),imshow(J),subplot(122),imshow(K)
%
%     % -- original RGB image --
%     [I,map] = imread('trees.tif');
%     I = ind2rgb(I,map);
%     % noisy image
%     J = imnoise(I,'salt & pepper',0.02);
%     % hybrid median filtering (using a 9x9 box)
%     K = hmf(J,9);
%     % figures
%     subplot(121),imshow(J),subplot(122),imshow(K)
%
%   See also MEDFILT2, MEDFILT2RGB, MEDFILT3, COLFILT
%
%   -- Damien Garcia -- 2007/08, revised 2010/02

error(nargchk(1,2,nargin));
if nargin==1, n = 5; end

if ~isscalar(n) || n<0, n = 5; end

% --- n must be odd. If not then n = n+1
n = round(n);
if rem(n+1,2)~=0, n = n+1; end

% --- Do we have an RGB image?
% RGB images can be only be uint8, uint16, single, or double
isRGB = ndims(A)==3 && (isfloat(A) || isa(A,'uint8') || isa(A,'uint16'));
% ---- Adapted from the obsolete function ISRGB ----
if isRGB
   if isfloat(A)
      % At first just test a small chunk to get a possible quick negative
      mm = size(A,1);
      nn = size(A,2);
      chunk = A(1:min(mm,10),1:min(nn,10),:);
      isRGB = (min(chunk(:))>=0 && max(chunk(:))<=1);
      % If the chunk is an RGB image, test the whole image
      if isRGB
         isRGB = (min(A(:))>=0 && max(A(:))<=1);
      end
   end
end
% ---- end of isrgb ----

assert(isRGB | ndims(A)==2,...
    'The input must be a 2-D array or an RGB image.')

classA = class(A);

% --- If the input is an RGB image, HMF is used in the HSV color space
if isRGB
    A = rgb2hsv(A);
    for k = 1:3, A(:,:,k) = hmf(A(:,:,k),n); end
    A = hsv2rgb(A);
    % HSV2RGB returns a double: change the class if necessary
    switch classA
        case 'uint8'
            A = uint8(A*255);
        case 'uint16'
            A = uint16(A*65535);
        case 'single'
            A = single(A);
    end
    return
end

% --- Plus & Cross masks
Plus = false(n,n);
Plus((n+1)/2,:) = true;
Plus(:,(n+1)/2) = true;
Plus = Plus(:);
Cross = false(n,n);
Cross((1:n)+n*(0:n-1)) = true;
Cross((1:n)+n*((n-1):-1:0)) = true;
Cross = Cross(:);

%% --- Hybrid median filtering

% Note: NANMEDIAN is used if this function exists (Statistics Toolbox)
existNaNmedian = exist('nanmedian','file');

% --- the COLFILT function zero-pads! => replicate boundaries
A = padarray(A,[(n-1)/2 (n-1)/2],'replicate');

M1 = colfilt(A,[n n],'sliding',@CrossMedian);
M2 = colfilt(A,[n n],'sliding',@PlusMedian);
if existNaNmedian
    A = nanmedian(cat(3,A,M1,M2),3);
else
    A = median(cat(3,A,M1,M2),3);
end

% remove the borders that were added by PADARRAY
A = A((n+1)/2:end-(n-1)/2,(n+1)/2:end-(n-1)/2);

function CM = CrossMedian(X)
    ncol = size(X,2);
    I = repmat(Cross,[1 ncol]);
    X = reshape(X(I),[2*n-1 ncol]);
    if existNaNmedian
        CM = nanmedian(X);
    else
        CM = median(X);
    end
end

function PM = PlusMedian(X)
    ncol = size(X,2);
    I = repmat(Plus,[1 ncol]);
    X = reshape(X(I),[2*n-1 ncol]);
    if existNaNmedian
        PM = nanmedian(X);
    else
        PM = median(X);
    end
end

end


function plot_circle(q,r,options)

% plot_circle - display a collecion of circles
%
%   plot_circle(q,r,options);
%
%   Copyright (c) 2008 Gabriel Peyre

options.null = 0;
draw_centers = getoptions(options, 'draw_centers', 1);
center_width = getoptions(options, 'center_width', 20);
npoints_circle = getoptions(options, 'npoints_circle', 60)+1;
color_circle = getoptions(options, 'color_circle', 'b');
color_center = getoptions(options, 'color_center', 'b');

if draw_centers
hh = plot(q(1,:), q(2,:), [color_center '.']);
end
set(hh, 'MarkerSize', center_width);
% draw circles
t = linspace(0,2*pi,npoints_circle);
for i=1:length(r)
    plot( sin(t)*r(i)+q(1,i), cos(t)*r(i)+q(2,i), color_circle );
end


function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu,ww)
%function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
% This algorithm goes for accuracy without worrying about memory requirements.
% ydata:   dependent variable data matrix
% xdata:   exogenous variable data matrix
% lags:    number of lags
% breaks:  rows in ydata and xdata after which there is a break.  This allows for
%          discontinuities in the data (e.g. war years) and for the possibility of
%          adding dummy observations to implement a prior.  This must be a column vector.
%          Note that a single dummy observation becomes lags+1 rows of the data matrix,
%          with a break separating it from the rest of the data.  The function treats the
%          first lags observations at the top and after each "break" in ydata and xdata as
%          initial conditions.
% lambda:  weight on "co-persistence" prior dummy observations.  This expresses
%          belief that when data on *all* y's are stable at their initial levels, they will
%          tend to persist at that level.  lambda=5 is a reasonable first try.  With lambda<0,
%          constant term is not included in the dummy observation, so that stationary models
%          with means equal to initial ybar do not fit the prior mean.  With lambda>0, the prior
%          implies that large constants are unlikely if unit roots are present.
% mu:      weight on "own persistence" prior dummy observation.  Expresses belief
%          that when y_i has been stable at its initial level, it will tend to persist
%          at that level, regardless of the values of other variables.  There is
%          one of these for each variable.  A reasonable first guess is mu=2.
%      The program assumes that the first lags rows of ydata and xdata are real data, not dummies.
%      Dummy observations should go at the end, if any.  If pre-sample x's are not available,
%      repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into
%      xdata(1:lags,:) are reasonable subsititutes.  These values are used in forming the
%      persistence priors.

% Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m

if nargin<7
   scale_ = 0;
else
    % correct for heteroskedasticity
    scale_=1;
end

[T,nvar] = size(ydata);
nox = isempty(xdata);
if ~nox
    [T2,nx] = size(xdata);
else
    T2 = T;
    nx = 0;
    xdata = zeros(T2,0);
end
% note that x must be same length as y, even though first part of x will not be used.
% This is so that the lags parameter can be changed without reshaping the xdata matrix.
if T2 ~= T, error('Mismatch of x and y data lengths'),end
if nargin < 4
    nbreaks = 0;
    breaks = [];
else
    nbreaks = length(breaks);
end
breaks = [0;breaks;T];
smpl = [];
for nb = 1:nbreaks+1
    smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]'];
end
Tsmpl = size(smpl,1);
X = zeros(Tsmpl,nvar,lags);
for is = 1:length(smpl)
    X(is,:,:) = ydata(smpl(is)-(1:lags),:)';
end
X = [X(:,:) xdata(smpl,:)];
y = ydata(smpl,:);

% rescale if heteroskedasticity corrected
if scale_ ==1
    ww = [ww; ones(length(y)-length(ww),1) ];
    y = y./ repmat(ww,1,size(y,2)) ;
    X = X ./ repmat(ww,1,size(X,2));
end
% Everything now set up with input data for y=Xb+e

% Add persistence dummies
if lambda ~= 0 || mu > 0
    ybar = mean(ydata(1:lags,:),1);
    if ~nox
        xbar = mean(xdata(1:lags,:),1);
    else
        xbar = [];
    end
    if lambda ~= 0
        if lambda>0
            xdum = lambda*[repmat(ybar,1,lags) xbar];
        else
            lambda = -lambda;
            xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))];
        end
        ydum = zeros(1,nvar);
        ydum(1,:) = lambda*ybar;
        y = [y;ydum];
        X = [X;xdum];
    end
    if mu>0
        xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu;
        ydum = mu*diag(ybar);
        X = [X;xdum];
        y = [y;ydum];
    end
end

% Compute OLS regression and residuals
[vl,d,vr] = svd(X,0);
di = 1./diag(d);
B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y;
u = y-X*B;
xxi = vr.*repmat(di',nvar*lags+nx,1);
xxi = xxi*xxi';

var.B = B;
var.u = u;
var.xxi = xxi;
var.y   = y;
var.X   = X;


function [Nm] = ftlb2Nm(ftlb)
% Convert energy or work from foot-pounds to newtons-meters.
% Chad A. Greene 2012
Nm = ftlb*1.3558179;


function x_stdft = stdft(x, N, K, N_fft)

frames      = 1:K:(length(x)-N);
x_stdft     = zeros(length(frames), N_fft);

w           = ml_hanning(N);
x           = x(:);

for i = 1:length(frames)
    ii              = frames(i):(frames(i)+N-1);
	x_stdft(i, :) 	= fft(x(ii).*w, N_fft);
end


function [Dimg,D,X,err,Z] = perform_dictionary_signature_learning(Y, k, options)

% perform_dictionary_signature_learning - compute an image signature
%
%   [Dimg,D,X,err,options.Z] = perform_dictionary_signature_learning(Y, k, w, options);
%
%   The algorithm is described in
%       M. Aharon and M. Elad,
%       " Sparse and Redundant Modeling of Image Content Using an Image-Signature-Dictionary",
%       Submitted.
%
%   Y is a set of exemplar, each Y(:,i)=p(:) is a w*w vector where p should
%       be some 2D patch of size (w,w) extracted from some image(s).
%   k is the width of the dictionary signature.
%
%   The number of iterations is options.niter.
%   The sparse coder used is set in options.sparse_coder to either 'omp' or
%       'mp'.
%
%   Copyright (c) 2007 Gabriel Peyre

options.null = 0;

% width of the patches
ww = size(Y,1);
w = sqrt(ww);
% number of exemplar
m = size(Y,2);
d = k;
dd = d^2; % number of atoms in the dictionary
kk = k^2;

if m<2*dd
    warning('You should increase the number of exemplars.');
end

% option for OMP
if not(isfield(options, 'nbr_max_atoms'))
    options.nbr_max_atoms = 4;
end
if not(isfield(options, 'use_mex'))
    options.use_mex = 1;
end

Dimg = getoptions(options, 'Dimg', randn(k));
niter = getoptions(options, 'niter', 40);
use_cg = getoptions(options, 'use_cg', 1);
options.niter_max = getoptions(options, 'niter_cg', 10);
sparse_coder = getoptions(options, 'sparse_coder', 'omp');

Dimg = Dimg/sqrt( sum(Dimg(:).^2) );

if isfield(options, 'strict_sparsity')
    options.nbr_atoms_max = options.strict_sparsity;
end

% remove mean
mu = sum(Y);
Y = Y - repmat( mu/ww, [ww 1] );

% compute the dictionary extraction sparse matrix
if isfield(options, 'Z')
    Z = options.Z;
else
    Z = sparse(ww*dd,kk);
    num = 0;
    for x=1:d
        for y=1:d
            num = num+1;
            selx = x:x+w-1;
            sely = y:y+w-1;
            selx = mod(selx-1,k)+1;
            sely = mod(sely-1,k)+1;
            [Ya,Xa] = meshgrid(sely,selx);
            sel = Xa(:) + k*(Ya(:)-1);
            Z( (1:ww)' + (num-1)*ww + (sel-1)*dd*ww ) = 1;
        end
    end
end
err = []; Dimg = Dimg(:);
for i=1:niter
    disp(['--> Iteration ' num2str(i) '/' num2str(niter) '.']);
    % extract dictionary and precompute the matrices
    D = reshape( Z*Dimg, ww, dd);
    % remove zero component and normalize
    D = D - repmat( mean(D), [ww 1] );
    D = D ./ repmat( sqrt( sum(D.^2) ), [ww 1] );
    % sparse coding
    disp('-> Sparse coding.');
    if strcmp(sparse_coder, 'omp')
        X = perform_omp(D,Y,options);
    else
        X = perform_mp(D,Y,options);
    end
    X = full(X);
    err(end+1) = norm(Y-D*X, 'fro');
    % update dictionary
    if not(use_cg)
        % pseudo inverion
        D = Y * pinv(X);
    else
        options.x = D';
        [D,err1] = perform_conjugate_gradient(X*X',X*Y',options);
        D = D';
    end
    % reconstruct
    Dimg = 1/ww * Z'*D(:);
end
Dimg = reshape(Dimg,k,k);
D = reshape( Z*Dimg(:), ww, dd);
D = D - repmat( mean(D), [ww 1] );
D = D ./ repmat( sqrt( sum(D.^2) ), [ww 1] );

% add the low pass DC
D = [ones(ww,1)/sqrt(ww) D];
X = [mu/sqrt(ww); X];


function cout=comp_irdgtiii(cin,a,M)
%COMP_IRDGTIII  Compute inverse real DGT type III.
%
%   This is a computational routine. Do not call it
%   directly.

%   AUTHOR : Peter L. Søndergaard

N=size(cin,1)/M;
W=size(cin,2);
L=N*a;

cin=reshape(cin,M,N,W);

Mhalf=floor(M/2);

cout=zeros(M,N,W,assert_classname(cin));

for m=0:Mhalf-1
  cout(m+1,:,:)=1/sqrt(2)*(cin(2*m+1,:,:)-i*cin(2*m+2,:,:));
  cout(M-m,:,:)=1/sqrt(2)*(cin(2*m+1,:,:)+i*cin(2*m+2,:,:));
end;

if mod(M,2)==1
  cout((M+1)/2,:,:)=cin(M,:,:);
end;


%% Check rate of convergence for 3D H1 interface problem
%     -div(A grad u)  = f,    x\in \Omega
%      where A is a piecewise constant on Omega^+ and Omega^-.
%
% Domain: Rectangular domain: [xmin,xmax] X [ymin,ymax] X [zmin,zmax]
% Mesh: Cartesian triangular mesh.
% Method: VIFE

%% Geometry and Boundary Conditions
%clear
%close all
%clc

%path(pathdef)
addpath(genpath(pwd),'-begin');
rmpath(genpath('./.git'));
rmpath(genpath('./docs'));
savepath;

domain = [-1,1,-1,1,-1,1];
bc = [1,1,1,1,1,1]; % Dirichelet BC

%% Finite Element Type
femtype = 'P1';
disp(['FEM Type =  Conforming ', femtype]);

%% Initial Partition
nx0 = 10;
ny0 = nx0;
nz0 = nx0;

%% Task
showErr = 0;
showMesh = 0;
computErr = 1;

%% PDE
test = 5;
switch test
    case 0
        pde = poissonNonPoly3D;
    case 1 % circular interface
        %r = pi/5; bm = 1; bp = pi/(2*r^2);
        r = sqrt(pi/2); bm = 1; bp = pi/(2*r^2);domain = [-2,2,-2,2,-2,2];
        x0 = 0; y0 = 0; z0 = 0; rx = r; ry = r; rz = r;
        pde = elli3DcircIntf(bm,bp,r,x0,y0,z0,rx,ry,rz);
    case 2 % orthotorus interface
        domain = [-1.2,1.2,-1.2,1.2,-1.2,1.2];
        bm = 1; bp = 1;
        rx = 1; ry = 0.075; rz = 3;
        pde = elli3DorthocircIntf(bm,bp,rx,ry,rz);
    case 3 % line interface
        bm = 1; bp = 10;
        rx = 1; ry = 0; rz = 0; cx = pi/10; cy = 0; cz = 0;
        cm = 1; cp = 1; a = 1;
        pde = elli3DlinIntf(bm,bp,cx,cy,cz,rx,ry,rz,a,cm,cp);
    case 4 % line interface but with zero boundary conditions
        bm = 1; bp = 10^(2); delta = pi/10; % delta can not be -1,1
        pde = elli3DlinIntf2(bm,bp,delta);
    case 5 % circular interface
        r = pi/4; bm = 1; bp = 10; domain = [-1,1,-1,1,-1,1];
        x0 = 0; y0 = 0; z0 = 0;
        pde = elli3DcircIntf5(bm,bp,r,x0,y0,z0);
    case 6 % circular interface
        bm = 1; bp = 10; domain = [-1.3,1.3,-1.3,1.3,-1.3,1.3];
        x1 = -0.3; y1 = 0; z1 = 0; r11 = pi/5; r12 = 0.2;
        x2 =  0.3; y2 = 0; z2 = 0; r21 = pi/5; r22 = 0.2;
        pde = elli3DtorusTwin(bm,bp,x1,y1,z1,r11,r12,x2,y2,z2,r21,r22);
end

%% Max Iteration
maxIt = 4;
time = zeros(9,maxIt);
error = zeros(maxIt,4);
ratio = zeros(maxIt,4);

for i = 1:maxIt

    %% 1. Generate Mesh
    tic
    nx = nx0 + 10*(i-1); h = (domain(2) - domain(1))/nx;
    ny = ny0 + 10*(i-1);
    nz = nz0 + 10*(i-1);
    time(1,i) = nx;
    disp(' ')
    disp('**************************************************************************************')
    disp(['Partition =  ',int2str(nx),' X ',int2str(ny),' X ',int2str(nz)]);
    disp(' ')

    mesh = genMesh3D(domain, nx, ny, nz);
    mesh = enrichMesh3D(mesh,1); % Mesh detail level = 2 (for PPIFE).
    disp(['number of element =  ', int2str(length(mesh.t))]);
    mesh = genIntfMesh3D(mesh,pde.intf);
    disp(['number of interface element =  ', int2str(-min(mesh.tLoc)),...
        ', is ', num2str(100*-min(mesh.tLoc)/length(mesh.t)), '% of all elements']);
    time(2,i) = toc;

    tic
    fem = genFEM3D(mesh,femtype,bc);
    disp(['number of DoF =  ', int2str(length(fem.p))]);
    time(3,i) = toc;

    %% 2. Generate FEMI data including IFE functions and their matrices
    tic
    meshI = genIVmesh(mesh);
    time(4,i) = toc;
    length(unique(union(union(meshI.tface(:,1),meshI.tface(:,2)),meshI.tface(:,3))))

    tic
    option.mass = 0; % generate mass matrix
    option.rhs = 1;
    femI = genP1VIFEM3D(meshI,mesh,pde,option);
    time(5,i) = toc;

    %% 3. Assemble Matrix
    tic
    disp(' '); disp('Start Assembling Matrix');
    option.mass = 0; % generate mass matrix
    matrix = genMatVIFE3D(pde,mesh,fem,meshI,femI);
    time(6,i) = toc;

    %% 4. Solve the linear system Au = f
    tic
    disp(' ')

    disp('Start Solving Linear System: using PCG with ichol precond');
    %L = ichol(matrix.A);
    alpha = 10;
    L = ichol(matrix.A,struct('type','ict','droptol',1e-3,'diagcomp',alpha));
    [u,flag,relres,iter,resvec] = pcg(matrix.A,matrix.f,1e-8,1000,L,L');

    time(7,i) = toc;
    tu = matrix.tu;
    uh = tu; %uh(matrix.mapper) = u;

    %% 5. Postprocess: Calculating Errors
    tic
    errND = max(abs(uh - tu)); % Error on nodes
    err.nd = errND; err.inf = 0; err.l2 = 0; err.h1 = 0;
    if computErr == 1
        disp(' ');  disp('Start computing error in Inf norm');
        eNorm = 'inf';
        errInfN = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);
        eNorm = 'L2'; disp(['Start computing error in ',eNorm,'  norm']);
        errL2 = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);
        eNorm = 'H1x'; disp(['Start computing error in ',eNorm,' norm']);
        errH1x = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);
        eNorm = 'H1y'; disp(['Start computing error in ',eNorm,' norm']);
        errH1y = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);
        eNorm = 'H1z'; disp(['Start computing error in ',eNorm,' norm']);
        errH1z = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);

        disp(' ')
        err.inf = max([errND,errInfN]);
        err.l2 = errL2;
        err.h1 = sqrt(errH1x^2+errH1y^2+errH1z^2);
    end
    time(8,i) = toc;
    time(9,i) = 1e6*sum(time(2:8,i))/length(mesh.t);
    error(i,1) = errND; error(i,2) = err.inf;
    error(i,3) = err.l2; error(i,4) = err.h1;

    %% 6: Display Output
    disp(' ')
    disp('Errors')
    disp('Node        Inf norm    L2 norm     H1 norm')
    formatSpec = '%6.4e  %6.4e  %6.4e  %6.4e\n';
    fprintf(formatSpec, err.nd, err.inf, err.l2, err.h1)

    if i > 1
        format short
        rNd = log(err0.nd/err.nd)./log(h0/h);
        rInf = log(err0.inf/err.inf)./log(h0/h);
        rL2 = log(err0.l2/err.l2)./log(h0/h);
        rH1 = log(err0.h1/err.h1)./log(h0/h);
        disp(' ')
        disp('Convergence Rate')
        disp('Node        Inf norm    L2 norm     H1 norm')
        formatSpec = '%6.4f      %6.4f      %6.4f      %6.4f\n';
        fprintf(formatSpec, rNd, rInf, rL2, rH1)
        ratio(i,:) = [rNd,rInf,rL2,rH1];
    end
    err0 = err; h0 = h;

    disp(' '); disp('CPU Time')
    disp('   N     Mesh     FEM      MeshI    FemI    Matrix   Solve    Error    Time/1M cell')
    formatSpec = '%4i  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f   %7.2f\n';
    fprintf(formatSpec, time(:,1:i))

    %% 6. Plot Solution and Error
    if showErr == 1
    end

end


function [rh,rg,h,g]=rh2rg(rh)

%RH2RG    Calculates all the filters from the synthesis lowpass
%	  in the orthogonal case.
%
%	  [RH,RG,H,G]=RH2RG(RH) begins with the synthesis lowpass
%	  filter (RH) and returns the synthesis highpass filter (RG),
%	  the analysis lowpass filter (H) and the analysis highpass
%	  filter (G).
%
%	  It is an auxiliary function for orthogonal filters design.

%--------------------------------------------------------
% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo
%
%
% Uvi_Wave 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, or (at your option) any
% later version.
%
% Uvi_Wave 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 Uvi_Wave; see the file COPYING.  If not, write to the Free
% Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
%
%       Author: Nuria Gonzalez Prelcic
%       e-mail: Uvi_Wave@tsc.uvigo.es
%--------------------------------------------------------

% Calculate rg from rh.

for i=1:length(rh)
	rg(i) = -(-1)^i*rh(length(rh)-i+1);
end

% Calculate h and g

h=rh(length(rh):-1:1);
g=rg(length(rg):-1:1);


function [x_cplx,opt_val,lb_seq,ub_seq] = CE_similarity_ComRad( H,y,power,ee,x0,cle )
% Branch and Bound Method for ComRad CEP
%   Detailed explanation goes here
N = length(x0);
amp = sqrt(power/N); % Amplitude of the Transmit Signal
y_wave = sqrt(power*cle)*[real(y);imag(y)]; % Equivalent Real Desired Symbol
H_wave = amp*[real(H),imag(H);-imag(H),real(H)]; % Equivalent Real Channel
x0_wave = [real(x0);imag(x0)];
delta = acos(1-ee^2/2);
for ii = 1:N
    l(ii,1) = angle(x0(ii))-delta;
    u(ii,1) = angle(x0(ii))+delta;     %Initialized Upper and Lower Bound
end

A = zeros(N,2*N);
for ii = 1:N
    A(ii,ii) = cos((l(ii)+u(ii))/2)/cos(delta);
    A(ii,ii+N) = sin((l(ii)+u(ii))/2)/cos(delta);
end

max_iternum = 200; %Maximum Iteration Number
epsl = 1e-3; %Tolerence
epsl1 = 1e-6;

[x,LB] = QCQP_LB1( H_wave,y_wave,N,l,u);          %Initialized LB and x
[x_nml1,UB1] = normalize_UB( H_wave,y_wave,x,N,l,u); %Initialized Normalization UB
[x_nml2,UB2] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml1); % fmincon UB
[x_nml,UB] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml2); % fmincon UB
LB_start = LB;
UB_start = UB;

prob_list = zeros(max_iternum+100,4*N+1);          %Problem list initialization
prob_list(1,:)=[x',l',u',LB];
used = 1;
lbest = LB;
ubest = UB;
x_opt = x_nml;

lb_seq = lbest;
ub_seq = ubest;

% if (ubest-lbest)/abs(ubest)<epsl
%     final_lb=lbest;
%     final_ub=ubest;
% end

iter = 2;
con = 1;

while iter<=max_iternum
    xc = prob_list(con,1:2*N)';                                   % Pick a problem having the smallest LB
    lc = prob_list(con,(2*N+1):3*N )';
    uc = prob_list(con,(3*N+1):4*N)';
    x_cplx = x(1:N)+j*x(N+1:2*N);
    %     x_abs = abs(x_cplx);
%     [x_abs_min,cd] = min(x_abs);

    [x_nml3,~] = normalize_UB( H_wave,y_wave,x,N,lc,uc);          % Calculate the UB of the problem
    x_nml3_cplx = x_nml3(1:N)+j*x_nml3(N+1:2*N);
    x_abs = abs(x_cplx - x_nml3_cplx);                            % Branching from the x(n) having the largest gap between x_u and x_l
    [~,cd] = max(x_abs);

    xchild_left_lb=lc;                                            % Generate two sub-problems (left child and right child) at the chosen x(n)
    xchild_left_ub=uc;
    xchild_right_lb=lc;
    xchild_right_ub=uc;
    tr=(lc(cd)+uc(cd))/2;
    xchild_left_ub(cd)=tr;
    xchild_right_lb(cd)=tr;

    if con < used
        prob_list(con,:) = prob_list(used,:);
        used=used-1;
    else
        used=used-1;
    end
    [x,lb] = QCQP_LB1( H_wave,y_wave,N,xchild_left_lb,xchild_left_ub);        % Compute the LB and the associated solution of the left sub-problem

%     [xn_temp,ub_temp] = normalize_UB( H_wave,y_wave,x,N,xchild_left_lb,xchild_left_ub);
%     [xn,ub] = QCQP_UB( H_wave,y_wave,N,xchild_left_lb,xchild_left_ub,xn_temp);
    [xn,ub] = normalize_UB( H_wave,y_wave,x,N,xchild_left_lb,xchild_left_ub); % Compute the UB and the associated solution of the left sub-problem

    if ub < ubest                                                   % If the UB is lower than the current ubest, replace ubest with UB
       ubest=ub;
       x_opt=xn;
    end
    prob_list(used+1,:)=[x',xchild_left_lb',xchild_left_ub',lb];              % Insert the associated LB and solutions into the problem list
    used=used+1;

    [x,lb] = QCQP_LB1( H_wave,y_wave,N,xchild_right_lb,xchild_right_ub);                         % Compute the LB and the associated solution of the right sub-problem
%     [xn_temp,ub_temp] = normalize_UB( H_wave,y_wave,x,N,xchild_right_lb,xchild_right_ub);
%     [xn,ub] = QCQP_UB( H_wave,y_wave,N,xchild_right_lb,xchild_right_ub,xn_temp);
    [xn,ub] = normalize_UB( H_wave,y_wave,x,N,xchild_right_lb,xchild_right_ub); % Compute the UB and the associated solution of the right sub-problem
    if ub < ubest                    % If the UB is lower than the current ubest, replace ubest with UB
       ubest=ub;
       x_opt=xn;
    end
    prob_list(used+1,:)=[x',xchild_right_lb',xchild_right_ub',lb]; % Insert the associated LB and solutions into the problem list
    used=used+1;

    [lbest,con]=min(prob_list(1:used,4*N+1)); % Replace lbest with the smallest LB in the list, mark its index in the problem list as con

    lb_seq(iter)=lbest;           %Generate LB and UB sequences
    ub_seq(iter)=ubest;
    iter=iter+1;

    if ((ubest-lbest)/abs(ubest)<epsl || (ubest-lbest)<epsl1)               %Convergence condition
        final_lb=lbest;
        final_ub=ubest;
        break;
    end
%     clc
%     disp(['Progress - ',num2str(iter),'/',num2str(max_iternum)]);
end
x_cplx = x_opt(1:N)+j*x_opt(N+1:2*N);          %Optimal x

opt_val = objval_func(x_opt,H_wave,y_wave);  %Optimal objective function

end


function [xAL,xBL,doesClip]=clipLine2ConvexPolygon(xAL,xBL,v)
%%CLIPLINE2CONVEXPOLYGON Given the vertices of a convex polygon in 2D in
%       either clockwise or counterclockwise order, clip one or more lines
%       to the polygon. The lines are defined by two points on the lines,
%       though they extend beyond the two points.
%
%INPUTS: xAL, xBL These are 2 2XnumLines matrices where xAL(:,k) and
%                 xBL(:,k) are two points on the kth line.
%               v A 2XnumVertices set of vertices defining the perimeter of
%                 the convex polygon. The last vertex should not be a
%                 repeat of the first vertex.
%
%OUTPUTS: xAL, xBL These are 2XnumLines set of the starting and ending
%                  points of the lines clipped to the polygon. If the kth
%                  line is complete outside the polygon, then xAL(:,k) and
%                  xBL(:,k) will be NaNs.
%         doesClip A numLinesX1 boolean vector indicating whether or not
%                  each line is in or on the polygon at all.
%
%EXAMPLE:
%Draw a polygon and a few line segments in black. The line segments
%represent infinte lines. Clip the lines to the polygon and draw the
%clipped lines in red. One of the lines does not clip, so a black segment
%is drawn, but nothing is drawn in red.
% numVertices=5;
% v=zeros(2,numVertices);
% v(:,1)=[1;1];
% v(:,2)=[15;0];
% v(:,3)=[10;10];
% v(:,4)=[7;10];
% v(:,5)=[0;8];
%
% %Two line segments.
% xA=[[-3;10],[0;0],[4;6],[-2;1]];
% xB=[[12;10],[16;8],[2;7],[-3;3]];
% [xAT,xBT]=clipLine2ConvexPolygon(xA,xB,v);
%
% figure(1)
% clf
% hold on
% plot([v(1,:),v(1,1)],[v(2,:),v(2,1)],'linewidth',2)
% for k=1:size(xA,2)
%     plot([xA(1,k),xB(1,k)],[xA(2,k),xB(2,k)],'-k','linewidth',4)
%
%     if(~isnan(xAT(1,k)))
%         plot([xAT(1,k),xBT(1,k)],[xAT(2,k),xBT(2,k)],'-r','linewidth',2)
%     end
% end
%
%REFERENCES:
%[1] V. Skala, "An efficient algorithm for line clipping by convex
%    polygon," Computer and Graphics, vol. 17, no. 4, pp. 417-421, 1993.
%
%September 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

N=size(v,2);%N is the number of edges and vertices.

%If many lines are clipped at once, precomputing this outside the loop can
%be fastest.
siHat=zeros(2,N);
for k=1:(N-1)
    siHat(:,k)=v(:,k+1)-v(:,k);
end
siHat(:,N)=v(:,1)-v(:,N);

numPts=size(xAL,2);
doesClip=false(numPts,1);

for curPt=1:numPts
    xA=xAL(:,curPt);
    xB=xBL(:,curPt);

    si=bsxfun(@minus,v,xA);
    index=zeros(2,1);
    prevSpecialIdx=-2;

    k=0;
    i=N-1;
    j=0;
    s=xB-xA;
    xi=(si(2,i+1)*s(1)-si(1,i+1)*s(2));
    while((j<N)&&(k<2))
        eta=(si(2,j+1)*s(1)-si(1,j+1)*s(2));
        if(xi*eta<0)%There is an intersection
            index(k+1)=i+1;%The edge having the intersection.
            k=k+1;
            xi=eta;
        elseif(xi*eta==0)%xi and/or eta=0
            if(~(prevSpecialIdx==N-1&&i==0)&&~(prevSpecialIdx==i-1))
                if(eta==0)
                    if(xi~=0)%If not special case m.
                        index(k+1)=i+1;%The edge having the intersection.
                        k=k+1;
                        xi=eta;
                        prevSpecialIdx=i;
                    end
                else%xi==0 and eta is not zero.
                    index(k+1)=i+1;%The edge having the intersection.
                    k=k+1;
                    xi=eta;
                    prevSpecialIdx=i;
                end
            end
        end
        i=j;
        j=j+1;
    end

    if(k==0)
        doesClip(curPt)=false;%There is no intersection.
        xA=NaN;
        xB=NaN;
    else
        doesClip(curPt)=true;%There is an intersection.
        tMin=-Inf;
        tMax=Inf;
        i=index(1);
        t1=det([si(:,i),-siHat(:,i)])/det([s,-siHat(:,i)]);
        i=index(2);
        t2=det([si(:,i),-siHat(:,i)])/det([s,-siHat(:,i)]);

        if(t1<t2)
           temp=t2;
           t2=t1;
           t1=temp;
        end

        if(t2<tMax)
            xB=xA+s*t2;
        end

        if(t1>tMin)
            xA=xA+s*t1;
        end
    end

    xAL(:,curPt)=xA;
    xBL(:,curPt)=xB;
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.


function vbrfa2011_testbed_measure(model, Q)

if nargin < 2 || isempty(Q)
  % Load default results
  disp('Loading default results..')
  files = {'testbed_results_gaussian_D=30_20110617', ...
           'testbed_results_multi-t_D=30_20110617', ...
           'testbed_results_ind-t_D=30_20110617', ...
           'testbed_results_laplace_D=30_20110617'};
  Q = load(files{model}, 'W_struct', 'W', 'CovW', 'X', 'CovX', 'Tau_struct');
end

% Load test data
disp('Loading test data..')
data_test = load(['/share/climate/jluttine/testbed/' ...
                  'testbed_vbrfa2011_testdata']);

% Compute predictive log-likelihood
disp('Computing predictive log-likelihood..')
samples = 10;
[M,N] = size(data_test.observations);
Ytest = data_test.observations;
Itest = ~isnan(Ytest);
loglike = nan(samples,1);
for i=1:samples

  % Sample a noise level
  tau = gamrnd(Q.W_struct.rho_struct.a_tau, 1/Q.W_struct.rho_struct.b_tau);

  % Sample a reconstruction
  for m=1:M
    W(:,m) = gaussian_rand(Q.W(:,m), 1/tau * Q.CovW(:,:,m));
  end
  for n=1:N
    X(:,n) = gaussian_rand(Q.X(:,n), Q.CovX(:,:,n));
  end
% $$$   W = mvnrnd(Q.W', 1/tau * Q.CovW)';
% $$$   X = mvnrnd(Q.X', Q.CovX)';
  F = W'*X;

  % Log-likelihood
  switch model
   case 1 % GAUSSIAN
    Z = Ytest(Itest) - F(Itest);
    loglike(i) = gaussian_logpdf(tau*(Z'*Z), ...
                                 0, ...
                                 0, ...
                                 -numel(Z)*log(tau), ...
                                 numel(Z));

   case 2 % MULTIVARIATE T
    alpha = Q.Tau_struct.a_u;
    beta = Q.Tau_struct.b_u;
    tau = tau * (alpha./beta);
    nu = 2*alpha;
    Z = Ytest - F;
    Z(~Itest) = 0;
    Z2 = tau .* dot(Z,Z,1);
    Nmv = sum(Itest,1)>0;
    loglike(i) = sum(t_logpdf(Z2(Nmv), ...
                              -log(tau(Nmv)), ...
                              nu(Nmv), ...
                              sum(Itest(:,Nmv),1)));

   case 3 % INDEPENDENT T
    [I,J] = find(Itest);
    Z2 = tau * (Ytest(Itest) - F(Itest)).^2;
    loglike(i) = sum(t_logpdf(Z2, ...
                              -log(tau), ...
                              Q.Tau_struct.nu(I), ...
                              1));

   case 4 % LAPLACE
    loglike(i) = sum(laplace_logpdf(Ytest(Itest), ...
                                    F(Itest), ...
                                    sqrt(tau)));
  end

end
%loglike = loglike / samples;
fprintf('Mean predictive log-density: %.4e\n', mean(loglike));
bias = max(loglike);
fprintf('Log predictive density: %.4e\n', log(mean(exp(loglike-bias))) + bias);


function [data,units] = compute_dangle_smallest_wing(trx,n)

flies = trx.exp2flies{n};
nflies = numel(flies);
data = cell(1,nflies);
for i = 1:nflies,
  fly = flies(i);

  danglel = diff(-trx(fly).wing_anglel);
  dangler = diff(trx(fly).wing_angler);
  data{i} = danglel;
  idx = trx(fly).wing_arear_mm(1:end-1) <= trx(fly).wing_areal_mm(1:end-1);
  data{i}(idx) = dangler(idx);
  data{i} = data{i} ./ trx(fly).dt;

end
units = parseunits('rad/s');


function [km3] = cl2km3(cl)
% Convert volume from centiliters to cubic kilometers.
% Chad Greene 2012
km3 = cl*1e-14;


% Dual RPCA (Lin et al. 2009)
% process_video('RPCA', 'DUAL', 'dataset/demo.avi', 'output/demo_DUAL.avi');
lambda = 1/sqrt(max(size(M))); % default lambda
[L,S] = dual_rpca_2(M,lambda);


function [AP,TP,FN,FP,prec,rec,mdAll,levh]=averageprecision(coord_est,coord_true,radiustrue,intens)
% Evaluates average precision for set of true and estimated points. See S407_report for details.
% References: Everingham, M., Gool, L., Williams, C.K.I., Winn, J. & Zisserman, A. The Pascal Visual Object Classes (VOC) Challenge. International Journal of Computer Vision 88, 303-338 (2009).
%
% [AP,TP,FN,FP,prec,rec,mdAll]=averageprecision(coord_est,coord_true,radiustrue,intens)
% input:  coord_est - Nx2 matrix of estimated coordinates
%         coord_true- Nx2 matrix of true coordinates
%         radiustrue - limit on distance between true and estimated coordinates. For smaller distance the estimated point is considered as a true positive (can be set to sigma/2, where sigma is the std of the gaussian approximation of hte PSF.)
%         intens - Nx1 vector of intensity of the estimated source
%
% output: AP - average precision
%         TP - true positives
%         FN - false negatives
%         FP - false poitives
%         prec - precision
%         rec - recall
%         mdAll - localisation precision at the lowest confidence level

% levn = 100; % number of confidence levels for AP (see S407_report.pdf)

levh=sort(unique(sqrt(double(intens))));
levn=length(levh); % number of different intensities

nT=size(coord_true,1);
nE=size(coord_est,1);
minh=min(levh);
maxh=max(levh);
% levh=minh+(maxh-minh)/(levn-1)*[0:levn-1];

TP=zeros(levn,1);
FP=nE*ones(levn,1);
FN=nT*ones(levn,1);
T = coord_true;
mdAll=mindistsep(T,coord_est);
for ii=1:levn
    index = sqrt(intens)>=levh(ii); % above the limit brightness
    E = coord_est(index,:);
    [md,mT,mE]=mindistsep(T,E); % mT and mE are indeces of points connected by a distance md.
    TP(ii) = sum(md<=radiustrue); %true positives
    setDiffE=setdiff(1:size(E,1),mE); % These estimated points have not been assighned to any true point.
    setDiffT=setdiff(1:size(T,1),mT); % These true points have not been assighned to any estimated point.
    FP(ii) = numel(setDiffE)+sum(md>radiustrue); %False positives: points futher from true then md, and estimated pints without any assigned true point
    FN(ii) = numel(setDiffT)+sum(md>radiustrue); %False negatives: points futher from true then md, and true poitions without any assigned esitmated point
end

prec = TP./(TP+FP);
rec = TP./(TP+FN);

precinterpol = zeros(11,1);
for ii=0:10;
    recind=rec>=(.1*ii);
    maxprec = max(prec(recind));
    if ~isempty(maxprec)
        precinterpol(ii+1)=maxprec;
    end
end

AP=1/11*sum(precinterpol);


function [beta,betastar] = igls_orig(y, x, Vy, type)
% function [betastar] = igls(y, x, Vy)
%
% Variance Component Estimation using IGLS/RIGLS
%
% y = d + cx + epsilon  where  epsilon ~ N(0,sigma*Vy)
%
% d ~ N(0, sigma_d) and c ~ N(0, sigma_c)
%
% Calculate d, c, sigma, sigma_d and sigma_c using Maximum Likelihood
% methods (IGLS) and Restricted Maximum Likelihood methods (RIGLS).
%
% y - matrix T x subjects
% x - matrix T x subjects
% Vy - matrix T x T x subjects
% type = 'i' IGLS
% type = 'r' RIGLS
%
% By Martin Lindquist, April 2007
%
% Example:
%
% len = 200; sub =20;
% x = zeros(len,sub);
% x(11:20,:) = 2;
% x = x+ normrnd(0,0.1,len,sub);
% c = normrnd(0.5,0.1,sub,1);
% d = normrnd(3,0.2,sub,1);
% y=x;
% for i=1:sub, y(:,i) = d(i) + c(i).*x(:,i) + normrnd(0,0.5,len,1); end;
% Vy = zeros(len,len,sub);
% for i=1:sub, Vy(:,:,i) = eye(len,len).*0.5; end;
%
% [beta, betastar] = igls(y, x, Vy,'i')
%
c1= clock;
[T, sub] = size(y);             % Length of y vector and Number of subjects

one = zeros(T,1)+1;             % Vector of ones
null = zeros(T,1);              % Vector of zeros

epsilon = 0.001;
num_iter = 5;

len = sub*T;                                    % Total number of observations
z = reshape(y,len,1);                           % Concatenated data
D = [zeros(len,1)+1 reshape(x,len,1)];          % Design matrix

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Step 1: Find the OLS solution
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

beta = pinv(D)*z;                           % Beta values
resid = z - D*beta;                         % Residuals

ystar = [];
if (type == 'i'),           % IGLS
     for i=1:sub,
         tmp = vech(resid(((i-1)*T+1):(i*T))*resid(((i-1)*T+1):(i*T))');                 % Find vech of estimated covariance
         ystar = [ystar; tmp];
     end;
elseif (type == 'r'),       % RIGLS
    for i=1:sub,
        Dtmp = D((((i-1)*T+1):(i*T)),:);
        rtmp = resid(((i-1)*T+1):(i*T));
        rig = rtmp*rtmp' + Dtmp*inv(Dtmp'*Dtmp)*Dtmp';
        tmp = vech(rig);                              % Find vech of estimated covariance
        ystar = [ystar; tmp];
    end;
end;

clear tmp rtmp rig Dtmp
G = Create_Design_Eq2(y, x, Vy);                      % Create design matrix for variance estimation
betastar = pinv(G)*ystar;                             % Estimate variance components

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Step 2: Iterate
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

cnt = 0;
betastar_old = betastar+10;

iSigma = zeros(len,len);

while(cnt < num_iter | sum((betastar-betastar_old).^2)> epsilon),

    num = size(G,1)/sub;

    for i=1:sub,
        iSigma(((i-1)*T+1):(i*T),((i-1)*T+1):(i*T)) = ivech(G(((i-1)*num+1):(i*num),:)*betastar);
    end;

    beta = inv(D'*iSigma*D)*D'*iSigma*z;          % Beta values
    resid = z - D*beta;                           % Residuals

    ystar = [];

    if (type == 'i'),           % IGLS
         for i=1:sub,
             tmp = vech(resid(((i-1)*T+1):(i*T))*resid(((i-1)*T+1):(i*T))');                 % Find vech of estimated covariance
             ystar = [ystar; tmp];
         end;
    elseif (type == 'r'),       % RIGLS
         for i=1:sub,
            Dtmp = D((((i-1)*T+1):(i*T)),:);
            rtmp = resid(((i-1)*T+1):(i*T));
            rig = rtmp*rtmp' + Dtmp*inv(Dtmp'*iSigma((((i-1)*T+1):(i*T)),(((i-1)*T+1):(i*T)))*Dtmp)*Dtmp';
            tmp = vech(rig);                                                                 % Find vech of estimated covariance
            ystar = [ystar; tmp];
         end;
    end;

    clear tmp rtmp rig Dtmp

    betastar_old = betastar;
    betastar = pinv(G)*ystar;                                         % Estimate variance components

    cnt = cnt+1
end;

c2 = clock;
c2 - c1
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Subfunctions
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [G] = Create_Design_Eq2(y, x, Vy)
% function [G] = Create_Design(y, x, Vy)
%
% Create Design matrix for estimation of variance componets
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[T, sub] = size(x);
len = T*(T+1)/2;
ONE = zeros(len,1)+1;

G = [];
H = [];

for i=1:sub,

    XX = x(:,i)*x(:,i)';

    Gtmp = zeros(len,3);
    Gtmp(:,1) = ONE;
    Gtmp(:,2) = vech(XX);
    Gtmp(:,3) = vech(Vy(:,:,i));
    G = [G; Gtmp];

end;

return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function V = vech(Mat)
% function V = vech(Mat)
%
% Calculate vech for the matrix Mat
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

V = Mat(logical(tril(ones(size(Mat)))));

return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function Mat = ivech(V)
% function Mat = vech(V)
%
% Calculate the "inverse" of the vech function
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

len = length(V);
dim = -0.5 + sqrt(0.25 + 2*len);
Mat = zeros(dim,dim);
ind=1;

for i=1:dim
    for j=i:dim
        Mat(j,i)=V(ind);
        ind=ind+1;
    end
end

return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function [ homos ] = NewWarping( pa_, pb_, H, W, qH, qW, lambda)
% A warpped up wersion of as-similar-as-possible warping, with pre-warp.
% set PREWARP to false if the output is badly distorted.
    PREWARP = true;
    nP = length(pa_);
    if length(pb_) ~= nP
        error('Points Numbers met Matching!');
    end
    if PREWARP
        [preH, ~] = ransacfithomography(pa_', pb_', 0.001);
        whilecount = 0;
        while isnan(preH(1, 1)) && whilecount < 100
            [preH, ~] = ransacfithomography(pa_', pb_', 0.001);
            whilecount = whilecount + 1;
        end
        if whilecount == 100
            error('?') ;
        end
    else
        preH = eye(3);
        pa = pa_;
    end
    pbWarp = preH \ [pb_' ; ones(1, nP)];
    pbWarp(1, :) = pbWarp(1, :) ./ pbWarp(3, :);
    pbWarp(2, :) = pbWarp(2, :) ./ pbWarp(3, :);
    pbWarp = pbWarp(1:2, :)';

    diff = sum((pa_ - pbWarp) .* (pa_ - pbWarp), 2) < 1000;
    valid = pbWarp(:, 1) > 0 & pbWarp(:, 1) < W & pbWarp(:, 2) > 0 & pbWarp(:, 2) < H;
    pa = pa_(valid & diff, :);
    pbWarp = pbWarp(valid & diff, :);

    asap = AsSimilarAsPossibleWarping(H, W, qW, qH, lambda);
    asap.SetControlPts(pa, pbWarp);
    asap.Solve();

% -----DEBUG-SCRIPT------
% use it to check the warping result
%     e = asap.CalcError();

%     grid = asap.Warp(ones(H, W, 3) * 255, 400);
%     imshow(grid);

%     if e > 10
%         disp('?') ;
%     end

    homos2 = asap.CalcHomos();
    homos = homos2;
    for row = 1:H/qH
        for col = 1:W/qW
            tempH = preH * squeeze(homos2(row, col, :, :));
            homos(row, col, :, :) = tempH ./ tempH(3, 3);
        end
    end
end


function SeamVector=removalMap(X,lines);
% REMOVALMAP takes a given image and finds the ordered set of (vertical)
% seams that are removed from an image and returns them in an array, where
% the Nth column in the array corresponds to the Nth seam to be removed.
%
% Author: Danny Luong
%         http://danluong.com
%
% Last updated: 12/20/07

[rows cols dim]=size(X);

E=findEnergy(X);    %Finds the gradient image

for i=1:min(lines,cols-1)

    %find "energy map" image used for seam calculation given the gradient image
    S=findSeamImg(E);

    %find seam vector given input "energy map" seam calculation image
    SeamVector(:,i)=findSeam(S);

    %remove seam from image
    X=SeamCut(X,SeamVector(:,i));
    E=SeamCut(E,SeamVector(:,i));

    %updates size of image
    [rows cols dim]=size(X);
end