function b=num2ibm(x)
% num2ibm : convert IEEE 754 doubles to IBM 32 bit floating point format
%    b=num2ibm(x)
% x is a matrix of doubles
% b is a corresponding matrix of uint32
%
% The representations for NaN and inf are arbitrary
%
% See also ibm2num

%
%    This program is free software; you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation; either version 2 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program; if not, write to the Free Software
%    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
%
%
% (C) Brian Farrelly, 22 October 2001
%  mailto:Brian.Farrelly@nho.hydro.com          Norsk Hydro Research Centre
%  phone +47 55 99 68 74                 (((                  Postboks 7190
%  fax   +47 55 99 69 70                2oooS                 N-5020 Bergen
%  home  +47 55 13 78 49                HYDRO                        Norway
%

b=repmat(uint32(0),size(x));
err=zeros(size(x));

%format long

x(x> 7.236998675585915e+75)= inf;        % change big numbers to infinity
x(x<-7.236998675585915e+75)=-inf;        % 7.236998675585915e+75 is
                                         %    ibm2num(uint32(hex2dec('7fffffff')) or
                                         %    ibm2num(num2ibm(inf))

[F E]=log2(abs(x));

e=E/4;                         % exponent of base 16
ec=ceil(e);                    % adjust upwards to integer
p=ec+64;                       % offset exponent

f=F.*2.^(-4*(ec-e));           % correct mantissa for fractional part of exponent
f=round(f*2^24);               % convert to integer. Roundoff here can be as large as
                               % 0.5/2^20 when mantissa is close to 1/16 so that
                               % 3 bits of signifance are lost.

p(f==2^24)=p(f==2^24)+1;       % Roundoff can cause f to be 2^24 for numbers just under a
f(f==2^24)=2^20;               % power of 16, so correct for this

%format hex
psi=uint32(p*2^24);            % put exponent in first byte of psi.
phi=uint32(f);                 % put mantissa into last 3 bytes of phi

% make bit representation

b=bitor(psi,phi);                        % exponent and mantissa
b(x<0)=bitset(b(x<0),32);                % sign bit
%format long

% special cases

b(x==0)          =uint32(0)                  ;         %  bias is incorrect for zero
b(isnan(x))      =uint32(hex2dec('7fffffff'));         %  7.237005145973116e+75 in IBM format
b(isinf(x) & x>0)=uint32(hex2dec('7ffffff0'));         %  7.236998675585915e+75    ,,
b(isinf(x) & x<0)=uint32(hex2dec('fffffff0'));         % -7.236998675585915e+75    ,,
                                                       % Note that NaN > inf in IBM format

% check bit representation for normal cases

checkx=ibm2num(b);                      % note that use of base 16 in IBM format
z=x==0;                                 % can lead to a loss of 3 bits of precision
err(z)=0;                               % compared with an IEEE single.
q=(checkx(~z)-x(~z))./x(~z);
err(~z) = abs(q) > 5e-7;                % this is almost reached with numbers
                                        % of the form 16^n + 0.5*16^(n-5) where
                                        % the mantissa is 100001 hex. Roundoff
                                        % error is then 0.5/16^5=0.5/2^20=4.7684e-7

if any(err)
   warning('Conversion error in num2ibm for the following:')
   disp(x(logical(err)))
end


function C = xcorrn( A, T, shape )
% n-dimensional cross-correlation.  Generalized version of xcorr2.
%
% For 2 dimensional inputs this function is exactly the same as xcorr2, but
% also works in higher dimensions. Can also be more efficient because it
% performs convolution using convnFast.  Note that xcorr2 is part of the
% 'Signal Processing Toolbox' and may not be available on all systems.
%
% The order of parameters is reversed from normxcorrn. This is to be
% compatible with the matlab functions normxcorr2 and xcorr2 (which take
% parameters in different orders).
%
% USAGE
%  C = xcorrn( A, T, [shape] )
%
% INPUTS
%  A           - first d-dimensional matrix
%  T           - second d-dimensional matrix
%  shape       - ['full'] 'valid', or 'same' (see convn)
%
% OUTPUTS
%  C           - correlation matrix
%
% EXAMPLE
%  T=gaussSmooth(rand(20),2); A=repmat(T,[3 3]);
%  C1=xcorr2(A,T); C2=xcorrn(A,T); C3=rot90(xcorrn(T,A),2);
%  figure(1); im(C1);  figure(2); im(C2);  figure(3); im(C3);
%
% See also XCORR2, NORMXCORRN, XEUCN, CONVNFAST
%
% Piotr's Computer Vision Matlab Toolbox      Version 2.12
% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( nargin<3 || isempty(shape)); shape='full'; end
nd = ndims(A);
if(nd~=ndims(A)); error('xcorrn: T and A must have same ndims'); end;

% flip for conv purposes
if(nd==2); T=rot90(T,2); else for d=1:nd; T=flipdim(T,d); end; end

% convolve [in frequency or spatial domain]
C = convnFast( A, T, shape );


%ISCALESPACE  Scale-space image sequence
%
% [G,L,S] = ISCALESPACE(IM, N, SIGMA) is a scale space image sequence of
% length N derived from IM (HxW).  The standard deviation of the smoothing
% Gaussian is SIGMA.  At each scale step the variance of the Gaussian increases
% by SIGMA^2.  The first step in the sequence is the original image.
%
% G (HxWxN) is the scale sequence, L (HxWxN) is the absolute value of the
% Laplacian of Gaussian (LoG) of the scale sequence, corresponding to each
% step of the sequence, and S (Nx1) is the vector of scales.
%
% [G,L,S] = ISCALESPACE(IM, N) as above but SIGMA=1.
%
% Examples::
%  Create a scale-space image sequence
%         im = iread('lena.png', 'double', 'grey');
%         [G,L,s] = iscalespace(im, 50, 2);
%  Then find scale-space maxima, an array of ScalePointFeature objects.
%         f = iscalemax(L, s);
%  Look at the scalespace volume
%         slice(L, [], [], 5:10:50); shading interp
%
% Notes::
% - The Laplacian is approximated by the the difference of adjacent Gaussians.
%
% See also ISCALEMAX, ISMOOTH, ILAPLACE, KLOG.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.

function [G, L, S] = scalespace(im, n, sigma)

    if nargin < 3
        sigma = 1;
    end

    g(:,:,1) = im;
    scale = 0.5;
    scales = scale;
    for i=1:n-1,
        im = ismooth(im, sigma);
        scale = sqrt(scale^2 + sigma^2);
        scales = [scales; scale];
        g(:,:,i+1) = im;
        lap(:,:,i) = scale^2 * ( g(:,:,i+1) - g(:,:,i) );
    end

    % return results as requested
    if nargout > 2,
        S = scales;
    end
    if nargout > 0,
        G = g;
    end
    if nargout > 1,
        L = lap;
    end


function mb = trimeshMeanBreadth(vertices, faces)
%TRIMESHMEANBREADTH Mean breadth of a triangular mesh.
%
%   MB = trimeshMeanBreadth(VERTICES, FACES)
%   Computes the mean breadth (proporitonal to the integral of mean
%   curvature) of a triangular mesh.
%
%   Example
%     [V, F] = createCube;
%     F2 = triangulateFaces(F);
%     MB = trimeshMeanBreadth(V, F2)
%     MB =
%         1.5000
%
%   See also
%   meshes3d, trimeshSurfaceArea, trimeshEdgeFaces, polyhedronMeanBreadth
%
%   References
%   Stoyan D., Kendall W.S., Mecke J. (1995) "Stochastic Geometry and its
%       Applications", John Wiley and Sons, p. 26
%   Ohser, J., Muescklich, F. (2000) "Statistical Analysis of
%       Microstructures in Materials Sciences", John Wiley and Sons, p.352

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2015-08-19,    using Matlab 8.5.0.197613 (R2015a)
% Copyright 2015 INRA - Cepia Software Platform.

%% Check input validity

if size(faces, 2) ~= 3
    error('meshes3d:trimeshMeanBreadth:NonTriangularMesh', ...
        'Requires a triangular mesh as input');
end

%% Compute edge and edgeFaces arrays
% Uses the same code as in trimeshEdgeFaces

% compute vertex indices of each edge (in increasing index order)
edges = sort([faces(:,[1 2]) ; faces(:,[2 3]) ; faces(:,[3 1])], 2);

% create an array to keep indices of faces "creating" each edge
nFaces = size(faces, 1);
edgeFaceInds = repmat( (1:nFaces)', 3, 1);

% sort edges, keeping indices
[edges, ia, ib] = unique(edges, 'rows'); %#ok<ASGLU>
nEdges = size(edges, 1);

% allocate memory for result
edgeFaces = zeros(nEdges, 2);

% iterate over edges, to identify incident faces
for iEdge = 1:nEdges
    inds = find(ib == iEdge);
    edgeFaces(iEdge, 1:length(inds)) = edgeFaceInds(inds);
end

%% Compute dihedral angle for each edge

% compute normal of each face
normals = meshFaceNormals(vertices, faces);

% allocate memory for resulting angles
alpha = zeros(nEdges, 1);

% iterate over edges
for iEdge = 1:nEdges
    % indices of adjacent faces
    indFace1 = edgeFaces(iEdge, 1);
    indFace2 = edgeFaces(iEdge, 2);

    % normal vector of adjacent faces
    normal1 = normals(indFace1, :);
    normal2 = normals(indFace2, :);

    % compute dihedral angle of two vectors
    alpha(iEdge) = vectorAngle3d(normal1, normal2);
end

%% Compute mean breadth
% integrate the dihedral angles weighted by the length of each edge

% compute length of each edge
lengths = meshEdgeLength(vertices, edges);

% compute product of length by angles
mb = sum(alpha .* lengths) / (4*pi);


function [trans, points] = registerPoints3dAffine(points, target, varargin)
%REGISTERPOINTS3DAFFINE Fit 3D affine transform using iterative algorithm.
%
%   TRANS = registerPoints3dAffine(POINTS, TARGET)
%   Computes the affine transform that maps the shape defines by POINTS
%   onto the shape defined by the points TARGET. Both POINTS and TARGET are
%   N-by-3 array of point coordinates, not necessarily the same size.
%   The result TRANS is a 4-by-4 affine transform.
%
%   TRANS = registerPoints3dAffine(POINTS, TARGET, NITER)
%   Specifies the number of iterations for the algorithm.
%
%   [TRANS, POINTS2] = registerPoints3dAffine(...)
%   Also returns the set of transformed points.
%
%   Example
%     registerPoints3dAffine
%
%   See also
%     transforms3d, fitAffineTransform3d
%

% ------
% Author: David Legland
% E-mail: david.legland@inra.fr
% Created: 2015-02-24, using Matlab 8.4.0.150421 (R2014b)
% Copyright 2015-2022 INRA - Cepia Software Platform

nIters = 10;
if ~isempty(varargin)
    nIters = varargin{1};
end

% keep original points to transform them at each
trans = [1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1];

for i = 1:nIters
    % identify target points for each source point
    inds = findClosestPoint(points, target);
    corrPoints = target(inds, :);

    % compute transform for current iteration
    trans_i = fitAffineTransform3d(points, corrPoints);

    % apply transform, and update cumulated transform
    points = transformPoint3d(points, trans_i);
    trans = trans_i * trans;
end


function diff = getDiffuseness_TV(i_vecs)
%GETDIFFUSENESS_TV Compute diffuseness from temporal variation of intensity
%vectors
%
%   This routine estimates diffuseness using the temporal variation of
%   intensity vectors, as proposed in
%
%       Ahonen, J. and Pulkki, V., 2009.
%       Diffuseness estimation using temporal variation of intensity vectors.
%       In 2009 IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (WASPAA).
%
%   also termed coefficient of variation in other works. It is based on the
%   relation sqrt( 1 - ||<Ia>||/<||Ia||> ), where Ia is the active intensity
%   vector. It is similar to the spherical variance estimator, but it takes
%   into account the magnitude of the DoA vectors, hence giving more weight
%   to strong sound estimates instead of low noisy ones. It is also flexible
%   in the sense that alternative DoA vectors with magnitude that relates
%   to the energy of the sound-field can be used instead of the intensity
%   vector.
%
%   Inputs:
%       i_vecs:  Kx3 matrix of DoA vectors, for K temporal observations
%
%   Outputs:
%       diff:       diffuseness value
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GETDIFFUSENESS_TV.M - 5/10/2016
% Archontis Politis, archontis.politis@aalto.fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% mean of active intensity vectors
mean_i_vecs = mean(i_vecs, 1);
% norm of mean vector
norm_mean_i_vecs = sqrt(sum(mean_i_vecs.^2, 2));

% norm of intensity vectors
norm_i_vecs = sqrt(sum(i_vecs.^2, 2));
% mean of norms
mean_norm_i_vecs = mean(norm_i_vecs);

% diffuseness
diff = sqrt( 1 - norm_mean_i_vecs/mean_norm_i_vecs );

end


function nu = PoissonRatio(S,x,y)
% Poisson ratio of an elasticity tensor
%
% Syntax
%   nu = PoissonRatio(S,x,y)
%   nu = PoissonRatio(S) % isotropic case
%
% Input
%  S - elastic @complianceTensor
%  x - @vector3d tension direction
%  y - @vector3d perpendicular direction
%
% Output
%  nu - Poisson ratio
%
% Description
%
% $$\nu = \frac{-S_{ijkl} x_i x_j y_k y_l}{S_{mnop} x_m x_n x_o x_p}$$
%

if nargin == 1  % isotrpoic theory

  S_iso_Voigt = mean(S,uniformODF(S.CS));
  nu = S_iso_Voigt.PoissonRatio(xvector,yvector);

  return
end

% generate a function if required
if nargin == 1 || isempty(x)

  nu = S2FunHarmonicSym.quadrature(@(v) PoissonRatio(S,v,y),'bandwidth',4,S.CS);

elseif nargin <= 2 || isempty(y)

  nu = S2FunHarmonicSym.quadrature(@(v) PoissonRatio(S,x,v),'bandwidth',4,S.CS);

else

  % compute tensor product
  nu = -EinsteinSum(S,[-1 -2 -3 -4],x,-1,x,-2,y,-3,y,-4) ./ ...
    EinsteinSum(S,[-1 -2 -3 -4],x,-1,x,-2,x,-3,x,-4);

end


function D = spm_mesh_distmtx(M,order)
% Compute the distance matrix of a triangle mesh
% FORMAT D = spm_mesh_distmtx(M,order)
% M        - patch structure
% order    - 0: adjacency matrix
%            1: first order distance matrix [default]
%            2: second order distance matrix
%
% D        - distance matrix
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_mesh_distmtx.m 4035 2010-08-05 18:54:32Z guillaume $

if nargin < 2, order = 1; end

if order > 2, error('High order distance matrix not handled.'); end

%-Adjacency matrix
%--------------------------------------------------------------------------
if order == 0
    D = spm_mesh_adjacency(M);
    return;
end

%-First order distance matrix
%--------------------------------------------------------------------------
if isstruct(M) && ~isa(M.faces,'double')
    M.faces = double(M.faces);
elseif isa(M,'gifti')
    M = export(M,'patch');
    M.faces = double(M.faces);
end
d = M.vertices(M.faces(:,[1 2 3]),:) - M.vertices(M.faces(:,[2 3 1]),:);

D = sparse([M.faces(:,1); M.faces(:,2); M.faces(:,3)], ...
           [M.faces(:,2); M.faces(:,3); M.faces(:,1)], sqrt(sum(d.^2, 2)));

D = (D + D')/2;

if order == 1, return; end

%-Second order distance matrix
%--------------------------------------------------------------------------
D2 = D;
for i=1:size(M.vertices,1)
    a      = find(D2(i,:));
    [b,c]  = find(D2(a,:));
    D(i,c) = D(i,a(b)) + diag(D(a(b),c))';
    D(c,i) = D(i,c)';
end


function flux = EulerRoe2D(nx, ny, QM, QP, gamma)

% function flux = EulerRoe2D(nx, ny, QM, QP, gamma)
% Purpose: compute surface fluxes for Euler's equations using the approximate
%          Riemann solver based on Roe averages

% Rotate "-" trace momentum to face normal-tangent coordinates
rhouM = QM(:,:,2); rhovM = QM(:,:,3);
QM(:,:,2) = nx.*rhouM + ny.*rhovM; QM(:,:,3) =-ny.*rhouM + nx.*rhovM;

% Rotate "+" trace momentum to face normal-tangent coordinates
rhouP = QP(:,:,2); rhovP = QP(:,:,3);
QP(:,:,2) = nx.*rhouP + ny.*rhovP; QP(:,:,3) =-ny.*rhouP + nx.*rhovP;

% Compute fluxes and primitive variables in rotated coordinates
[fxQM,fyQM,rhoM,uM,vM,pM] = EulerFluxes2D(QM, gamma);
[fxQP,fyQP,rhoP,uP,vP,pP] = EulerFluxes2D(QP, gamma);
EnerM = QM(:,:,4); EnerP = QP(:,:,4);

Nfields = 4;
HM   = (EnerM+pM)./rhoM; cM = sqrt(gamma*pM./rhoM);
HP   = (EnerP+pP)./rhoP; cP = sqrt(gamma*pP./rhoP);

% Compute Roe average variables
rhoMs = sqrt(rhoM); rhoPs = sqrt(rhoP);

rho = rhoMs.*rhoPs;
u   = (rhoMs.*uM + rhoPs.*uP)./(rhoMs + rhoPs);
v   = (rhoMs.*vM + rhoPs.*vP)./(rhoMs + rhoPs);
H   = (rhoMs.*HM + rhoPs.*HP)./(rhoMs + rhoPs);

c2  = (gamma-1)*(H - 0.5*(u.^2 + v.^2)); c = sqrt(c2);

% Compute estimate of waves speeds
SL = min(uM-cM, u-c); SR = max(uP+cP, u+c);

% Compute HLL flux
t1 = (min(SR,0)-min(0,SL))./(SR-SL);
t2 = 1-t1;
t3 = (SR.*abs(SL)-SL.*abs(SR))./(2*(SR-SL));

for n=1:4
  fx(:,:,n) = t1.*fxQP(:,:,n) + t2.*fxQM(:,:,n) - t3.*(QP(:,:,n)-QM(:,:,n));
end

% rotate flux back into Cartesian coordinates
flux(:,:,1) = fx(:,:,1);
flux(:,:,2) = nx.*fx(:,:,2) - ny.*fx(:,:,3);
flux(:,:,3) = ny.*fx(:,:,2) + nx.*fx(:,:,3);
flux(:,:,4) = fx(:,:,4);;
return;


%                           solveWirtFlow.m
%
%  Implementation of the Wirtinger Flow (WF) algorithm proposed in the
%  paper.
%
%% I/O
%  Inputs:
%     A:    m x n matrix or a function handle to a method that
%           returns A*x.
%     At:   The adjoint (transpose) of 'A'. If 'A' is a function handle,
%           'At' must be provided.
%     b0:   m x 1 real,non-negative vector consists of all the measurements.
%     x0:   n x 1 vector. It is the initial guess of the unknown signal x.
%     opts: A struct consists of the options for the algorithm. For details,
%           see header in solvePhaseRetrieval.m or the User Guide.
%
%     Note: When a function handle is used, the
%     value of 'At' (a function handle for the adjoint of 'A') must be
%     supplied.
%
%  Outputs:
%     sol:  n x 1 vector. It is the estimated signal.
%     outs: A struct consists of the convergence info. For details,
%           see header in solvePhaseRetrieval.m or the User Guide.
%
%
%  See the script 'testWirtFlow.m' for an example of proper usage of this
%  function.
%
%% Notations
%  x is the estimation of the signal. y is the vector of measurements such
%  that yi = |<ai,x>|^2 for i = 1,...,m
%
%% Algorithm Description
%  WF successively refines the estimate via an update rule that bears a
%  strong resemblance to a gradient descent scheme. Specifically, at each
%  iteration, x = x + mu/m * gradient log-likelihood of x given y For the
%  detailed formulation of "gradient log-likelihood of x given y" and a
%  detailed explanation of the theory, see the WF paper referenced below.
%
%% References
%  Paper Title:   Phase Retrieval via Wirtinger Flow: Theory and Algorithms
%  Place:         Chapter 2.3
%  Authors:       Emmanuel Candes, Xiaodong Li, Mahdi Soltanolkotabi
%  arXiv Address: https://arxiv.org/abs/1407.1065
%
% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,
% Christoph Studer, & Tom Goldstein
% Copyright (c) University of Maryland, 2017

%% -----------------------------START-----------------------------------

function [sol, outs] = solveWirtFlow(A, At, b0, x0, opts)
    innerOpts = struct;
    innerOpts.maxIters = opts.maxIters;
    innerOpts.maxTime = opts.maxTime;
    innerOpts.tol = opts.tol;
    innerOpts.verbose = opts.verbose;
    innerOpts.recordTimes = opts.recordTimes;
    innerOpts.recordResiduals = opts.recordResiduals;
    innerOpts.recordMeasurementErrors = opts.recordMeasurementErrors;
    innerOpts.recordReconErrors = opts.recordReconErrors;
    innerOpts.xt = opts.xt;

    innerOpts.searchMethod = opts.searchMethod;
    innerOpts.betaChoice = opts.betaChoice;

    [sol, outs] = gradientDescentSolver(A, At, x0, b0, @updateObjective, innerOpts);

    function [f, gradf] = updateObjective(~, ~)
        f = @(z) 0.5 * norm(abs(z).^2 - b0.^2)^2;
        gradf = @(z) (abs(z).^2 - b0.^2) .* z;
    end
end


function [J, grad] = linearRegCostFunction(X, y, theta, lambda)
%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear
%regression with multiple variables
%   [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the
%   cost of using theta as the parameter for linear regression to fit the
%   data points in X and y. Returns the cost in J and the gradient in grad

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost and gradient of regularized linear
%               regression for a particular choice of theta.
%
%               You should set J to the cost and grad to the gradient.
%

h = X*theta;
hy = h-y;
J = sum(hy.^2)/(2*m) + lambda*sum(theta(2:end).^2)/(2*m);
hyrep = repmat(hy,[1 size(X,2)]);
grad = sum(hyrep.*X,1)'/m;

grad(2:end) = grad(2:end) + lambda.*theta(2:end)/m;

% =========================================================================

grad = grad(:);

end


function cdf = beta_binomial_cdf ( x, a, b, c )

%*****************************************************************************80
%
%% BETA_BINOMIAL_CDF evaluates the Beta Binomial CDF.
%
%  Discussion:
%
%    A simple summing approach is used.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer X, the argument of the CDF.
%
%    Input, real A, B, parameters of the PDF.
%    0.0D+00 < A,
%    0.0D+00 < B.
%
%    Input, integer C, a parameter of the PDF.
%    0 <= C.
%
%    Output, real CDF, the value of the CDF.
%
  if ( x < 0 )

    cdf = 0.0;

  elseif ( x < c )

    cdf = 0.0;
    for y = 0 : x
      pdf = beta ( a + y, b + c - y ) / ( ( c + 1 ) ...
        * beta ( y + 1,  c - y + 1 ) * beta ( a, b ) );
      cdf = cdf + pdf;
    end

  elseif ( c <= x )

    cdf = 1.0;

  end

  return
end


N = 25;
x = 0:N-1;
H = zeros(N,1);

for i = 1:N
    if i == (N+1)/2
        H(i) = 1/6;
    else
        H(i) = sin(pi*(i-(N+1)/2)/6)/(pi*(i-(N+1)/2));
    end;
end;
H = H.*blackman(N);
newN = 1000;
H = [H',zeros(1,newN-length(H))];
Y = fft(H);
Y = fftshift(Y);
W = calculateDiscreteFrequencyIndex(length(Y));
subplot(2,1,1);
%plot(W,abs(Y));
plot(W,10*log10(abs(Y)));
subplot(2,1,2);
plot(W,angle(Y));


function sp = mdp_span(W)

% mdp_span  Returns the span of W
%           sp(W) = max W(s) - min W(s)

% MDPtoolbox: Markov Decision Processes Toolbox
% Copyright (C) 2009  INRA
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
%    * Redistributions of source code must retain the above copyright notice,
%      this list of conditions and the following disclaimer.
%    * Redistributions in binary form must reproduce the above copyright notice,
%      this list of conditions and the following disclaimer in the documentation
%      and/or other materials provided with the distribution.
%    * Neither the name of the <ORGANIZATION> nor the names of its contributors
%      may be used to endorse or promote products derived from this software
%      without specific prior written permission.
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
% IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
% OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
% OF THE POSSIBILITY OF SUCH DAMAGE.

sp = max(W) - min(W);


function v=v_dlyapsq(a,b)
%V_DLYAPSQ Solves the discrete Lyapunov equation AV'VA' - V'V + BB' = 0
% V is upper triangular with real non-negative diagonal entries
% this is equivalent to v=chol(dlyap(a,b*b')) but better conditioned numerically

%      Copyright (C) Mike Brookes 2002
%      Version: $Id: v_dlyapsq.m 10865 2018-09-21 17:22:45Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[q,s]=schur(a');
[q,s]=rsf2csf(q,s);
[qd,r]=qr(b'*q,0);
% save r for testing
r0=r;
[m,n]=size(r);
u=zeros(n,n);
if m==1
   for i=1:n-1
      in=i+1:n;
      si=s(i,i);
      aa=sqrt(1-si*si');
      u(i,i)=r(1)/aa;
      u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(2:end))/(eye(n-i)-si'*s(in,in));
      r=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(2:end);
   end
   u(n,n)=r/sqrt(1-s(n,n)*s(n,n)');

else
   w=zeros(m,1); w(m)=1;
   em=eye(m);
   for i=1:n-m
      in=i+1:n;
      si=s(i,i);
      aa=sqrt(1-si*si');
      u(i,i)=r(1,1)/aa;
      u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(1,2:end))/(eye(n-i)-si'*s(in,in));
      vv=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(1,2:end);
      rr=zeros(m,n-i);
      rr(1:m-1,:)=r(2:end,2:end);
      [qq,r]=qrupdate(em,rr,w,vv');
   end
   for i=n-m+1:n-1
      in=i+1:n;
      si=s(i,i);
      aa=sqrt(1-si*si');
      u(i,i)=r(1,1)/aa;
      u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(1,2:end))/(eye(n-i)-si'*s(in,in));
      vv=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(1,2:end);
      rr=zeros(n-i+1,n-i);
      rr(1:n-i,:)=r(2:end,2:end);
      [qq,rr]=qrupdate(eye(n-i+1),rr,w(m-n+i:end),vv');
      r=rr(1:n-i,:);
   end

   u(n,n)=r/sqrt(1-s(n,n)*s(n,n)');

end

v=triu(qr(u*q'));
dv=diag(v);
ix=dv~=0;
v(ix,:)=diag(abs(dv(ix))./dv(ix))*v(ix,:);
if isreal(a) & isreal(b)
   v=real(v);
end


function x = block_levinson(y, L)
%BLOCK_LEVINSON Block Levinson recursion for efficiently solving
%symmetric block Toeplitz matrix equations.
%   BLOCK_LEVINSON(Y, L) solves the matrix equation T * x = y, where T
%   is a symmetric matrix with block Toeplitz structure, and returns the
%   solution vector x. The matrix T is never stored in full (because it
%   is large and mostly redundant), so the input parameter L is actually
%   the leftmost "block column" of T (the leftmost d columns where d is
%   the block dimension).

%   Author: Keenan Pepper
%   Last modified: 2007-12-23

%   References:
%     [1] Akaike, Hirotugu (1973). "Block Toeplitz Matrix Inversion".
%     SIAM J. Appl. Math. 24 (2): 234-241

s = size(L);
d = s(2);                 % Block dimension
N = s(1) / d;             % Number of blocks

B = reshape(L, [d,N,d]);  % This is just to get the bottom block row B
B = permute(B, [1,3,2]);  % from the left block column L
B = flipdim(B, 3);
B = reshape(B, [d,N*d]);

f = L(1:d,:)^-1;          % "Forward" block vector
b = f;                    % "Backward" block vector
x = f * y(1:d);           % Solution vector

for n = 2:N
    ef = B(:,(N-n)*d+1:N*d) * [f;zeros(d)];
    eb = L(1:n*d,:)' * [zeros(d);b];
    ex = B(:,(N-n)*d+1:N*d) * [x;zeros(d,1)];
    A = [eye(d),eb;ef,eye(d)]^-1;
    fn = [[f;zeros(d)],[zeros(d);b]] * A(:,1:d);
    bn = [[f;zeros(d)],[zeros(d);b]] * A(:,d+1:end);
    f = fn;
    b = bn;
    x = [x;zeros(d,1)] + b * (y((n-1)*d+1:n*d) - ex);
end


%	nufft_tune_gauss
%	tune the FWHM for gaussian interpolation in 1D NUFFT
%	to minimize the worst-case error

if ~isvar('err_gauss')
	N = 2^8;
	K_N = 2;				% oversampling factor
	Jlist = [2:16];
	Plist = linspace(0.2, 0.4, 101);	% sig = parameter * sqrt(J)
	rlist = [0:20]'/40;			% fractions of gamma

	err_gauss.zn = zeros([length(rlist) length(Jlist) length(Plist)]);
	err_gauss.ft = zeros([length(rlist) length(Jlist) length(Plist)]);

	for jj=1:length(Jlist)
		J = Jlist(jj);	printf('J=%d', J)

		K = K_N * N;
		gam = 2*pi/K;
		om = gam * rlist;

		%
		%	gaussian with various FWHM
		%
		for ii=1:length(Plist)
			sig = Plist(ii) * sqrt(J);
			[Gfunc, Gfunc_ft] = nufft_gauss('inline', J, sig);

			%
			%	interpolator worst-case error
			%
		        err_gauss.ft(:,jj,ii) = nufft1_error(om, N, J, K, ...
				Gfunc, Gfunc_ft);
		        err_gauss.zn(:,jj,ii) = nufft1_error(om, N, J, K, ...
				Gfunc);
		end
	end
end

emax.zn = squeeze( max(err_gauss.zn, [], 1) );		% [M,J,F] -> [J,F]
[emax.zn, ibest.zn] = min(emax.zn, [], 2);		% [J,F] -> J
pbest.zn = Plist(ibest.zn);

emax.ft = squeeze( max(err_gauss.ft, [], 1) );		% [M,J,F] -> [J,F]
[emax.ft, ibest.ft] = min(emax.ft, [], 2);		% [J,F] -> J
pbest.ft = Plist(ibest.ft);

%	plot best sig vs J (on log scale!)
clf
if 1
	log_J = log(Jlist);
	log_sig.zn = log(pbest.zn .* sqrt(Jlist));
	log_sig.ft = log(pbest.ft .* sqrt(Jlist));

	subplot(131)
	plot(log_J, log_sig.zn, 'co', log_J, log_sig.ft, 'yx'), axis tight
	lsline, legend('zn', 'ft')
	xlabel log(J), ylabel 'log(sig best)'
	pol = polyfit(log_J, log_sig.zn, 1)
	printf('\\sigma \\approx %g * J^{%g}', exp(pol(2)), pol(1))
	pol = polyfit(log_J, log_sig.ft, 1)
	printf('\\sigma \\approx %g * J^{%g}', exp(pol(2)), pol(1))
end

%
%	plot emax vs J
%
if 1
	subplot(132)
	semilogy(Jlist, emax.zn, 'c-o', Jlist, emax.ft, 'y-x')
	xlabel J, ylabel E_{max}
        title(sprintf('Maximum error for K/N=%g', K/N))
	legend('zn', 'ft')

	subplot(133)
	plot(emax.zn ./ emax.ft), axis tight, title 'emax: zn / ft'
%	savefig c 'fig_?'
end

%
%	save both sets of tuned sigma's to "private" file
%
if 1
	Jgauss2 = Jlist;
	Sgauss2.zn = pbest.zn .* sqrt(Jlist);		% tuned sig zn
	Sgauss2.ft = pbest.ft .* sqrt(Jlist);		% tuned sig ft
	save nufft_gauss2 Jgauss2 Sgauss2
	disp('MOVE TO private!')
end


%% B-A Scale-Free Network Generation and Visualization
% *By Mathew Neil George*

%% Description and Cautions
% The *SFNG* m-file is used to simulate the B-A algorithm and returns scale-free
% networks of given node sizes. Understanding the B-A algorithm is key
% to using this code to its fullest. Due to Matlab resource limitations, it may not be
% possible to generate networks much larger than 15000 nodes, and increasing the
% *mlinks* variable increases processing time severely. This code was
% developed so that one could generate a network of small size, and then
% use that network as a seed to build a greater sized network, continuing
% this process until the actual desired network size is reached. This is for
% processor and time management purposes. However, realize that the initial
% seed does not have to have scale-free properties, while the later seeds
% may happen to have these properties. Therefore, it is prudent not to make the
% initial seed size much larger than a few nodes (most commonly 5
% interconnected nodes). In addition, the *mlinks* should be kept constant
% throughout the creation of the scale-free network.
%
% The *PLplot* m-file takes a scale-free network in adjacency matrix format
% and draws a best fit line to the frequency of degrees distribution of the
% nodes. Degree is the number of links that connect to and from a single node
% For scale-free networks, the frequency of degrees distribution forms a
% power-law curve, with an exponent usually between -2 and -3. This code is
% designed to allow only non-zero frequencies to be graphed in log-log format.
% The function returns the equation of the power-law fit in a cfit variable.
%
% The *CNet* m-file function creats a network graph using the *gplot*
% function with circular coordinates. It allows for a simple, yet
% intuitive, visualization of a given network.

%% Parameters
% *SFNG*
%
% * *Nodes* is the desired network size, including the seed network size
%   (i.e. Nodes minus seed network size equals the number of nodes to be
%   added).
%
% * *mlinks* controls the number of links a new node can make to the existing
%   network nodes.
%
% * *seed* is the original network to which the B-A algorithm links
%   additional nodes with a specific preferential attachment procedure.
%   This undirected adjacency matrix can be created manually, or one could
%   use the *Adjacency Matrix GUI*. Each node must have at least one link.
%   The *seed* variable can be replaced with a developed scale-free network
%   to generate a larger one. Make sure the new *Nodes* variable is greater
%   than the size of the *seed* network.
%
% *PLplot*
%
% * *Net* is the input network which is to be graphed.
%
% *CNet*
%
% * *Net* is the input network which is to be graphed.
%
% Note that variables *Nodes*, *mlinks*, and *size* must be whole numbers and
% variables *seed* and *Net* must be undirected adjacency matrices. The
% diagonol elements of any adjacency matrix used with these functions must
% all be zero.

%% Sample Output
% Here is a small example to demonstrate how to use the code. This code
% creates a seed network of 5 nodes, generates a scale-free network of 300 nodes from
% the seed network, and then performs the two graphing procedures.
seed =[0 1 0 0 1;1 0 0 1 0;0 0 0 1 0;0 1 1 0 0;1 0 0 0 0]
Net = SFNG(300, 1, seed);
PL_Equation = PLplot(Net)
CNet(Net)

%% References
% One explanation of the B-A Algorithm can be found on this PDF website
% http://arxiv.org/PS_cache/cond-mat/pdf/0107/0107420.pdf
%
% Undirected Adjecency Matrices are defined on Wikipedia.org
% http://en.wikipedia.org/wiki/Adjacency_matrix
%
% The *Adjacency Matrix GUI* file by Steve Chuang can be found on the Matlab File Exchange
% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=6937&objectType=file

%% Acknowledgements
% Special thanks to Mark Ballerini with the Massapequa High School Science
% Research Program and Zoltan Dezso at the University of Notre Dame for
% their invaluable help in researching network theory as well as to my
% family for providing motivation and encouragement in pursuing science.


function geometry_test0202 ( )

%*****************************************************************************80
%
%% TEST0202 tests CYLINDER_POINT_INSIDE_3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  dim_num = 3;
  test_num = 6;

  inside_test = [ 0, 1, 0, 0, 1, 1 ];
  p_test = [ ...
      4.0,   0.5,  0.0; ...
     -0.5,  -1.0,  0.0; ...
      4.0,   6.0,  0.0; ...
      0.75, -10.0, 0.0; ...
      0.0,   0.0,  0.0; ...
      0.25,  1.75, 0.0 ]';
  p1 = [ 0.0, -2.0, 0.0 ];
  p2 = [ 0.0,  2.0, 0.0 ];
  r = 1.0;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST0202\n' );
  fprintf ( 1, '  CYLINDER_POINT_INSIDE_3D determines if a point is\n' );
  fprintf ( 1, '  inside a cylinder.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Radius R = %f\n', r );
  fprintf ( 1, '  Center of bottom disk = %10f  %10f  %10f\n', p1(1:dim_num) );
  fprintf ( 1, '  Center of top disk =    %10f  %10f  %10f\n', p2(1:dim_num) );

  for test = 1 : test_num

    p(1:dim_num) = p_test(1:dim_num,test);

    fprintf ( 1, '\n' );
    fprintf ( 1, '  P =    %10f  %10f  %10f\n', p(1:dim_num) );

    inside = cylinder_point_inside_3d ( p1, p2, r, p );

    fprintf ( 1, '  INSIDE (computed) = %d\n', inside );
    fprintf ( 1, '  INSIDE (exact) =    %d\n', inside_test(test) );

  end

  return
end


function quad_mesh_test02 ( )

%*****************************************************************************80
%
%% QUAD_MESH_TEST02 tests AREA_Q4_MESH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUAD_MESH_TEST02\n' );
  fprintf ( 1, '  AREA_Q4_MESH computes the area of each element\n' );
  fprintf ( 1, '  in a Q4 mesh.\n' );

  [ node_num, element_num, hole_num ] = example2_q4_mesh_size ( );

  [ node_xy, element_node, element_neighbor ] = example2_q4_mesh ( ...
    node_num, element_num );

  [ element_area, mesh_area ] = area_q4_mesh ( node_num, element_num, ...
    node_xy, element_node );

  r8vec_print ( element_num, element_area, '  Element areas:' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '   Mesh =   %f\n', mesh_area );

  return
end


function s=norm(a,P)
%norm: Matrix or vector norm of vector/matrix of mp-type

%     For matrices...
%       NORM(X) is the largest singular value of X, max(svd(X)).
%       NORM(X,2) is the same as NORM(X).
%       NORM(X,1) is the 1-norm of X, the largest column sum,
%                       = max(sum(abs(X))).
%       NORM(X,inf) is the infinity norm of X, the largest row sum,
%                       = max(sum(abs(X'))).
%       NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
%       NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
%
%     For vectors...
%       NORM(V,P) = sum(abs(V).^P)^(1/P).
%       NORM(V) = norm(V,2).
%       NORM(V,inf) = max(abs(V)).
%       NORM(V,-inf) = min(abs(V)).
%
%     See also COND, RCOND, CONDEST, NORMEST.

if nargin<2,P=2;end
if isa(P,'mp')
 error(['Second parameter should not be of mp-type'])
end
if min(size(a))==1
 %is a vector
 if isinf(P) | strcmp(lower(P),'inf')
  if P>0
   s=max(abs(a));
  else
   s=min(abs(a));
  end
  return
 end
 A=max(abs(a(:)));a=a/A;
 if P==2
  %naive implementation
  s=A*sqrt(sum(a.*a));
 else
  s=A*(sum(a.^P))^(1/P);
 end
else
 %is a matrix
 if isinf(P) | strcmp(lower(P),'inf')
  s=max(sum(abs(a')));
  return
 end
 if ischar(P)
  if strcmp(lower(P),'fro')
   s=sqrt(sum(diag(a'*a)));
  else
   error(['Second parameter is not recognized as an option: ' P])
  end
  return
 end
 switch P
  case 1
   s=max(sum(abs(a)));
  case 2
   s=max(svd(a));
  otherwise
   error(['NORM(X,P) is available for matrix X only if P is 1, 2, inf or ' setstr(39) 'fro' setstr(39) '.'])
 end
end


function xcovar=covarf(x,cov_wsize)

%%% covarf: computes covariance of a signal.
%%% covarf(X), if X is a vector, returns the variance.
%%% For matrices, where each row is an observation, and each column a variable,
%%% covarf(X) is the covariance matrix.
%%% diag(covarf(X)) is a vector of variances for each column.
%%% sqrt(diag(covarf(X))) is a vector of standard deviations.
%%% wsize should be odd.

%%% Author : B. K. SHREYAMSHA KUMAR
%%% Created on 15-02-2012.
%%% Updated on 15-02-2012.

tr=x-repmat(mean(x),cov_wsize,1);
xcovar=tr'*tr/(cov_wsize-1);


function [all_theta] = oneVsAll(X, y, num_labels, lambda)
%ONEVSALL trains multiple logistic regression classifiers and returns all
%the classifiers in a matrix all_theta, where the i-th row of all_theta
%corresponds to the classifier for label i
%   [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels
%   logisitc regression classifiers and returns each of these classifiers
%   in a matrix all_theta, where the i-th row of all_theta corresponds
%   to the classifier for label i

% Some useful variables
m = size(X, 1);
n = size(X, 2);

% You need to return the following variables correctly
all_theta = zeros(num_labels, n + 1);

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the following code to train num_labels
%               logistic regression classifiers with regularization
%               parameter lambda.
%
% Hint: theta(:) will return a column vector.
%
% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use
%       whether the ground truth is true/false for this class.
%
% Note: For this assignment, we recommend using fmincg to optimize the cost
%       function. It is okay to use a for-loop (for c = 1:num_labels) to
%       loop over the different classes.
%
%       fmincg works similarly to fminunc, but is more efficient when we
%       are dealing with large number of parameters.
%
% Example Code for fmincg:
%
%     % Set Initial theta
%     initial_theta = zeros(n + 1, 1);
%
%     % Set options for fminunc
%     options = optimset('GradObj', 'on', 'MaxIter', 50);
%
%     % Run fmincg to obtain the optimal theta
%     % This function will return theta and the cost
%     [theta] = ...
%         fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
%                 initial_theta, options);
%

for c = 1:num_labels

% Set initial theta
initial_theta=zeros(n+1,1);
%initial_theta=zeros(num_labels, n + 1);

% Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 50);

% Run fmincg to obtain the optimal theta
% This function will return theta and the cost
[theta]=fmincg(@(t)(lrCostFunction(t,X, (y == c), lambda)), initial_theta, options);

% Updating theta to overall all_theta
if (c==1)
	history_theta=theta';
else
	history_theta=[history_theta; theta'];
end

end

all_theta=history_theta;

% =========================================================================

end


function triangle_symq_rule_test02 ( degree, numnodes, vert1, vert2, vert3 )

%*****************************************************************************80
%
%% TRIANGLE_SYMQ_RULE_TEST02 calls TRIASYMQ for a quadrature rule of given order and region.
%
%  Licensing:
%
%    This code is distributed under the GNU GPL license.
%
%  Modified:
%
%    27 June 2014
%
%  Author:
%
%    Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Hong Xiao, Zydrunas Gimbutas,
%    A numerical algorithm for the construction of efficient quadrature
%    rules in two and higher dimensions,
%    Computers and Mathematics with Applications,
%    Volume 59, 2010, pages 663-676.
%
%  Parameters:
%
%    Input, integer DEGREE, the desired total polynomial degree exactness
%    of the quadrature rule.  0 <= DEGREE <= 50.
%
%    Input, integer NUMNODES, the number of nodes to be used by the rule.
%
%    Input, real VERT1(2), VERT2(2), VERT3(2), the
%    vertices of the triangle.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TRIANGLE_SYMQ_RULE_TEST02\n' );
  fprintf ( 1, '  Symmetric quadrature rule for a triangle.\n' );
  fprintf ( 1, '  Polynomial exactness degree DEGREE = %d\n', degree );

  area = triangle_area ( vert1, vert2, vert3 );
%
%  Retrieve and print a symmetric quadrature rule.
%
  [ rnodes, weights ] = triasymq ( degree, vert1, vert2, vert3, numnodes );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  NUMNODES = %d', numnodes );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     J      W               X               Y\n' );
  fprintf ( 1, '\n' );
  for j = 1 : numnodes
    fprintf ( 1, '  %4d  %14.6g  %14.6g  %14.6g\n', ...
      j, weights(j), rnodes(1,j), rnodes(2,j) );
  end

  d = sum ( weights(1:numnodes) );

  fprintf ( 1, '   Sum  %14.6g\n', d );
  fprintf ( 1, '  Area  %14.6g\n', area );

  return
end


function X = randnd(beta,varargin)
%% X = randnd(beta,varargin)
% This function is a "decorator" for the Matlab in-build 'randn' function.
% It takes an additional first argument (beta) which shapes the spectral
% characteristic of the data (in all dimensions) as f^beta. The output data
% is scaled to zero mean and unit standard deviation.
%
% For help on 'varargin' go to Matlab help for the 'randn' function.
%
% EXAMPLE 1 - Input robustness
% A = randnd(-1,[2^5+1 1]); % Handle odd dimensionality
% A = randnd((rand-0.5)*4,[134 12 1 1 1 26 1 9]); % Handle large number of dimentions
% A = randnd(-1,[1 0 3]); % Handle 0's
% A = randnd(2,[1 1 1 256]); % Handle leading singleton dimensions
%
% EXAMPLE 2 - Pink map
% A = randnd(-1,2^8); % Generate 256 x 256 grid with random 1/f (pink) noise
% contourf(A,'edgecolor','none'); axis square; % Display it as a contour plot
%
% EXAMPLE 3 - Brownian cube
% A = randnd(-2,[2^4 2^4 2^4]); % Generate 16 x 16 x 16 cube of f^-2 (Brownian) noise
% [X,Y,Z] = meshgrid(1:2^4); % Generate 3d meshgrid
% scatter3(X(:),Y(:),Z(:),100,A(:),'filled');
% axis vis3d; axis off;
%
% EXAMPLE 4 - Single blue noise
% p = single(magic(10)); % Single precision matrix of interest
% A = randnd(1,size(p),'like',p); % Generate f (blue) noise 'like' p
% isa(A,'single') % X is also a single precision random number
%
% EXAMPLE 5 - Proof that beta scales power spectral density correctly
% beta = -2;
% A = randnd(beta,[1 2^11]);
% Afft = abs(fft(A.^2)); % Get the magnitude of power (i.e. signal^2) spectrum
% Afft = Afft(2:length(Afft)/2); % Get the spectrum between DC and Nyquist
% k = 1:length(Afft); % Create wavenumber (frequency) vector
% P = polyfit(log(k),log(Afft),1); % Fit a straight line to the loglog plot
% loglog(k,Afft,'.',k,exp(P(2))*k.^P(1),'-'); grid on; % Plot on loglog axis
% xlim([min(k) max(k)]); title(['Beta = ',num2str(beta),'; Slope = ',num2str(P(1))]);
%
%
% Based on similar functions by Jon Yearsley and Hristo Zhivomirov
% Written by Marcin Konowalczyk
% Timmel Group @ Oxford University

%% Parse the input
narginchk(0,Inf); nargoutchk(0,1);

if nargin < 2 || isempty(beta); beta = 0; end % Default to white noise
assert(isnumeric(beta) && isequal(size(beta),[1 1]),'''beta'' must be a number');
assert(-2 <= beta && beta <= 2,'''beta'' out of range'); % Put on reasonable bounds

%% Generate N-dimensional white noise with 'randn'
X = randn(varargin{:});
if isempty(X); return; end; % Usually happens when size vector contains zeros

% Squeeze prevents an error if X has more than one leading singleton dimension
% This is a slight deviation from the pure functionality of 'randn'
X = squeeze(X);

% Return if white noise is requested
if beta == 0; return; end;

%% Generate corresponding N-dimensional matrix of multipliers
N = size(X);
% Create matrix of multipliers (M) of X in the frequency domain
M = [];
for j = 1:length(N)
    n = N(j);

    if (rem(n,2)~=0) % if n is odd
        % Nyquist frequency bin does not show up in odd-numbered fft
        k = ifftshift(-(n-1)/2:(n-1)/2);
    else
        k = ifftshift(-n/2:n/2-1);
    end

    % Spectral multipliers
    m = (k.^2)';

    if isempty(M);
        M = m;
    else
        % Create the permutation vector
        M_perm = circshift(1:length(size(M))+1,1,2);
        % Permute a singleton dimension to the beginning of M
        M = permute(M,M_perm);
        % Add m along the first dimension of M
        M = bsxfun(@plus,M,m);
    end
end
clear j M_perm k n m
% Reverse M to match X (since new dimensions were being added form the left)
M = permute(M,length(size(M)):-1:1);
assert(isequal(size(M),size(X)),'Bad programming error'); % This should never occur

% Shape the amplitude multipliers by (beta/2) which corresponds to shaping
% the power by beta
M = M.^(beta/2);

% Set the DC component to zero
M(1,1) = 0;

%% Multiply X by M in frequency domain
Xstd = std(X(:));
Xmean = mean(X(:));
X = real(ifftn(fftn(X).*M));

% Force zero mean unity standard deviation
X = X - mean(X(:));
X = X./std(X(:));

% Restore the standard deviation and mean from before the spectral shaping.
% This ensures the random sample from randn is truly random. After all, if
% the mean was always exactly zero it would not be all that random.
X = X + Xmean;
X = X.*Xstd;
end


function n = planeNormal(plane)
%PLANENORMAL Compute the normal to a plane
%
%   N = planeNormal(PLANE)
%   compute the normal of the given plane
%   PLANE : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]
%   N : [dx dy dz]
%
%   See also
%   geom3d, planes3d, createPlane
%

%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 17/02/2005.
%

%   HISTORY
%   15/04/2013 Extended to N-dim planes by Sven Holcombe

% plane normal
outSz = size(plane);
outSz(2) = 3;
n = zeros(outSz);
n(:) = crossProduct3d(plane(:,4:6,:), plane(:, 7:9,:));


% demo for SINEFIT program.
% % Written by Dr Chen YangQuan <yqchen@ieee.org>
echo on

% test codes:
A0=2;sigma=2;
omega=2*pi*2; % f=2 Hz
theta0=pi/2;
t=0:.005:2;
dn=sigma*randn(size(t));
s0=A0*sin(omega*t + theta0) + dn;
t0=0;Ts=0.005;

%Assume frequency f = 2.5 Hz which is 25% larger than the theoretical value of 2 Hz.
% Calling [Ahat,Theta,Omega,RMS]=sinefit(s0,0.4,0,0.005)
pause
[Ahat,Theta,Omega,RMS]=sinefit(s0,1/2.5,0,0.005);
%gives the filtering results shown in Fig. 4.

pause

%Now, increase sigma from 1 to 2. The filtering
%results are shown in Fig. 5 by calling  [Ahat,Theta,Omega,RMS]=sinefit(s0,1/1.5,0,0.005).
[Ahat,Theta,Omega,RMS]=sinefit(s0,1/1.5,0,0.005);
%Note that in this case, the frequency f = 1:5 Hz which is 25% lower than the theoretical value
%of 2 Hz. It can be concluded that the optimal feature extraction can be used as a means of
%filtering.


function [LR, HR, kernel, sigma] = degradation_model(HR, scale)

% kernel
ksize  = 15;
theta  = pi*rand(1);
l1     = 0.1+9.9*rand(1);
l2     = 0.1+(l1-0.1)*rand(1);
kernel = anisotropic_Gaussian(ksize,theta,l1,l2); % double
kernel = single(kernel);

% noise level
sigma_max = 75;
sigma = single(sigma_max*rand(1)/255); % single

% HR image
HR  = modcrop(HR, scale); % double

% xxxxxxxxxxxxxx degradation model xxxxxxxxxxxxxxxxxxxxxx
% you can change to your own degradation model

blurry_HR  = imfilter(HR,double(kernel),'replicate');
downsampled_HR = imresize(blurry_HR, 1/scale,'bicubic');
downsampled_HR = im2single(im2uint8(downsampled_HR));

noise  = single(randn(size(downsampled_HR),'single')*sigma);
LR = downsampled_HR + noise;

kernel = single(kernel);
% xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

end


function SR = getInitialSRImage(W, LRImages, photoParams)
% GETINITIALSRIMAGE Initial guess for super-resolved image
%   GETINITIALSRIMAGE computes a rough estimate for the super-resolved
%   image from given model parameters.
%
%   X = GETINITIALSRIMAGE(W, Y, PHOTOPARAMS) computes the "average image" X
%   as initial guess based on the system matrix W, the low-resolution data
%   Y and the photometric parameters PHOTOPARAMS.
%
%   See David P. Capel, Image Mosaicing and Super-resolution, PhD thesis,
%   2001 for details.

    if nargin > 2 && ~isempty(photoParams)
        numFrames = length(photoParams.mult);
        numLRPixel = length(LRImages) / numFrames;

        % Compose photometric parameters into additive and multiplicative term.
        bm = zeros(size(LRImages));
        ba = zeros(size(LRImages));
        for k = 1:numFrames
            bm( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(photoParams.mult(k), numLRPixel, 1);
            ba( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(photoParams.add(k), numLRPixel, 1);
        end
        bm_invmat = spdiags(1./bm(:), 0, length(bm), length(bm));

        % Compute "average image" from low-resolution observtions, system
        % matrix and phtometric parameters.
        SR =  (W' * bm_invmat * (LRImages - ba .* ones(size(LRImages)))) ./ (sum(W, 1)' + 1e-4);
    else
        % Compute "average image" without photometric parameters
        SR = (W' * LRImages) ./ (sum(W, 1)' + 1e-4);
    end


function [out] = baseflow_3(S,Smax)
%baseflow_3

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

% Flux function
% ------------------
% Description:  Empirical non-linear outflow from a reservoir
% Constraints:  None specified
% @(Inputs):    S    - current storage [mm]
%               Smax - maximum contributing storage [mm]

out = Smax^(-4)/(4)*(S^5);

end


function crackFVMP2
%% CRACK Problem
%
% crack solves the Poisson equation $-\Delta u =f$ in $\Omega$ and $u =
% g_D$ on $\partial \Omega$ in a crack domain
% $\Omega=\{|x|+|y|<1\}\backslash \{0<= x <=1, y=0\}$
%  using adaptive finite element method (AFEM). We choose f=1 and g_D such
%  that the exact solution is $u = r^{\beta}\sin(\beta\theta)-0.25r^2,
%  \beta = 1/2$ in the polar coordinate.
%
% EXAMPLE
%
%    crack
%
% See also  crack_performance, Lshape
%
% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.

close all;clc;clear;
%% Parameters
maxN = 2e3;     theta = 0.5;    maxIt = 50;
N = zeros(maxIt,1); err = zeros(maxIt,3);
%%  Generate an initial mesh
node = [1,0; 0,1; -1,0; 0,-1; 0,0; 1,0];        % nodes
elem = [5,1,2; 5,2,3; 5,3,4; 5,4,6];            % elements
elem = label(node,elem);                        % label the mesh
bdEdge = setboundary(node,elem,'Dirichlet');    % Dirichlet boundary condition
showmesh(node,elem);                            % plot mesh
findelem(node,elem);                            % plot element indices
findnode(node,1:5);                             % plot node indices
findedge(node,[1 5; 5 6],1);                    % plot the crack edge
text(node(6,1)+0.05,node(6,2)+0.075,int2str(6), ...
     'FontSize',14,'FontWeight','bold');
%%
% node 1 and node 6 are the same point (1,0)

%%  Get a fine mesh by uniform bisection
for k = 1:2
    [node,elem,bdEdge] = uniformbisect(node,elem,bdEdge);
end
clf; showmesh(node,elem);
%% Set up PDE data
pde.f = @f;
pde.exactu = @exactu;
pde.g_D = @exactu;
pde.Du=@Du;
pde.d=[];
%%  Adaptive Finite Element Method
% *SOLVE* -> *ESTIMATE* -> *MARK* -> *REFINE*
for k = 1:maxIt
    % Step 1: SOLVE
   [u,A,~,~,edge] = PoissonP2FVM(node,elem,[],@pde.f,@pde.g_D);
    % Plot mesh and solution
    figure(1);  showresult(node,elem,u(1:size(node,1)),[-7,12]);
    % Step 2: ESTIMATE
   % eta = estimaterecovery(node,elem,u); % recovery type % need eta^2 for mark
    eta = recoverFlux2(node,elem,pde,bdEdge,u);
    % Record error and number of vertices
   uI = pde.exactu([node; (node(edge(:,1),:)+node(edge(:,2),:))/2]);
   err(k,1) = sqrt((u-uI)'*A*(u-uI));
   err(k,2) = getL2error(node,elem,@exactu,u);
   err(k,3) = getH1error(node,elem,@pde.Du,u);
    N(k) = size(node,1);
    if (N(k)>maxN), break; end
    % Step 3: MARK
    markedElem = mark(elem,eta,theta);
    % Step 4: REFINE
    [node,elem,bdEdge] = bisect(node,elem,markedElem,bdEdge);
end

%% Plot convergence rates
N= N(1:k);
erruIuh= err(1:k,1); errL2 = err(1:k,2); errH1 = err(1:k,3);
figure(2);
r1 = showrate(N,erruIuh,5,'-*');
hold on;
r2 = showrate(N,errL2,5,'k-+');
r3 = showrate(N,errH1,10,'r-+');
legend('||Du_I-Du_h||',['cN^{' num2str(r1) '}'], ...
       '||u-u_h||',['cN^{' num2str(r2) '}'], ...
       '||Du-Du_h||',['cN^{' num2str(r3) '}'], ...
       'LOCATION','Best');
%%
% Using AFEM, we obtain optimal rate of convergence the error in the energy
% norm ($N^{-0.5}$) and in the $L^2$ norm ($N^{-1}$).
end % End of function CRACK

%%  Data of CRACK
function z = f(p)   % load data (right hand side function)
z = ones(size(p,1),1);
end

function z = exactu(p) % exact solution
r = sqrt(sum(p.^2,2));
z = sqrt(0.5*(r-p(:,1)))-0.25*r.^2;
end

function z = Du(p) % derivative of the exact solution
r = sqrt(sum(p.^2,2));
z(:,1) = (p(:,1)./r-1)./sqrt(8*(r-p(:,1)))-0.5*p(:,1); % u_x
z(:,2) = p(:,2)./r./sqrt(8*(r-p(:,1)))-0.5*p(:,2);     % u_y
end


function y = circle_characteristic ( m, n, x )

%*****************************************************************************80
%
%% CIRCLE_CHARACTERISTIC evaluates the characteristic function of a circle.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 May 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points to check.
%
%    Input, real X(M,N), the coordinates of points to be checked.
%
%    Output, real Y(N,1), is 1 if the point is inside, 0 otherwise.
%
  y = sqrt ( sum ( x.^2, 1 ) );

  y = y';

  y = ( y < 1.0 );

  return
end


function r8plu_inverse_test ( )

%*****************************************************************************80
%
%% R8PLU_INVERSE_TEST tests R8PLU_INVERSE;
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  n = 5;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8PLU_INVERSE_TEST\n' );
  fprintf ( 1, '  R8PLU_INVERSE determines the inverse of a matrix\n' );
  fprintf ( 1, '  from its compressed PLU factors.\n' );
  fprintf ( 1, '  Using initial random number seed = %d\n', seed );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Matrix order N = %d\n', n );
%
%  Set the matrix.
%
  [ a, seed ] = r8mat_uniform_01 ( n, n, seed );

  r8mat_print ( n, n, a, '  The matrix A:' );
%
%  Factor the matrix.
%
  [ pivot, lu, info ] = r8mat_to_r8plu ( n, a );

  if ( info ~= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'TEST0852 - Fatal error!\n' );
    fprintf ( 1, '  R8MAT_TO_R8PLU declares the matrix is singular!\n' );
    fprintf ( 1, '  The value of INFO is %d\n', info );
    return
  end
%
%  Compute the inverse.
%
  b = r8plu_inverse ( n, pivot, lu );

  r8mat_print ( n, n, b, '  The inverse matrix B:' );
%
%  Compute the product C = A * B.
%
  c(1:n,1:n) = a(1:n,1:n) * b(1:n,1:n);

  r8mat_print ( n, n, c, '  The product matrix C = A * B:' );

  return
end


function g = year_to_golden_number ( y )

%*****************************************************************************80
%
%% YEAR_TO_GOLDEN_NUMBER returns the golden number of a Common year.
%
%  Discussion:
%
%    Nineteen solar years are very close to 235 lunations.  Calendars
%    that try to keep track of both the sun and moon often make use of
%    this fact, ascribed to the Greek astronomer Meton.
%
%    While trying to determine a formula for Easter, Dionysus Exiguus
%    symbolized the place of each year in its Metonic cycle by a
%    "golden number" between 1 and 19.  The numbering began with the
%    year 1 BC, assigned the golden number of 1.  The following year,
%    1 AD, got the golden number of 2, and after that it gets easier.
%
%    The same golden year calculation is done for years in the Julian
%    or Gregorian calendar.
%
%  Example:
%
%    Year  Golden Number
%
%      1 BC     1
%      1 AD     2
%      2 AD     3
%     18 AD    19
%     19 AD     1
%     20 AD     2
%   1066 AD     3
%   1900 AD     1
%   1919 AD     1
%   1938 AD     1
%   1957 AD     1
%   1976 AD     1
%   1995 AD     1
%   2014 AD     1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 April 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the year.
%
%    Output, integer G, the golden number, between 1 and 19.  This
%    records the position of the year in the 19 year Metonic cycle.
%
  if ( y == 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'YEAR_TO_GOLDEN_NUMBER - Fatal error!\n' );
    fprintf ( 1, '  Illegal input Y = 0.\n' );
    error ( 'YEAR_TO_GOLDEN_NUMBER - Fatal error!' );
  end
%
%  We assume that BC years come in as negative numbers, and that
%  the year before 1 AD is 1 BC.  So add 1 to any negative value
%  so that the arithmetic works.
%
  y2 = y_common_to_astronomical ( y );

  g = i4_wrap ( y2 + 1, 1, 19 );

  return
end


function R=return_Rt_matrix(alpha,beta,gamma,tx,ty,tz)

% Copyright (C) <2007>  <Francesc Moreno-Noguer, Vincent Lepetit, Pascal Fua>
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the version 3 of the GNU General Public License
% as published by the Free Software Foundation.
%
% 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/>.
%
% Francesc Moreno-Noguer, CVLab-EPFL, September 2007.
% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/

R(1,1)=cos(alpha)*cos(gamma)-cos(beta)*sin(alpha)*sin(gamma);
R(2,1)=cos(gamma)*sin(alpha)+cos(alpha)*cos(beta)*sin(gamma);
R(3,1)=sin(beta)*sin(gamma);
R(4,1)=0;

R(1,2)=-cos(beta)*cos(gamma)*sin(alpha)-cos(alpha)*sin(gamma);
R(2,2)=cos(alpha)*cos(beta)*cos(gamma)-sin(alpha)*sin(gamma);
R(3,2)=cos(gamma)*sin(beta);
R(4,2)=0;

R(1,3)=sin(alpha)*sin(beta);
R(2,3)=-cos(alpha)*sin(beta);
R(3,3)=cos(beta);
R(4,3)=0;

R(:,4)=[tx,ty,tz,1]';


function [lx, r0, ux] = get_rate_grid_boundaries( model, modparam, t, gamma)
% Retrive lower and upper boundaries for variance grid, based on first two moments of variance process
% model : see below
% modparam : container with each of the model parameters required
% t: time to maturity used for the vairance grid
% gamma: grid mult param, rougly centered around +/- gamma standard deviations of the variance process

if model == 1 %CIR  (eta, theta, Rho, Sigmar, r0)
    eta = modparam.eta; theta = modparam.theta; Sigmar = modparam.Sigmar; r0 = modparam.r0;

    mu_H = exp(-eta*t)*r0 + theta*(1-exp(-eta*t));
    sig2_H = Sigmar^2/eta*r0*(exp(-eta*t)-exp(-2*eta*t)) +theta*Sigmar^2/(2*eta)*(1-2*exp(-eta*t)+exp(-2*eta*t));

elseif model == 2 %VASICEK ( in SV this is STEIN STEIN / same moments as SCOTT) ... (eta, theta, Rho, Sigmar, r0)
    eta = modparam.eta; theta = modparam.theta; Sigmar = modparam.Sigmar; r0 = modparam.r0;

    mu_H = exp(-eta*t)*r0 + theta*(1-exp(-eta*t));
    sig2_H = Sigmar^2/(2*eta)*(1 -exp(-2*eta*t));

elseif model == 3 % Merton
    lambda = modparam.lambda;  Sigmar = modparam.Sigmar; r0 = modparam.r0;

    mu_H = r0 + lambda*t;
    sig2_H = Sigmar^2*t;

elseif model == 4 % Dothan
    a = modparam.a;  Sigmar = modparam.Sigmar; r0 = modparam.r0;

    mu_H = r0*exp(a*t);
    sig2_H = r0^2*exp(2*a*t)*(exp(Sigmar^2*t) - 1);

end

ux = mu_H + gamma*sqrt(sig2_H);  %variance grid upper bound
lx = mu_H - gamma*sqrt(sig2_H);

if model == 1 || model == 4
    lx = max(0.00001,lx);  %variance grid lower bound
end

end


function [fa,md,rd,ad] = dtiComputeFA(eigVal)
% Computes fractional anisotropy (FA) from tensor eigenvalues
%
%   [fa,md,rd,ad] = dtiComputeFA(eigVal)
%
% eigVal  XxYxZx3xN (or nx3xN) array of tensor eigenvalues (N is No. of subjects)
% fa      XxYxZxN (or nxN) array of FA values
% md      XxYxZxN (or nxN) array of Mean Diffusivity values (10^-^6 mm^2/sec)
% rd      XxYxZxN (or nxN) array of Radial Diffusivity values
%
% HISTORY:
% 2003.12.04 ASH (armins@stanford.edu) wrote it.
% 2003.12.04 RFD (bob@white.stanford.edu) added check to avoid divide-by-zero.
% 2004.02.19 ASH added extra dimension for subjects
% 2005.05.02 RFD: added option to pass in a dt6 array.
% 2006.07.12 ASH added indexed format
% 2006.07.13 RFD: fixed the features that ASH so rudely clobbered yesterday.
% 2007.02.28 RFD: added rd return arg.

% Programming:  Since this returns MD as an option, how about renaming the
% function.  Or giving it a flag about which to return.  Or something.

% Check inputs
if (ndims(eigVal)==2)
    Ind = 1;    % eigVal in indexed nx3 format
    eigVal = shiftdim(eigVal, -2);
elseif(ndims(eigVal)==3),
    if(size(eigVal,2)==3 && size(eigVal,3)~=3)
        Ind = 1;    % Data in indexed nx3xN format
        eigVal = shiftdim(eigVal, -2);
    else
        Ind = 2;    % Data in XxYx3 format
        eigVal = shiftdim(eigVal, -1);
    end
else
    Ind = 0;    % eigVal in XxYxZx3xN format
end
if (ndims(eigVal)<4 || ndims(eigVal)>5),
    error('Wrong input format');
end

if(size(eigVal,4) ~= 3),
    if(size(eigVal,4)==6)
        [eigVec, eigVal] = dtiEig(eigVal);
        clear eigVec;
    else
    error('Wrong input format');
    end
end

% Main
epsilon = 1e-10;  % Avoid division by zero

% Mean diffusivity
md = sum(eigVal,4)/3;

%
stdevDiffusivity = sqrt(sum((eigVal-repmat(md,[1,1,1,3,1])).^2,4));
normDiffusivity = sqrt(sum(eigVal.^2,4));
nz = normDiffusivity > epsilon;

% Formula for fractional anisotropy
fa = repmat(NaN, size(md));
fa(nz) = sqrt(3/2).*(stdevDiffusivity(nz)./normDiffusivity(nz));
fa = squeeze(fa);

% Mean diffusivity
md = squeeze(md);

% If requested, return rd and ad
if(nargout>2)
    % Radial diffusivity is the average of the two smaller eigenvalues
    rd = squeeze((eigVal(:,:,:,2)+eigVal(:,:,:,3))/2);
end
if(nargout>3)
    % Axial diffusivity - the largest eigenvalue
    ad = squeeze(eigVal(:,:,:,1));
end

return


function flag = checkinterfacemesh3(node, elem, interfaceData)
%% CHECKINTERFACEMESH3 check the validity of the polyhedra mesh generated
%   by interfacemesh3.
%
%   Here we check  validity of the polyhedra mesh by the Euler formla:
%            F - E + V = 2
%   where F, E and V are the number of faces, edges and vertices of a simply
%   closed polyhedron.
%
%   Author: Huayi Wei <weihuayi@xtu.edu.cn>, based on discussion with Long Chen.
%
%   See also: interfacemesh3
%
%   Copyright (C) Long Chen. See COPYRIGHT.txt for details.

face = interfaceData.face;
face2elem = interfaceData.face2elem;
N = size(node,1);
NF = size(face,1);

NP = max(face2elem);
isCutPoly = false(NP, 1);
isCutPoly(face2elem) = true;
cutPolyIdx = zeros(NP, 1);
NP = sum(isCutPoly);
cutPolyIdx(isCutPoly) = 1:NP;
face2elem = cutPolyIdx(face2elem);

isTriFace = face(:,4) == 0;
edge = 4*ones(NF,1);
edge(isTriFace) = 3;
E = accumarray(face2elem, edge)/2;
F = accumarray(face2elem, ones(NF,1));

poly2node = sparse(face2elem(isTriFace)*ones(1,3), face(isTriFace, 1:3), 1, NP,N)...
+ sparse(face2elem(~isTriFace)*ones(1,4), face(~isTriFace, 1:4), 1, NP,N);
poly2node = poly2node > 0;
NV = poly2node*ones(N,1);

isBdPoly = ((F - E + NV) ~= 2);

if ~isempty(find(isBdPoly,1))
    figure
    showmesh(node, face(isTriFace & isBdPoly(face2elem),1:3));
    sface = face(~isTriFace & isBdPoly(face2elem),1:4);
    hold on
    tsface = [sface(:, 1:3);sface(:,[3, 4,1])];
    showmesh(node, tsface, 'Facecolor','y');

%     bdPolyIdx = find(isBdPoly);
%     figure
%     for i = 1:size(bdPolyIdx)
%         sface = face(~isTriFace & face2elem == bdPolyIdx(i),1:4);
%         tsface = [sface(:, 1:3);sface(:,[3, 4,1])];
%         showmesh(node, [face(isTriFace & face2elem == bdPolyIdx(i),1:3);tsface]);
%     end
    flag = false;
else
    flag = true;
end


function y = perform_windowed_fourier_transform(x,w,q,n, options)

% perform_windowed_fourier_transform - compute a local Fourier transform
%
% Forward transform:
%   MF = perform_windowed_fourier_transform(M,w,q,n, options);
% Backward transform:
%   M  = perform_windowed_fourier_transform(MF,w,q,n, options);
%
%   w is the width of the window used to perform local computation.
%   q is the spacing betwen each window.
%
%   MF(:,:,,i,j) contains the spectrum around point ((i-1)*q,(j-1)*q)+1.
%
%   A typical use, for an redundancy of 2x2 could be w=2*q+1
%
%   options.bound can be either 'per' or 'sym'
%
%   options.normalization can be set to
%       'tightframe': tight frame transform, with energy conservation.
%       'unit': unit norm basis vectors, usefull to do thresholding
%
%   Copyright (c) 2006 Gabriel Peyre

options.null = 0;
if size(x,3)>1
    dir = -1;
    if nargin<4
        % assume power of 2 size
        n = q*size(x,3);
        n = 2^floor(log2(n));
    end
else
    dir = 1;
    n = size(x,1);
end

if isfield(options, 'bound')
    bound = options.bound;
else
    bound = 'sym';
    bound = 'per';
end

if isfield(options, 'transform_type')
    transform_type = options.transform_type;
else
    transform_type = 'fourier';
end

if isfield(options, 'normalization')
    normalization = options.normalization;
else
    normalization = 'tightframe';
end

% perform sampling
t = 1:q:n+1;
[Y,X] = meshgrid(t,t);
p = size(X,1);

if mod(w,2)==1
% w = ceil((w-1)/2)*2+1;
    w1 = (w-1)/2;
    t = -w1:w1;
else
    t = -w/2+1:w/2;
end
[dY,dX] = meshgrid(t,t);

X = reshape(X,[1 1 p p]);
Y = reshape(Y,[1 1 p p]);
X = repmat( X, [w w 1 1] );
Y = repmat( Y, [w w 1 1] );
dX = repmat( dX, [1 1 p p] );
dY = repmat( dY, [1 1 p p] );

X1 = X+dX;
Y1 = Y+dY;

switch lower(bound)
    case 'sym'
        X1(X1<1) = 1-X1(X1<1);
        X1(X1>n) = 2*n+1-X1(X1>n);
        Y1(Y1<1) = 1-Y1(Y1<1);
        Y1(Y1>n) = 2*n+1-Y1(Y1>n);
    case 'per'
        X1 = mod(X1-1,n)+1;
        Y1 = mod(Y1-1,n)+1;
end

% build a weight function
if isfield(options, 'window_type')
    window_type = options.window_type;
else
    window_type = 'sin';
end
if isfield(options, 'eta')
    eta = options.eta;
else
    eta = 1;
end

if strcmp(window_type, 'sin')
    t = linspace(0,1,w);
    W = sin(t(:)*pi).^2;
    W = W * W';
elseif strcmp(window_type, 'constant')
    W = ones(w);
else
    error('Unkwnown winow.');
end

I = X1 + (Y1-1)*n;

%% renormalize the windows
weight = zeros(n);
for i=1:p
    for j=1:p
        weight(I(:,:,i,j)) = weight(I(:,:,i,j)) + W.^2;
    end
end
weight = sqrt(weight);
Weight = repmat(W, [1 1 p p]);
for i=1:p
    for j=1:p
        Weight(:,:,i,j) = Weight(:,:,i,j) ./ weight(I(:,:,i,j));
    end
end

if strcmp(normalization, 'unit')
    if strcmp(transform_type, 'fourier')
        % for Fourier it is easy
        Renorm = sqrt( sum( sum( Weight.^2, 1 ), 2 ) )/w;
    else
        % for DCT it is less easy ...
        % take a typical window in the middle of the image
        weight = Weight(:,:,round(end/2),round(end/2));
        % compute diracs
        [X,Y,fX,fY] = ndgrid(0:w-1,0:w-1,0:w-1,0:w-1);
        A = 2 * cos( pi/w * ( X+1/2 ).*fX ) .* cos( pi/w * ( Y+1/2 ).*fY ) / w;
        A(:,:,1,:) = A(:,:,1,:) / sqrt(2); % scale zero frequency
        A(:,:,:,1) = A(:,:,:,1) / sqrt(2);
        A = A .* repmat( weight, [1 1 w w] );
        Renorm = sqrt( sum( sum( abs(A).^2, 1 ),2  ) );
    end
    Renorm = reshape( Renorm, w,w );
end

%% compute the transform
if dir==1
    y = zeros(eta*w,eta*w,p,p);
    if mod(w,2)==1
        m = (eta*w+1)/2; w1 = (w-1)/2;
        sel = m-w1:m+w1;
    else
        m = (eta*w)/2+1; w1 = w/2;
        sel = m-w1:m+w1-1;
    end
    y(sel,sel,:,:) = x(I) .* Weight;
    % perform the transform
    y = my_transform( y, +1, transform_type );
    % renormalize if necessary
    if strcmp(normalization, 'unit')
        y = y ./ repmat( Renorm, [1 1 p p] );
    end
else
    if strcmp(normalization, 'unit')
        x = x .* repmat( Renorm, [1 1 p p] );
    end
    x = my_transform( x, -1, transform_type );
    x = real( x.*Weight );
    y = zeros(n);
    for i=1:p
        for j=1:p
            y(I(:,:,i,j)) = y(I(:,:,i,j)) + x(:,:,i,j);
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = my_transform(x,dir,transform_type)

% my_transform - perform either FFT or DCT with energy conservation.
%   Works on array of size (w,w,a,b) on the 2 first dimensions.

w = size(x,1);
if strcmp(transform_type, 'fourier')
    % normalize for energy conservation
    if dir==1
        y = fftshift( fft2(x) ) / w;
    else
        y = ifft2( ifftshift(x*w) );
    end
elseif strcmp(transform_type, 'dct')
    for i=1:size(x,3)
        for j=1:size(x,4)
            y(:,:,i,j) = perform_dct_transform(x(:,:,i,j),dir);
        end
    end
else
    error('Unknown transform');
end


%................................................................

% MATLAB codes for Finite Element Analysis
% problem16vibrationsSchultz.m
% Timoshenko beam in free vibrations
% Lee/Schultz problem
% antonio ferreira 2008

% clear memory
clear all

% E; modulus of elasticity
% G; shear modulus
% I: second moments of area
% L: length of beam
% thickness: thickness of beam
E=10e7; poisson = 0.30;L  = 1;thickness=0.1;
I=thickness^3/12;
EI=E*I;
kapa=5/6;
rho=1;
A=1*thickness;
%

P = -1; % uniform pressure
% constitutive matrix
G=E/2/(1+poisson);
C=[   EI   0; 0    kapa*thickness*G];

% mesh
numberElements     = 40;
nodeCoordinates=linspace(0,L,numberElements+1);
xx=nodeCoordinates';x=xx';
for i=1:size(nodeCoordinates,2)-1
    elementNodes(i,1)=i;
    elementNodes(i,2)=i+1
end
% generation of coordinates and connectivities
numberNodes=size(xx,1);

% GDof: global number of degrees of freedom
GDof=2*numberNodes;

% computation of the system stiffness, force, mass
[stiffness,force,mass]=...
    formStiffnessMassTimoshenkoBeam(GDof,numberElements,...
    elementNodes,numberNodes,xx,C,P,rho,I,thickness);

% boundary conditions (CC)
fixedNodeW =find(xx==min(nodeCoordinates(:))...
    | xx==max(nodeCoordinates(:)));
fixedNodeTX=fixedNodeW;
prescribedDof=[fixedNodeW; fixedNodeTX+numberNodes];

% solution
displacements=solution(GDof,prescribedDof,stiffness,force);

% output displacements/reactions
outputDisplacementsReactions(displacements,stiffness,...
    GDof,prescribedDof)

% free vibration problem
activeDof=setdiff([1:GDof]',[prescribedDof]);
[V,D]=eig(stiffness(activeDof,activeDof),...
    mass(activeDof,activeDof));
D = diag(sqrt(D)*L*L*sqrt(rho*thickness/E/I));D=sqrt(D) ;
[D,ii] = sort(D);

% lee,schultz paper
modeNumber=4;
V1=zeros(GDof,1);
V1(activeDof,1:modeNumber)=V(:,1:modeNumber);

% drawing eigenmodes
drawEigenmodes1D(modeNumber,numberNodes,V1,xx,x)


function y = mg(DataDuration)

% Mackey-Glass chaotic time series generator.

NumOfSamples = DataDuration;
discarded = 350;
x = zeros(NumOfSamples + discarded + 1);
y = zeros(1,NumOfSamples);    % Each column represents different time instants.
Ts = 1;
x(1) = 1.2;
tau  = 17;

for n = tau+1:(NumOfSamples + discarded)
   x(n+1) = Ts*(0.2*x(n-tau)/( 1 + (x(n-tau))^10)) + (1 - 0.1*Ts)*x(n);
end

% plot(x);
% title('Mackey-Glass Chaotic Time Series');
% xlabel('Time Sample');
% ylabel('Estimated Value');

for k=1:NumOfSamples
   y(k) = x(discarded+k);
end


% Generate a set of covariance matrices according to a Wishart distrib.
% Inputs :
%   N : the size of the matrices
%   I : the number of matrices
%   Df : the degee of freedom
%   Sig : the parameter of the wishart disrib
%
% Outputs :
%   COV : a set of I covariance matrices
%   Sig : the parameter of the wishart disrib
function [COV Sig] = generate_wishart_set(N,I,Df,Sig)

    if nargin<4
        [Q,~] = qr(randn(N));
        Sig = Q'*diag(5*rand(N,1))*Q;
    end

    COV = zeros(N,N,I);
    for i=1:I
        COV(:,:,i) = wishrnd(Sig,Df);
    end


function set = exponential( varargin )

%EXPONENTIAL   Exponential cone.
%   EXPONENTIAL, called with no arguments, creates three scalar variables X,
%   Y, and Z and constraints them to lie in an exponetial cone. That is,
%   given the declaration
%       variables x y z
%       {x,y,z} == exp_cone
%   constraints the variables to satisfy
%       y*exp(x/y) <= z
%       y > 0
%   The inequality form does not obey the disciplined convex programming
%   ruleset, but a function EXP_P has been created to represent this
%   computation; so the set declaration above is equivalent to
%       EXP_P(X,Y) <= Z
%   EXP_CONE(SX), where SX is a size vector, creates three array variables
%   X, Y, and Z, each of size SX, which are constrained elementwise to
%   satisfy EXP_P(X,Y) <= Z. If SX is empty, then SX=[1,1] is assumed.

cvx_expert_check( 'exponential' );
[ sx, gp ] = cvx_get_dimlist( varargin ); %#ok
gp = ~isempty(gp) && gp;
if gp,
    cvx_begin gp set
        variables ex( sx ) ey( sx ) ez( sx )
        x = log( ex ); y = log( ey ); z = log( ez );
else
    cvx_begin set
        variable x( sx )
        variable y( sx ) nonnegative_
        variable z( sx ) nonnegative_
end
    cvx_pushcone( true, 'exponential', [ vec(x)' ; vec(y)' ; vec(z)' ] );
cvx_end
if gp,
    set = cvxtuple( struct( 'x', ex, 'y', ey, 'z', ez ) );
else
    set = cvxtuple( struct( 'x', x, 'y', y, 'z', z ) );
end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function bi = evalBSpline(xi,deg)
% evalBSpline: evaluate BSpline basis function
% usage: bi = evalBSpline(xi,deg);
%
% arguments:
%   xi (N-D arrary) - positions at which to evaluate BSpline basis function
%   deg (scalar) - degree of desired basis function
%
% Note: no error checking is performed for speed
%

% author: Nathan D. Cahill
% email: ndcahill@gmail.com
% date: 18 April 2008

switch deg
    case 0
        bi = (xi>=(-1/2))&(xi<(1/2));
    case 1
        bi = zeros(size(xi));
        k = (xi>=0) & (xi<1);
        bi(k) = 1 - xi(k);
        k(:) = (xi>=-1) & (xi<0);
        bi(k) = 1 + xi(k);
    case 2
        bi = zeros(size(xi));
        x2 = xi.*xi;
        k = (xi>=1/2) & (xi<3/2);
        bi(k) = (9/8) - (3/2).*xi(k) + (1/2).*x2(k);
        k = (xi>=-1/2) & (xi<1/2);
        bi(k) = (3/4) - x2(k);
        k = (xi>=-3/2) & (xi<-1/2);
        bi(k) = (9/8) + (3/2).*xi(k) + (1/2).*x2(k);
    case 3
        bi = zeros(size(xi));
        x2 = xi.*xi; x3 = x2.*xi;
        k = (xi>=1) & (xi<2);
        bi(k) = 4/3 - 2.*xi(k) + x2(k) - (1/6).*x3(k);
        k(:) = (xi>=0) & (xi<1);
        bi(k) = 2/3 - x2(k) + (1/2).*x3(k);
        k(:) = (xi>=-1) & (xi<0);
        bi(k) = 2/3 - x2(k) - (1/2).*x3(k);
        k(:) = (xi>=-2) & (xi<-1);
        bi(k) = 4/3 + 2.*xi(k) + x2(k) + (1/6).*x3(k);
    case 4
        bi = zeros(size(xi));
        x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi;
        k = (xi>=3/2) & (xi<5/2);
        bi(k) = 625/384 - (125/48).*xi(k) + (25/16).*x2(k) - (5/12).*x3(k) + (1/24).*x4(k);
        k = (xi>=1/2) & (xi<3/2);
        bi(k) = 55/96 + (5/24).*xi(k) - (5/4).*x2(k) + (5/6).*x3(k) - (1/6).*x4(k);
        k = (xi>=-1/2) & (xi<1/2);
        bi(k) = 115/192 - (5/8).*x2(k) + (1/4).*x4(k);
        k = (xi>=-3/2) & (xi<-1/2);
        bi(k) = 55/96 - (5/24).*xi(k) - (5/4).*x2(k) - (5/6).*x3(k) - (1/6).*x4(k);
        k = (xi>=-5/2) & (xi<-3/2);
        bi(k) = 625/384 + (125/48).*xi(k) + (25/16).*x2(k) + (5/12).*x3(k) + (1/24).*x4(k);
    case 5
        bi = zeros(size(xi));
        x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi; x5 = x4.*xi;
        k = (xi>=2) & (xi<3);
        bi(k) = 81/40 - (27/8).*xi(k) + (9/4).*x2(k) - (3/4).*x3(k) + (1/8).*x4(k) - (1/120).*x5(k);
        k = (xi>=1) & (xi<2);
        bi(k) = 17/40 + (5/8).*xi(k) - (7/4).*x2(k) + (5/4).*x3(k) - (3/8).*x4(k) + (1/24).*x5(k);
        k = (xi>=0) & (xi<1);
        bi(k) = 11/20 - (1/2).*x2(k) + (1/4).*x4(k) - (1/12).*x5(k);
        k = (xi>=-1) & (xi<0);
        bi(k) = 11/20 - (1/2).*x2(k) + (1/4).*x4(k) + (1/12).*x5(k);
        k = (xi>=-2) & (xi<-1);
        bi(k) = 17/40 - (5/8).*xi(k) - (7/4).*x2(k) - (5/4).*x3(k) - (3/8).*x4(k) - (1/24).*x5(k);
        k = (xi>=-3) & (xi<-2);
        bi(k) = 81/40 + (27/8).*xi(k) + (9/4).*x2(k) + (3/4).*x3(k) + (1/8).*x4(k) + (1/120).*x5(k);
    case 6
        bi = zeros(size(xi));
        x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi; x5 = x4.*xi; x6 = x5.*xi;
        k = (xi>=5/2) & (xi<7/2);
        bi(k) = 117649/46080 - (16807/3840).*xi(k) + (2401/768).*x2(k) - (343/288).*x3(k) + (49/192).*x4(k) - (7/240).*x5(k) + (1/720).*x6(k);
        k = (xi>=3/2) & (xi<5/2);
        bi(k) = 1379/7680 + (1267/960).*xi(k) - (329/128).*x2(k) + (133/72).*x3(k) - (21/32).*x4(k) + (7/60).*x5(k) - (1/120).*x6(k);
        k = (xi>=1/2) & (xi<3/2);
        bi(k) = 7861/15360 - (7/768).*xi(k) - (91/256).*x2(k) - (35/288).*x3(k) + (21/64).*x4(k) - (7/48).*x5(k) + (1/48).*x6(k);
        k = (xi>=-1/2) & (xi<1/2);
        bi(k) = 5887/11520 - (77/192).*x2(k) + (7/48).*x4(k) - (1/36).*x6(k);
        k = (xi>=-3/2) & (xi<-1/2);
        bi(k) = 7861/15360 + (7/768).*xi(k) - (91/256).*x2(k) + (35/288).*x3(k) + (21/64).*x4(k) + (7/48).*x5(k) + (1/48).*x6(k);
        k = (xi>=-5/2) & (xi<-3/2);
        bi(k) = 1379/7680 - (1267/960).*xi(k) - (329/128).*x2(k) - (133/72).*x3(k) - (21/32).*x4(k) - (7/60).*x5(k) - (1/120).*x6(k);
        k = (xi>=-7/2) & (xi<-5/2);
        bi(k) = 117649/46080 + (16807/3840).*xi(k) + (2401/768).*x2(k) + (343/288).*x3(k) + (49/192).*x4(k) + (7/240).*x5(k) + (1/720).*x6(k);
    case 7
        bi = zeros(size(xi));
        x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi; x5 = x4.*xi; x6 = x5.*xi; x7 = x6.*xi;
        k = (xi>=3) & (xi<4);
        bi(k) = 6405119470038039/1970324836974592 - (672537544353994073/118219490218475520).*xi(k) + (64/15).*x2(k) - (16/9).*x3(k) + (4/9).*x4(k) - (1/15).*x5(k) + (1/180).*x6(k) - (1/5040).*x7(k);
        k = (xi>=2) & (xi<3);
        bi(k) = -2173612320154509/9851624184872960 + (855120979246972939/354658470655426560).*xi(k) - (23/6).*x2(k) + (49/18).*x3(k) - (19/18).*x4(k) + (7/30).*x5(k) - (1/36).*x6(k) + (1/720).*x7(k);
        k = (xi>=1) & (xi<2);
        bi(k) = 103/210 - (7/90).*xi(k) - (1/10).*x2(k) - (7/18).*x3(k) + (1/2).*x4(k) - (7/30).*x5(k) + (1/20).*x6(k) - (1/240).*x7(k);
        k = (xi>=0) & (xi<1);
        bi(k) = 151/315 - (1/3).*x2(k) + (1/9).*x4(k) - (1/36).*x6(k) + (1/144).*x7(k);
        k = (xi>=-1) & (xi<0);
        bi(k) = 151/315 - (1/3).*x2(k) + (1/9).*x4(k) - (1/36).*x6(k) - (1/144).*x7(k);
        k = (xi>=-2) & (xi<-1);
        bi(k) = 103/210 + (7/90).*xi(k) - (1/10).*x2(k) + (7/18).*x3(k) + (1/2).*x4(k) + (7/30).*x5(k) + (1/20).*x6(k) + (1/240).*x7(k);
        k = (xi>=-3) & (xi<-2);
        bi(k) = -2173612320154509/9851624184872960 - (855120979246972939/354658470655426560).*xi(k) - (23/6).*x2(k) - (49/18).*x3(k) - (19/18).*x4(k) - (7/30).*x5(k) - (1/36).*x6(k) - (1/720).*x7(k);
        k = (xi>=-4) & (xi<-3);
        bi(k) = 6405119470038039/1970324836974592 + (672537544353994073/118219490218475520).*xi(k) + (64/15).*x2(k) + (16/9).*x3(k) + (4/9).*x4(k) + (1/15).*x5(k) + (1/180).*x6(k) + (1/5040).*x7(k);
    otherwise
        bi = ((xi + ((deg+1)/2)).*evalBSpline(xi+(1/2),deg-1) + ...
            (((deg+1)/2) - xi).*evalBSpline(xi-(1/2),deg-1))./deg;
end


% 迭代法求解方程
clear;
format long;
tol = 1e-5;
N = 100;
x0 = 10.5;

phi = @(x) exp(-x);
for k = 1 : N
    x1 = phi(x0);
    if abs(x1 - x0) < tol
        fprintf('方程的正根: %10.8f\n', x1);
        fprintf('迭代次数: %d\n', k);
        break;
    end
    x0 = x1;
end
if k == N
    fprintf('迭代方法失败\n');
end


function pts = intersectPolylines(poly1, varargin)
%INTERSECTPOLYLINES Find the common points between 2 polylines
%
%   INTERS = intersectPolylines(POLY1, POLY2)
%   Returns the intersection points between two polylines. Each polyline is
%   defined by a N-by-2 array representing coordinates of its vertices:
%   [X1 Y1 ; X2 Y2 ; ... ; XN YN]
%   INTERS is a NP-by-2 array containing coordinates of intersection
%   points.
%
%   INTERS = intersectPolylines(POLY1)
%   Compute self-intersections of the polyline.
%
%   Example
%   % Compute intersection points between 2 simple polylines
%     poly1 = [20 10 ; 20 50 ; 60 50 ; 60 10];
%     poly2 = [10 40 ; 30 40 ; 30 60 ; 50 60 ; 50 40 ; 70 40];
%     pts = intersectPolylines(poly1, poly2);
%     figure; hold on;
%     drawPolyline(poly1, 'b');
%     drawPolyline(poly2, 'm');
%     drawPoint(pts);
%     axis([0 80 0 80]);
%
%   This function is largely based on the 'interX' function, found on the
%   FileExchange:
%   https://fr.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections
%
%   See also
%   polygons2d, polylineSelfIntersections, intersectLinePolygon
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2009-06-15,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.

% The code is a slight rewritting of the interX function, consisting in
% avoiding argument transposition in the begining of the function. Comment
% of original submission are kept here for information.
%
%INTERX Intersection of curves
%   P = INTERX(L1,L2) returns the intersection points of two curves L1
%   and L2. The curves L1,L2 can be either closed or open and are described
%   by two-row-matrices, where each row contains its x- and y- coordinates.
%   The intersection of groups of curves (e.g. contour lines, multiply
%   connected regions etc) can also be computed by separating them with a
%   column of NaNs as for example
%
%         L  = [x11 x12 x13 ... NaN x21 x22 x23 ...;
%               y11 y12 y13 ... NaN y21 y22 y23 ...]
%
%   P has the same structure as L1 and L2, and its rows correspond to the
%   x- and y- coordinates of the intersection points of L1 and L2. If no
%   intersections are found, the returned P is empty.
%
%   P = INTERX(L1) returns the self-intersection points of L1. To keep
%   the code simple, the points at which the curve is tangent to itself are
%   not included. P = INTERX(L1,L1) returns all the points of the curve
%   together with any self-intersection points.
%
%   Example:
%       t = linspace(0,2*pi);
%       r1 = sin(4*t)+2;  x1 = r1.*cos(t); y1 = r1.*sin(t);
%       r2 = sin(8*t)+2;  x2 = r2.*cos(t); y2 = r2.*sin(t);
%       P = InterX([x1;y1],[x2;y2]);
%       plot(x1,y1,x2,y2,P(1,:),P(2,:),'ro')
%
%   Author : NS
%   Version: 3.0, 21 Sept. 2010
%
%   Two words about the algorithm: Most of the code is self-explanatory.
%   The only trick lies in the calculation of C1 and C2. To be brief, this
%   is essentially the two-dimensional analog of the condition that needs
%   to be satisfied by a function F(x) that has a zero in the interval
%   [a,b], namely
%           F(a)*F(b) <= 0
%   C1 and C2 exactly do this for each segment of curves 1 and 2
%   respectively. If this condition is satisfied simultaneously for two
%   segments then we know that they will cross at some point.
%   Each factor of the 'C' arrays is essentially a matrix containing
%   the numerators of the signed distances between points of one curve
%   and line segments of the other.

% Check number of inputs
narginchk(1, 2);

% Specific init depending on number of inputs
if nargin == 1
    % Compute self-intersections
    % -> Avoid the inclusion of common points
    poly2 = poly1;
    hF = @lt;
else
    % Compute intersections between distinct lines
    poly2 = varargin{1};
    hF = @le;
end

% Get coordinates of polyline vertices
x1 = poly1(:,1);
x2 = poly2(:,1)';
y1 = poly1(:,2);
y2 = poly2(:,2)';

% differentiate coordinate arrays
dx1 = diff(x1); dy1 = diff(y1);
dx2 = diff(x2); dy2 = diff(y2);

% Determine 'signed distances'
S1 = dx1 .* y1(1:end-1) - dy1 .* x1(1:end-1);
S2 = dx2 .* y2(1:end-1) - dy2 .* x2(1:end-1);

C1 = feval(hF, D(bsxfun(@times,dx1,y2) - bsxfun(@times,dy1,x2), S1), 0);
C2 = feval(hF, D((bsxfun(@times,y1,dx2) - bsxfun(@times,x1,dy2))', S2'), 0)';

% Obtain the segments where an intersection is expected
[i, j] = find(C1 & C2);

% Process case of no intersection
if isempty(i)
    pts = zeros(0, 2);
    return;
end

% Transpose and prepare for output
i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
L = dy2(j).*dx1(i) - dy1(i).*dx2(j);

% Avoid divisions by zero
i = i(L~=0);
j = j(L~=0);
L = L(L~=0);

% Solve system of eqs to get the common points
res = [dx2(j).*S1(i) - dx1(i).*S2(j), dy2(j).*S1(i) - dy1(i).*S2(j)] ./ [L L];
pts = unique(res, 'rows');

% Innre function computing a kind of cross-product
function u = D(x,y)
    u = bsxfun(@minus, x(:,1:end-1), y) .* bsxfun(@minus, x(:,2:end), y);
end

end


function varargout = cylinderMesh(cyl, varargin)
%CYLINDERMESH Create a 3D mesh representing a cylinder.
%
%   [V, F] = cylinderMesh(CYL)
%   Computes vertex coordinates and face vertex indices of a mesh
%   representing a 3D cylinder given as [X1 Y1 Z1 X2 Y2 Z2 R].
%
%   [V, F] = cylinderMesh(..., OPT)
%   with OPT = 'open' (0) (default) or 'closed' (1), specify if the bases
%   of the cylinder should be included.
%
%   [V, F] = cylinderMesh(..., NAME, VALUE);
%   Specifies one or several options using parameter name-value pairs.
%   Available options are:
%   'nPerimeter' the number of circles represeting the perimeter
%   'nRho' the number of circles along the hight
%
%   Example
%     % Draw a rotated cylinder
%     cyl = [0 0 0 10 20 30 5];
%     [v, f] = cylinderMesh(cyl);
%     figure;drawMesh(v, f, 'FaceColor', 'r');
%     view(3); axis equal;
%
%     % Draw three mutually intersecting cylinders
%       p0 = [30 30 30];
%       p1 = [90 30 30];
%       p2 = [30 90 30];
%       p3 = [30 30 90];
%       [v1 f1] = cylinderMesh([p0 p1 25]);
%       [v2 f2] = cylinderMesh([p0 p2 25]);
%       [v3 f3] = cylinderMesh([p0 p3 25],'closed','nPeri',40,'nRho',20);
%       figure; hold on;
%       drawMesh(v1, f1, 'FaceColor', 'r');
%       drawMesh(v2, f2, 'FaceColor', 'g');
%       drawMesh(v3, f3, 'FaceColor', 'b');
%       view(3); axis equal
%       set(gcf, 'renderer', 'opengl')
%
%   See also
%     drawCylinder, torusMesh, sphereMesh

% ------
% Author: David Legland
% E-mail: david.legland@inra.fr
% Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b)
% Copyright 2012-2022 INRA - Cepia Software Platform

parser = inputParser;
addRequired(parser, 'cyl', @(x) validateattributes(x, {'numeric'},...
    {'size',[1 7],'real','finite','nonnan'}));
capParValidFunc = @(x) (islogical(x) ...
    || isequal(x,1) || isequal(x,0) || any(validatestring(x, {'open','closed'})));
addOptional(parser,'cap','open', capParValidFunc);
addParameter(parser, 'nPerimeter', 20, @(x) validateattributes(x,{'numeric'},...
    {'integer','scalar','>=',4}));
addParameter(parser, 'nRho', 10, @(x) validateattributes(x,{'numeric'},...
    {'integer','scalar','>=',2}));
parse(parser,cyl,varargin{:});
cyl=parser.Results.cyl;
cap=lower(parser.Results.cap(1));
NoPP=parser.Results.nPerimeter;
nRho=parser.Results.nRho;

% extract cylinder data
p1 = cyl(:, 1:3);
p2 = cyl(:, 4:6);
r  = cyl(:, 7);

% compute length and orientation
[theta, phi, rho] = cart2sph2d(p2 - p1);

% parametrisation on x
t = linspace(0, 2*pi, NoPP);
lx = r * cos(t);
ly = r * sin(t);

% parametrisation on z
lz = linspace(0, rho, nRho);

% generate surface grids
x = repmat(lx, [length(lz) 1]);
y = repmat(ly, [length(lz) 1]);
z = repmat(lz', [1 length(t)]);

% transform points
trans = localToGlobal3d(p1, theta, phi, 0);
[x, y, z] = transformPoint3d(x, y, z, trans);

% convert to FV mesh
[vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', true);

% Close cylinder
if cap == 'c' || cap == 1
    toe.vertices = [x(1,1:NoPP-1); y(1,1:NoPP-1); z(1,1:NoPP-1)]';
    toe.vertices(NoPP,:) = transformPoint3d([0 0 0], trans);
    toe.faces = [repmat(NoPP, 1, NoPP-1); [2:NoPP-1 1]; 1:NoPP-1]';

    top.vertices = [x(end,1:NoPP-1); y(end,1:NoPP-1); z(end,1:NoPP-1)]';
    top.vertices(NoPP,:) = transformPoint3d([0 0 rho], trans);
    top.faces = fliplr(toe.faces);

    [vertices, faces] = concatenateMeshes(vertices, triangulateFaces(faces), ...
        toe.vertices, toe.faces, top.vertices, top.faces);
end

% format output
varargout = formatMeshOutput(nargout, vertices, faces);


function result = pyramid_unit_o06_3d ( func )

%*****************************************************************************80
%
%% PYRAMID_UNIT_O06_3D approximates an integral inside the unit pyramid in 3D.
%
%  Discussion:
%
%    A 6 point formula is used.
%
%    The (X,Y,Z) integration region can be represented as:
%
%    - ( 1 - Z ) <= X <= 1 - Z
%    - ( 1 - Z ) <= Y <= 1 - Z
%              0 <= Z <= 1.
%
%    When Z is zero, the integration region is a square lying in the (X,Y)
%    plane, centered at (0,0,0) with "radius" 1.  As Z increases to 1, the
%    radius of the square diminishes, and when Z reaches 1, the square has
%    contracted to the single point (0,0,1).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 April 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Carlos Felippa,
%    A compendium of FEM integration formulas for symbolic work,
%    Engineering Computation,
%    Volume 21, Number 8, 2004, pages 867-890.
%
%  Parameters:
%
%    Input, external FUNC, the name of the user supplied function which
%    evaluates F(X,Y,Z), of the form
%      function value = func ( x, y, z )
%
%    Output, real RESULT, the approximate integral of the function.
%
  order = 6;

  w = [ ...
   0.21000000000000000000, ...
   0.21000000000000000000, ...
   0.21000000000000000000, ...
   0.21000000000000000000, ...
   0.06000000000000000000, ...
   0.10000000000000000000 ]';
  x = [ ...
  -0.48795003647426658968, ...
   0.48795003647426658968, ...
   0.48795003647426658968, ...
  -0.48795003647426658968, ...
   0.00000000000000000000, ...
   0.00000000000000000000 ]';
  y = [ ...
  -0.48795003647426658968, ...
  -0.48795003647426658968, ...
   0.48795003647426658968, ...
   0.48795003647426658968, ...
   0.00000000000000000000, ...
   0.00000000000000000000 ]';
  z = [ ...
   0.16666666666666666667, ...
   0.16666666666666666667, ...
   0.16666666666666666667, ...
   0.16666666666666666667, ...
   0.58333333333333333333, ...
   0.75000000000000000000 ]';
%
%  Quadrature.
%
  quad = 0.0;
  for i = 1 : order
    quad = quad + w(i) * feval ( func, x(i), y(i), z(i) );
  end
%
%  Volume.
%
  volume = pyramid_unit_volume_3d ( );
%
%  Result.
%
  result = quad * volume;

  return
end