function a = clement2_inverse ( n, x, y )

%*****************************************************************************80
%
%% CLEMENT2_INVERSE returns the inverse of the CLEMENT2 matrix.
%
%  Example:
%
%    N = 6, X and Y arbitrary:
%
%     0                1/Y1 0         -X2/(Y1*Y3) 0   X2*X4/(Y1*Y3*Y5)
%     1/X1             0    0          0          0    0
%     0                0    0          1/Y3       0   -X4/(Y3*Y5)
%    -Y2/(X1*X3)       0    1/X3       0          0    0
%     0                0    0          0          0    1/Y5
%     Y2*Y4/(X1*X3*X5) 0   -Y4/(X3*X5) 0          1/X5 0
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Clement,
%    A class of triple-diagonal matrices for test purposes,
%    SIAM Review,
%    Volume 1, 1959, pages 50-52.
%
%  Parameters:
%
%    Input, integer N, the order of A.  N must not be odd%
%
%    Input, real X(N-1), Y(N-1), the first super and
%    subdiagonals of the matrix A.  None of the entries
%    of X or Y may be zero.
%
%    Output, real A(N,N), the matrix.
%
  if ( mod ( n, 2 ) == 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'CLEMENT2_INVERSE - Fatal error!\n' );
    fprintf ( 1,'  The matrix is singular for odd N.\n' );
    error ( 'CLEMENT2_INVERSE - Fatal error!' );
  end

  for i = 1 : n-1

    if ( x(i) == 0.0 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'CLEMENT2_INVERSE - Fatal error!\n' );
      fprintf ( 1, '  The matrix is singular\n' );
      fprintf ( 1, '  X(I) = 0 for I = %d\n', i );
      error ( 'CLEMENT2_INVERSE - Fatal error!' );
    elseif ( y(i) == 0.0 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'CLEMENT2_INVERSE - Fatal error!\n' );
      fprintf ( 1, '  The matrix is singular\n' );
      fprintf ( 1, '  Y(I) = 0 for I = %d\n', i );
      error ( 'CLEMENT2_INVERSE - Fatal error!' );
    end

  end

  a = zeros ( n, n );

  for i = 1 : n

    if ( mod ( i, 2 ) == 1 )

      for j = i : 2 : n-1

        if ( j == i )
          prod1 = 1.0 / y(j);
          prod2 = 1.0 / x(j);
        else
          prod1 = - prod1 * x(j-1) / y(j);
          prod2 = - prod2 * y(j-1) / x(j);
        end

        a(i,j+1) = prod1;
        a(j+1,i) = prod2;

      end

    end

  end

  return
end


function y=savitzkyGolayFilt(x,N,DN,F,W,DIM)
%savitzkyGolayFilt Savitzky-Golay Filtering.
%   savitzkyGolayFilt(X,N,DN,F) filters the signal X using a Savitzky-Golay
%   (polynomial) filter.  The polynomial order, N, must be less than the
%   frame size, F, and F must be odd.  DN specifies the differentiation
%   order (DN=0 is smoothing). For a DN higher than zero, you'll have to
%   scale the output by 1/T^DN to acquire the DNth smoothed derivative of
%   input X, where T is the sampling interval. The length of the input X
%   must be >= F.  If X is a matrix, the filtering is done on the columns
%   of X.
%
%   Note that if the polynomial order N equals F-1, no smoothing
%   will occur.
%
%   savitzkyGolayFilt(X,N,DN,F,W) specifies a weighting vector W with
%   length F containing real, positive valued weights employed during the
%   least-squares minimization. If not specified, or if specified as
%   empty, W defaults to an identity matrix.
%
%   savitzkyGolayFilt(X,N,DN,F,[],DIM) or savitzkyGolayFilt(X,N,DN,F,W,DIM)
%   operates along the dimension DIM.
%
%   See also savitzkyGolay, FILTER, sgolayfilt

%   References:
%     [1] Sophocles J. Orfanidis, INTRODUCTION TO SIGNAL PROCESSING,
%              Prentice-Hall, 1995, Chapter 8.

%   Author(s): R. Losada
%   Copyright 1988-2004 The MathWorks, Inc.
%   $Revision: 1.11.4.4 $  $Date: 2009/08/11 15:47:54 $

error(nargchk(4,6,nargin,'struct'));

% Check if the input arguments are valid
if round(F) ~= F, error(generatemsgid('MustBeInteger'),'Frame length must be an integer.'), end
if rem(F,2) ~= 1, error(generatemsgid('SignalErr'),'Frame length must be odd.'), end
if round(N) ~= N, error(generatemsgid('MustBeInteger'),'Polynomial order must be an integer.'), end
if N > F-1, error(generatemsgid('InvalidRange'),'The Polynomial order must be less than the frame length.'), end
if DN > N, error(generatemsgid('InvalidRange'),'The Differentiation order must be less than or equal to the Polynomial order.'), end

if nargin < 5 || isempty(W)
   % No weighting matrix, make W an identity
   W = ones(F,1);
else
   % Check for right length of W
   if length(W) ~= F, error(generatemsgid('InvalidDimensions'),'The weight vector must be of the same length as the frame length.'),end
   % Check to see if all elements are positive
   if min(W) <= 0, error(generatemsgid('InvalidRange'),'All the elements of the weight vector must be greater than zero.'), end
end

if nargin < 6, DIM = []; end

% Compute the projection matrix B
pp = fix(-F./2):fix(F./2);
B = savitzkyGolay(pp,N,DN,pp,W);

if ~isempty(DIM) && DIM > ndims(x)
	error(generatemsgid('InvalidDimensions'),'Dimension specified exceeds the dimensions of X.')
end

% Reshape X into the right dimension.
if isempty(DIM)
	% Work along the first non-singleton dimension
	[x, nshifts] = shiftdim(x);
else
	% Put DIM in the first dimension (this matches the order
	% that the built-in filter function uses)
	perm = [DIM,1:DIM-1,DIM+1:ndims(x)];
	x = permute(x,perm);
end

if size(x,1) < F, error(generatemsgid('InvalidDimensions'),'The length of the input must be >= frame length.'), end

% Preallocate output
y = zeros(size(x));

% Compute the transient on (note, this is different than in sgolayfilt,
% they had an optimization leaving out some transposes that is only valid
% for DN==0)
y(1:(F+1)/2-1,:) = fliplr(B(:,(F-1)/2+2:end)).'*flipud(x(1:F,:));

% Compute the steady state output
ytemp = filter(B(:,(F-1)./2+1),1,x);
y((F+1)/2:end-(F+1)/2+1,:) = ytemp(F:end,:);

% Compute the transient off
y(end-(F+1)/2+2:end,:) = fliplr(B(:,1:(F-1)/2)).'*flipud(x(end-(F-1):end,:));

% Convert Y to the original shape of X
if isempty(DIM)
	y = shiftdim(y, -nshifts);
else
	y = ipermute(y,perm);
end


function z = quad_pos_over_lin( x, y, dim )

%QUAD_POS_OVER_LIN Sum of squares of positives over linear.
%   Z=QUAD_POS_OVER_LIN(X,Y), where X is a vector and Y is a scalar, is equal to
%   SUM(MAX(X,0).^2)./Y if Y is positive, and +Inf otherwise. Both X and Y must
%   be real.
%
%   For matrices, QUAD_POS_OVER_LIN(X,Y) is a row vector containing the
%   application of QUAD_POS_OVER_LIN to each column. For N-D arrays, the
%   operation is applied to the first non-singleton dimension of X.
%
%   QUAD_POS_OVER_LIN(X,Y,DIM) takes the sum along the dimension DIM of X.
%   A special value of DIM == 0, is accepted here, which is automatically
%   replaced with DIM == NDIMS(X) + 1. This has the effect of eliminating
%   the sum; thus QUAD_POS_OVER_LIN( X, Y, NDIMS(X) + 1 ) = MAX(X,0).^2./Y.
%
%   In all cases, both X and Y must be real, and Y must either be a scalar
%   or a matrix of the same size as SUM(X,DIM).
%
%   Disciplined convex programming information:
%       QUAD_POS_OVER_LIN is convex, nondecreasing in X, and nonincreasing
%       in Y. Thus when used with CVX expressions, X must be convex (or
%       affine) and Y must be concave (or affine).

%
% Check arguments
%

error( nargchk( 2, 3, nargin ) );
if ~isreal( x ),
    error( 'First argument must be real.' );
elseif ~isreal( y ),
    error( 'Second argument must be real.' );
elseif nargin < 3 || isempty( dim ),
    dim = cvx_default_dimension( size( x ) );
elseif ~cvx_check_dimension( dim ),
    error( 'Third argument, if supplied, must be a positive integer.' );
end

%
% Perform calculation
%

z = quad_over_lin( max( x, 0 ), y, dim );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function elliptic_km_values_test ( )

%*****************************************************************************80
%
%% ELLIPTIC_KM_VALUES_TEST demonstrates the use of ELLIPTIC_KM_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'ELLIPTIC_KM_VALUES_TEST:\n' );
  fprintf ( 1, '  ELLIPTIC_KM_VALUES stores values of\n' );
  fprintf ( 1, '  the complete elliptic integral of the first\n' );
  fprintf ( 1, '  kind, with parameter modulus M.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      M            KM(M)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, fx ] = elliptic_km_values ( n_data );

    if ( n_data == 0 )
      break
    end

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

  end

  return
end


function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters.
%               You should set p to a vector of 0's and 1's
%

f=@(n) round(n);

s = sigmoid(X * theta);

p = f(s);

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

end


function F = CalHV(points,bounds,k,nSample)
% Calculate the hypervolume-based fitness value of each solution

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

% This function is modified from the code in
% http://www.tik.ee.ethz.ch/sop/download/supplementary/hype/

    [N,M] = size(points);
    if M > 2
        % Use the estimated method for three or more objectives
        alpha = zeros(1,N);
        for i = 1 : k
            alpha(i) = prod((k-[1:i-1])./(N-[1:i-1]))./i;
        end
        Fmin = min(points,[],1);
        S    = unifrnd(repmat(Fmin,nSample,1),repmat(bounds,nSample,1));
        PdS  = false(N,nSample);
        dS   = zeros(1,nSample);
        for i = 1 : N
            x        = sum(repmat(points(i,:),nSample,1)-S<=0,2) == M;
            PdS(i,x) = true;
            dS(x)    = dS(x) + 1;
        end
        F = zeros(1,N);
        for i = 1 : N
            F(i) = sum(alpha(dS(PdS(i,:))));
        end
        F = F.*prod(bounds-Fmin)/nSample;
    else
        % Use the accurate method for two objectives
        pvec  = 1:size(points,1);
        alpha = zeros(1,k);
        for i = 1 : k
            j = 1:i-1;
            alpha(i) = prod((k-j)./(N-j))./i;
        end
        F = hypesub(N,points,M,bounds,pvec,alpha,k);
    end
end

function h = hypesub(l,A,M,bounds,pvec,alpha,k)
% The recursive function for the accurate method

    h     = zeros(1,l);
    [S,i] = sortrows(A,M);
    pvec  = pvec(i);
    for i = 1 : size(S,1)
        if i < size(S,1)
            extrusion = S(i+1,M) - S(i,M);
        else
            extrusion = bounds(M) - S(i,M);
        end
        if M == 1
            if i > k
                break;
            end
            if alpha >= 0
                h(pvec(1:i)) = h(pvec(1:i)) + extrusion*alpha(i);
            end
        elseif extrusion > 0
            h = h + extrusion*hypesub(l,S(1:i,:),M-1,bounds,pvec(1:i),alpha,k);
        end
    end
end


function [y,deriv] = logdet_chol(w)
% This is an MV2DF. See MV2DF_API_DEFINITION.readme.
% y = log(det(W)), where W is positive definite and W = reshape(w,...)

if nargin==0
    test_this();
    return;
end

if isempty(w)
    y = @(w)logdet_chol(w);
    return;
end

if isa(w,'function_handle')
    outer = logdet_chol([]);
    y = compose_mv(outer,w,[]);
    return;
end

dim = sqrt(length(w));
W = reshape(w,dim,dim);

if nargout>1
    %[inv_map,bi_inv_map,logdet,iW] = invchol2(W);
    [inv_map,bi_inv_map,logdet,iW] = invchol_or_lu(W);
    y = logdet;
    deriv = @(dy) deriv_this(dy,bi_inv_map,iW);
else
    %[inv_map,bi_inv_map,logdet] = invchol2(W);
    [inv_map,bi_inv_map,logdet] = invchol_or_lu(W);
    y = logdet;
end

function [g,hess,linear] = deriv_this(dy,bi_inv_map,iW)
G = iW.';
grad = G(:);
g = dy*grad;
linear = false;
hess = @(d) hess_this(grad,bi_inv_map,dy,d);

function [h,Jd] = hess_this(grad,bi_inv_map,dy,d)
dim = sqrt(length(d));
D = reshape(d,dim,dim);
H = - dy*bi_inv_map(D).';
h = H(:);
if nargout>1
    Jd = grad.'*d(:);
end

function test_this()
m = 3;
n = 10;

w = [];
A = UtU(w,n,m);

f = logdet_chol(A);
w = randn(m*n,1);

test_MV2DF(f,w,true);


function [out] = smoothThreshold_storage_logistic(S,Smax,r,e)
%smoothThreshold_storage_logistic Logisitic smoother for storage threshold functions.

% Copyright (C) 2018 Wouter J.M. Knoben
% 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.

%   Smooths the transition of threshold functions of the form:
%
%   Q = { P, if S = Smax
%       { 0, if S < Smax
%
%   By transforming the equation above to Q = f(P,S,Smax,e,r):
%   Q = P * 1/ (1+exp((S-Smax+r*e*Smax)/(r*Smax)))
%
%   Inputs:
%   S       : current storage
%   Smax    : maximum storage
%   r       : [optional] smoothing parameter rho, default = 0.01
%   e       : [optional] smoothing parameter e, default 5
%
%   NOTE: this function only outputs the multiplier. This needs to be
%   applied to the proper flux utside of this function.
%
%   NOTE: can be applied for temperature thresholds as well (i.e. snow
%   modules). This simply means that S becomes T, and Smax T0.

% Check for inputs and use defaults if not provided
% NOTE: this is not very elegant, but it is more than a factor 10 faster then:
% if ~exist('r','var'); r = 0.01; end
% if ~exist('e','var'); e = 5.00; end
if nargin == 2
    r = 0.01;
    e = 5.00;
elseif nargin == 3
    e = 5.00;
end

% Calculate multiplier
Smax = max(Smax,0);   % this avoids numerical instabilities when Smax<0
if r*Smax == 0
    out = 1 ./ (1+exp((S-Smax+r*e*Smax)/(r)));
else
    out = 1 ./ (1+exp((S-Smax+r*e*Smax)/(r*Smax)));
end

end


function px = gmmEval(x, gmm)
% Computes the probability of the data given a Guassian mixture model
% x(ndata, ndim) - the data to be evaluated
% gmm.mu{K}, gmm.sigma{K}, gmm.priors{K} - the mixture parameters

K = length(gmm.priors);
[ndata, ndim] = size(x);

px = zeros(ndata, 1);

if K ==0
    return;
end

for k = 1:K
    invSigma = inv(gmm.sigma{k});
    for i = 1:ndata
        px(i) = px(i) + 1/(sqrt(2*pi)*sqrt(det(gmm.sigma{k}))) * ...
            exp(-1/2 * (x(i, :)-gmm.mu{k}) * invSigma * (x(i, :)-gmm.mu{k})') ...
            * gmm.priors(k);
    end
end


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

%*****************************************************************************80
%
%% ERLANG_CDF evaluates the Erlang CDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the argument of the CDF.
%
%    Input, real A, B, integer C, the parameters of the PDF.
%    0.0 < B.
%    0 < C.
%
%    Output, real CDF, the value of the CDF.
%
  if ( x < a )

    cdf = 0.0;

  else

    x2 = ( x - a ) / b;
    p2 = c;

    cdf = gamma_inc ( p2, x2 );

  end

  return
end


function imgOut = ExponentialTMO(img, exp_k)
%
%       imgOut = ExponentialTMO(img, exp_k)
%
%
%       Input:
%           -img: input HDR image
%           -exp_k: appearance value [1, +inf)
%
%       Output
%           -imgOut: tone mapped image
%
%     Copyright (C) 2010-15 Francesco Banterle
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
%

%is it a three color channels image?
check13Color(img);

checkNegative(img);

if(~exist('exp_k', 'var'))
    exp_k = 1;
end

if(exp_k <= 0)
    exp_k = 1;
end

%Luminance channel
L = lum(img);

Lwa = logMean(L); %geometric mean

%dynamic range reduction
Ld = 1 - exp(-exp_k * ( L / Lwa));

%change luminance in img
imgOut = ChangeLuminance(img, L, Ld);

end


function geometry_test170 ( )

%*****************************************************************************80
%
%% TEST170 tests PROVEC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
  m = 4;
  n = 2;

  base = [ ...
    4.0, 3.0, 2.0, 1.0; ...
    1.0, 2.0, 3.0, 4.0 ]';
  vecm = [ 1.0, 1.0, 1.0, 2.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST170\n' );
  fprintf ( 1, '  PROVEC projects a vector onto a subspace.\n' );

  r8mat_transpose_print ( m, n, base, '  Base vectors' );

  r8vec_print ( m, vecm, '  Vector to be projected:' );

  [ vecn, vecnm ] = provec ( m, n, base, vecm );

  r8vec_print ( n, vecn, '  Projected vector in BASE coordinates:' );

  r8vec_print ( m, vecnm, '  Projected vector in original coordinates:' );

  return
end


function ulimit = SlopeLimitN(u);

% function ulimit = SlopeLimitN(u);
% Purpose: Apply slopelimiter (Pi^N) to u assuming u an N'th order polynomial

Globals1D;

% Compute cell averages
uh = invV*u; uh(2:Np,:)=0; uavg = V*uh; v = uavg(1,:);

% Apply slope limiter as needed.
ulimit = u; eps0=1.0e-8;

% find end values of each element
ue1 = u(1,:); ue2 = u(end,:);

% find cell averages
vk = v; vkm1 = [v(1),v(1:K-1)]; vkp1 = [v(2:K),v(K)];

% Apply reconstruction to find elements in need of limiting
ve1 = vk - minmod([(vk-ue1);vk-vkm1;vkp1-vk]);
ve2 = vk + minmod([(ue2-vk);vk-vkm1;vkp1-vk]);
ids = find(abs(ve1-ue1)>eps0 | abs(ve2-ue2)>eps0);

% Check to see if any elements require limiting
if(~isempty(ids))
  % create piecewise linear solution for limiting on specified elements
  uhl = invV*u(:,ids); uhl(3:Np,:)=0; ul = V*uhl;

  % apply slope limiter to selected elements
  ulimit(:,ids) = SlopeLimitLin(ul,x(:,ids),vkm1(ids),vk(ids),vkp1(ids));
end
return;


function Q = deconvolutionDAMAS(S, e, maxIterations)
%deconvolutionDAMAS - deconvolves the intensity plot with the DAMAS algorithm
%as implemented in "A deconvolution approach for the mapping of acoustic sources
%(DAMAS) determined from phased microphone arrays", Brooks and Humphreys, 2005
%
%Q = deconvolutionDAMAS(S, e, maxIterations)
%
%IN
%S - MxN matrix of delay-and-sum steered response power
%e - MxNxP steering vector/matrix for a certain frequency
%
%OUT
%Q - MxN devonvolved intensity plot
%
%Created by J?rgen Grythe
%Last updated 2017-02-27

if ~exist('maxIterations', 'var')
    maxIterations = 100;
end

Y = real(S);
deps = 0.1;

%M # of y-points, N # of x-points, P number of mics
[M, N, P] = size(e);

%Make the A-matrix square size NxM x NxM x P
ee = reshape(e, M*N, P);
A = (abs(ee*ee').^2)./P^2;

%Initialise final source powers Q
Q = zeros(size(Y));
Q0 = Y;

%Solve the system Y = AQ for Q by Gauss-Seidel iteration where Y is the
%original delay-and-sum plot we want to deconvolve, and Q are the true
%source powers
for i=1:maxIterations;

    %Gauss-Seidel iteration. If the solution is negative set it to zero (to
    %ensure that we only have positive and not negative power)
    for n=1:M*N
        Q(n) = max(0, Y(n) - A(n, 1:n-1)*Q(1:n-1)' ...
            - A(n, n+1:end)*Q0(n+1:end)');
    end

    %Break criterion for convergence
    dX = (Q - Q0);
    maxd = max(abs(dX(:)))/mean(Q0(:));

    if  maxd < deps
        break;
    end

    Q0 = Q;
end

if i == maxIterations
    disp(['Stopped after maximum iterations (' num2str(maxIterations) ')'])
else
    disp(['Converged after ' num2str(i) ' iterations'])
end


function vec=DelaunayVar(TDB1,TDB2)
%%DELAUNAYVAR Get the Delaunay variables that are needed for tide models
%             involving Doodson numbers using the equations in the IERS
%             conventions.
%
%INPUTS: T The time as measured in Julian centuries Barycentric dynamical
%          time (TDB).
%
%OUTPUTS: vec A vector of the Delaunay variables in the order with all
%             units in RADIANS.
%             vec(1) Mean anomaly of the moon: l
%             vec(2) Mean anomaly of the sun: l'
%             vec(3) F=L-Omega, The mean longitude of the moon minus the
%                    mean longitude of the ascending node of the moon.
%             vec(4) Mean Elongation of the moon from the sun: D
%             vec(5) Mean Longitude of the Ascending Node of the Moon:
%                    Omega
%
%This function implements Equation 5.43 in Section 5.7.2 of [1]. The units
%in those equations are degrees (and arcseconds). However, in Equation 6.8
%in Section 6.2, it looks like the angles should be in radians, since one
%is using trigonometric functions. Thus, the return value here is put into
%radians to be convenient.
%
%REFERENCES:
%[1] G. Petit and B. Luzum, IERS Conventions (2010), International Earth
%    Rotation and Reference Systems Service Std. 36, 2010.
%
%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

    %The time as measured in Julian centuries Barycentric dynamical time
    %(TDB). The precision of the model is low enough that it shouldn't
    %matter that the two parts are added together.
    T=(TDB1+TDB2)/36525;

    vec=zeros(5,1);

    %The conversion from arcseconds to degrees
    sec2Deg=1/3600;

    %Mean anomaly of the moon: l
    vec(1)=134.96340251+sec2Deg*(1717915923.2178*T+31.8792*T^2+0.051635*T^3-0.00024470*T^4);
    %Mean anomaly of the sun: l'
    vec(2)=357.52910918+sec2Deg*(129596581.0481*T-0.5532*T^2+0.000136*T^3-0.00001149*T^4);
    %L-Omega, The mean longitude of the moon minus the mean longitude of the
    %ascending node of the moon.
    vec(3)=93.27209062+sec2Deg*(1739527262.8478*T-12.7512*T^2-0.001037*T^3+0.00000417*T^4);
    %Mean Elongation of the moon from the sun: D
    vec(4)=297.85019547+sec2Deg*(1602961601.2090*T-6.3706*T^2+0.006593*T^3-0.00003169*T^4);
    %Mean Longitude of the Ascending Node of the Moon: Omega
    vec(5)=125.04455501+sec2Deg*(-6962890.5431*T+7.4722*T^2+0.007702*T^3-0.00005939*T^4);

    %Convert from degrees to radians.
    vec=mod(vec*(pi/180),2*pi);
end

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


function signedcos = acos2d(alpha, beta)
%ACOS2D      4-quadrant arccosine function, in degrees.
%
%   ACOS2D(alpha, beta) computes the four-quadrant arccosine of the amgle
%   [alpha]. For arguments |alpha| > 1, the result is NaN. The resulting
%   angle is not uniquely determined by alpha, nor by the lengths or
%   order of the sides of the triangle (as in ATAN2), so an additional
%   argument [beta] is required. If [beta] < 180�, the small angle
%   (0� <= alpha <= 180�) is returned. If [beta] > 180�, the large angle
%   (180� < alpha < 360�) is returned.
%
%   See also acos2.

% Rody P.S. Oldenhuis
% Delft University of Technology
% oldenhuis@gmail.com
%
% Crated     : 23/Feb/2009
% Last edited: 30/Nov/2012

    % compute 4-quadrant cosine by calling ACOS2 directly
    signedcos = acos2(alpha, beta)*180/pi;

end


function n = order( val, base )
%Order of magnitude of number for specified base. Default base is 10.
%order(0.002) will return -3., order(1.3e6) will return 6.
%Author Ivar Smith

if nargin < 2
    base = 10;
end
n = floor(log(abs(val))./log(base));


%  Figure 3.32      Feedback Control of Dynamic Systems, 5e
%                        Franklin, Powell, Emami
%
%script to generate Fig. 3.32
clf;
k=7.5;
numCL=[k k];
denCL=[1 5 k-6 k];
t=0:.05:12;
y1=step(numCL,denCL,t);
k=13;
numCL=[k k];
denCL=[1 5 k-6 k];
y2=step(numCL,denCL,t);
k=25;
numCL=[k k];
denCL=[1 5 k-6 k];
y3=step(numCL,denCL,t);
axis([0 12 -1 3]);
plot(t,y1,t,y2,t,y3)
grid;
xlabel('Time (sec)');
ylabel('y(t)');
title('Fig. 3.32 transient responses')
axis('normal');
text(3,2,'K=7.5');
text(2.1,1.5,'K=13');
text(1.4,1.2,'K=25');


function Y = fillnans(varargin)
% FILLNANS replaces all NaNs in array using inverse-distance weighting.
%
% Y = FILLNANS(X) replaces all NaNs in the vector or array X by
% inverse-distance weighted interpolation:
%                       Y = sum(X/D^3)/sum(1/D^3)
% where D is the distance (in pixels) from the NaN node to all non-NaN
% values X. Values farther from a known non-NaN value will tend toward the
% average of all the values.
%
% Y = FILLNANS(...,'power',p) uses a power of p in the weighting
% function. The higer the value of p, the stronger the weighting.
%
% Y = FILLNANS(...,'radius',d) only used pixels < d pixels away in
% for weighted averaging.
%
% NOTE: Use in conjunction with INVDISTGRID to grid and interpolate x,y,z
% data.
%
% See also INPAINT_NANS
%
% Ian M. Howat, Applied Physics Lab, University of Washington
% ihowat@apl.washington.edu Ian M. Howat
% Version 1: 05-Jul-2007 17:28:57
%   Revision 1: 16-Jul-2007 17:47:43
%       Added increment expression to waitbar to reduce number of times its
%       called. Provided by John D'Errico.
%   Revision 2: 16-Jul-2007 18:40:34
%       Added radius option and 'option',value varargin parser.
%   Revision 3: 18-Jul-2007 10:25:23
%       Adopted several code efficiency revisions made by Urs, including
%       removing the waitbar.

%parse input and set defualts:
X = varargin{1}; %input array
Y = X; %output array
n = 2; %weighting power
d = 0; %distance cut-off radius (0= all pixels, no cut-off)
if nargin > 1 && nargin < 6
    for k=2:2:length(varargin)
        if isnumeric(varargin{k}) || ~isnumeric(varargin{k+1})
            error('Input arguments must be in ''option'',value form.')
        end
        switch lower(varargin{k})	% (Urs:less error prone)
            case 'power'
                n = varargin{k+1};
            case 'radius'
                d = varargin{k+1};
            otherwise
                error(['Unrecognized input argument: ',varargin{k}])
        end
    end
elseif nargin >= 6
    error('Too many input arguments')
end

%(Urs:use ISNAN()/NOT() once only)
ix=isnan(X);
[rn,cn]=find(ix);   %row,col of nans
ix=~ix;
[r,c]=find(ix);     %row,col of non-nans
ind=find(ix);       %index of non-nans

%Break distance-finding loops into with cut-off and without cut-off
%versions. The cutoff conditional statement adds time
%if cut-off values near the max pixel distance are used.

if d %distance cut-off loop
    d=d.^2;				% (Urs:allows first step without SQRT())
    for k = 1:length(rn)
        D = (rn(k)-r).^2+(cn(k)-c).^2;	% (Urs:no SQRT() here)
        Dd = D < d;
        if sum(Dd) ~= 0
            D=1./sqrt(D(Dd)).^n; %(Urs: Compute once only for valid <D>s)
            Y(rn(k),cn(k)) = sum(X(ind(Dd)).*D)./ sum(D);
        end
    end
else %no distance cut-off loop
    for k = 1:length(rn)
        D = 1./(sqrt((rn(k)-r).^2+(cn(k)-c).^2)).^n;% (Urs:compute once only)
        Y(rn(k),cn(k)) = sum(X(ind).*D)./sum(D);
    end
end


function result=SideWindowBoxFilter(im, radius, iteration)
%papers: 1) Sub-window Box Filter, Y.Gong, B.Liu, X.Hou, G.Qiu, VCIP2018, Dec.09, Taiwan
%        2) Side Window Filtering, H.Yin, Y.Gong, G.Qiu. CVPR2019
%implemented by Yuanhao Gong

r = radius; %the radius of the side window
k = ones(2*r+1,1)/(2*r+1); %separable kernel
k_L=k; k_L(r+2:end)=0; k_L = k_L/sum(k_L); %half kernel
k_R=flipud(k_L);
m = size(im,1)+2*r; n = size(im,2)+2*r; total = m*n;
[row, col]=ndgrid(1:m,1:n);
offset = row + m*(col-1) - total;
im = single(im);
result = im;
d = zeros(m,n,8,'single');

for ch=1:size(im,3)
    U = padarray(im(:,:,ch),[r,r],'replicate');
    for i = 1:iteration
        %all projection distances
        d(:,:,1) = conv2(k_L, k_L, U,'same') - U;
        d(:,:,2) = conv2(k_L, k_R, U,'same') - U;
        d(:,:,3) = conv2(k_R, k_L, U,'same') - U;
        d(:,:,4) = conv2(k_R, k_R, U,'same') - U;
        d(:,:,5) = conv2(k_L, k, U,'same') - U;
        d(:,:,6) = conv2(k_R, k, U,'same') - U;
        d(:,:,7) = conv2(k, k_L, U,'same') - U;
        d(:,:,8) = conv2(k, k_R, U,'same') - U;

        %find the minimal signed distance
        tmp = abs(d);
        [~,ind] = min(tmp,[],3);
        index = offset+total*ind;
        dm = d(index); %signed minimal distance
        %update
        U = U + dm;
    end
    result(:,:,ch) = U(r+1:end-r,r+1:end-r);
end


function [YM,Y]=multigauss(x,mi,sigm,c)
% [YM,Y]=multigauss(x,mu,sigm,c)
%
% computes multigaussian likelihood
%
% x   : data (columnwise vectors)
% sigm: variances vector  (diagonal of the covariance matrix)
% mu  : means
% c   :the weights
DEBUG=0;

[L,T]=size(x);

if DEBUG L,T,end

M=size(c,1);

if DEBUG M,end

% repeating, changing dimensions:
X=permute(repmat(x',[1,1,M]),[1,3,2]);      % (T,L) -> (T,M,L) one per mixture

Sigm=permute(repmat(sigm,[1,1,T]),[3,2,1]); % (L,M) -> (T,M,L)

Mu=permute(repmat(mi,[1,1,T]),[3,2,1]);     % (L,M) -> (T,M,L)

if DEBUG size(X),size(Mu),size(Sigm),pause;end

%Y=squeeze(exp( 0.5.*dot(X-Mu,(X-Mu)./Sigm))) % L dissapears: (L,T,M) -> (T,M)
lY=-0.5.*dot(X-Mu,(X-Mu)./Sigm,3);
% c,const -> (T,M) and then multiply by old Y
coef=(2.*pi).^(L./2).*sqrt(prod(sigm,1)); % c,const -> (T,M)
lcoef=repmat(log(c')-log(coef),[T,1]);

if DEBUG log(coef),lcoef,lY,pause;end

YM=exp(lcoef+lY);            % ( T,M ) one mixture per column
Y=sum(YM,2);                 % add mixtures


function hpdi = hpdi(x, p)
% HPDI - Estimates the Bayesian HPD intervals
%
%   Y = HPDI(X,P) returns a Highest Posterior Density (HPD) interval
%   for each column of X. P must be a scalar. Y is a 2 row matrix
%   where ith column is HPDI for ith column of X.

%   References:
%      [1] Chen, M.-H., Shao, Q.-M., and Ibrahim, J. Q., (2000).
%          Monte Carlo Methods in Bayesian Computation. Springer-Verlag.
%
% Copyright (C) 2001 Aki Vehtari

% This software is distributed under the GNU General Public
% Licence (version 3 or later); please refer to the file
% Licence.txt, included with the software, for details.

if nargin < 2
  error('Not enough arguments')
end

m=size(x,2);
pts=linspace(0.1,99.9-p,20);
pt1=prctile(x,pts);
pt2=prctile(x,p+pts);
cis=abs(pt2-pt1);
[foo,hpdpi]=min(cis);
if m==1
  hpdi=[pt1(hpdpi); pt2(hpdpi)];
else
  hpdpi=sub2ind(size(pt1),hpdpi,1:m);
  hpdi=[pt1(hpdpi); pt2(hpdpi)];
end


%   Distribution code Version 1.0 -- 02/31/2020 by Wei Liu Copyright 2020
%
%   The code is created based on the method described in the following paper
%   [1] "Real-time Image Smoothing via Iterative Least Squares", Wei Liu, Pingping Zhang,
%        Xiaolin Huang, Jie Yang, Chunhua Shen and Ian Reid, ACM Transactions on Graphics,
%        presented at SIGGRAPH 2020.
%
%   The code and the algorithm are for non-comercial use only.

%  ---------------------- Input------------------------
%  F:              input image, can be gray image or RGB color image
%  lambda:     \lambda in Eq.(1), control smoothing strength
%  gamma:       the \gamma in the Welsch's penalty in Eq. (18)
%  iter:           iteration number of the ILS

%  ---------------------- Output------------------------
%  U:             smoothed image

function U =ILS_Welsch_GPU(F, lambda, gamma, iter)

F = gpuArray(single(F)); % 'single' precision is very important to reduce the computational cost

c = 2;

[N, M, D] = size(F);
sizeI2D = [N, M];

otfFx = psf2otf_Dx_GPU(sizeI2D); % equal to otfFx = psf2otf(fx, sizeI2D) where fx = [1, -1];
otfFy = psf2otf_Dy_GPU(sizeI2D); % equal to otfFy = psf2otf(fy, sizeI2D) where fy = [1; -1];

Denormin = abs(otfFx).^2 + abs(otfFy ).^2;
Denormin = repmat(Denormin, [1, 1, D]);
Denormin = 1 + 0.5 * c * lambda * Denormin;

U = F;  % smoothed image

Normin1 = fft2(U);

for k = 1: iter

    % Intermediate variables \mu update, in x-axis and y-axis direction
    u_h = [diff(U,1,2), U(:,1,:) - U(:,end,:)];
    u_v = [diff(U,1,1); U(1,:,:) - U(end,:,:)];

    mu_h = c .* u_h - 2 .* u_h .* exp(- u_h .* u_h / (2 * gamma^2));
    mu_v = c .* u_v - 2 .* u_v .* exp(- u_v .* u_v / (2 * gamma^2));

    % Update the smoothed image U
    Normin2_h = [mu_h(:,end,:) - mu_h(:, 1,:), - diff(mu_h,1,2)];
    Normin2_v = [mu_v(end,:,:) - mu_v(1, :,:); - diff(mu_v,1,1)];

    FU = (Normin1 + 0.5 * lambda * (fft2(Normin2_h + Normin2_v))) ./ Denormin;
    U = real(ifft2(FU));

    Normin1 = FU;  % This helps to further enlarge the smoothing strength

end

U = gather(U);


%  Figure 3.3      Feedback Control of Dynamic Systems, 6e
%                        Franklin, Powell, Emami
% script to generate Fig. 3.3
%% fig3_03.m Example 3.4
% Frequency response
clf;
k=1;
num=1;                      % form numerator
den=[1 k];                  % form denominator
sys=tf(num,den);            % form system
% frequency range
w=logspace(-2,2);
[mag,phase]=bode(sys,w);    % compute frequency response
% plot frequency response
subplot(2,1,1); loglog(w,mag(:));xlabel('\omega (rad/sec)');
ylabel('M');title('Figure 3.3: Magnitude, phase');grid;
subplot(2,1,2); semilogx(w,phase(:));xlabel('\omega (rad/sec)');
ylabel('\phi (deg)')
grid;
% Bode grid
bodegrid


function J=imshift_3D(I,u,kernel)
% USAGE    : J=imshift_3D(I,u);
% FUNCTION : Shifts the 3D image I by u{1} along the lines and by u{2}
% along the columns and u{3} in the third dimension. 'u' is an arbitrary
% vector field structured as:
%                   u{1} = u1(x,y,z)
%                   u{2} = u2(x,y,z)
%                   u{3} = u2(x,y,z).
% If 'u' is a single vector (i.e. u1 = a, u2 = b and u3 = c) then all the
% pixels are shifted by the same amount. Note the structure of u is alwasys
% assumed to be a cell.
%
% This function uses cubic spline interpolation used in 'interp_3D.m' with
% half point symmetric image extensions (can be changed).
%
% DATE     : 23 November 2014 (updated 28 Jan 2015 by C Gilliam)
% AUTHOR   : Thierry Blu, mailto:thierry.blu@m4x.org

[M,N,P]=size(I);

if nargin == 2,
%     kernel= 'cubicspline';
    kernel='cubicOMOMS';
% kernel = 'bilinear';
end

if length(u{1})>1               % check to see if u is a single vector or a field
    [M0,N0,P0]=size(u{1});
    if M0==M&N0==N&P0==P

        % Generate x, y and z:
        x = repmat((1:M)',[1,N,P]);
        y = repmat((1:N), [M,1,P]);
        z = repmat(shiftdim((1:P),-1), [M,N,1]);

        % Interpolation:
        J=interp_3D(double(x-u{1}),double(y-u{2}),double(z-u{3}),double(I),kernel);  %single/double
        J=cast(J,class(I));
    else
        error('Input image and flow dimensions do not match!')
    end
else
    u=[u{:}];
    integer_shift=(norm(round(u)-u)<=1e-6);

    if integer_shift
        u=round(u);
        xshift=abs(u(1));
        yshift=abs(u(2));
        zshift=abs(u(3));
        switch sign(u(1))
            case -1
                I1=[I;I(end-(1:xshift)+1,:,:)];
            case 0
                I1=I;
            case 1
                I1=[I((xshift:-1:1),:,:);I];
        end
        switch sign(u(2))
            case -1
                I1=[I1 I1(:,end-(1:yshift)+1,:)];
            case 0
            case 1
                I1=[I1(:,(yshift:-1:1),:) I1];
        end

        switch sign(u(3))
            case -1
                I1=cat(3,I1,I1(:,:,end-(1:zshift)+1));
            case 0
            case 1
                I1=cat(3,I1(:,:,(zshift:-1:1)), I1);
        end

        J=I1((1:M)+max(0,-u(1)),(1:N)+max(0,-u(2)), (1:P)+max(0,-u(3)));
    else
        % Generate x, y and z:
        x = repmat((1:M)',[1,N,P]);
        y = repmat((1:N), [M,1,P]);
        z = repmat(shiftdim((1:P),-1), [M,N,1]);

        % Interpolation:
        J=interp_3D(x-u(1),y-u(2),z-u(3),double(I),kernel);
        J=cast(J,class(I));
    end
end


function value = tfn ( h, a )

%*****************************************************************************80
%
%% TFN calculates the T function of Owen.
%
%  Discussion:
%
%    Owen's T function is useful for computation of the bivariate normal
%    distribution and the distribution of a skewed normal distribution.
%
%    Although it was originally formulated in terms of the bivariate
%    normal function, the function can be defined more directly as
%
%      T(H,A) = 1 / ( 2 * pi ) *
%        Integral ( 0 <= X <= A ) e^( -H^2 * (1+X^2) / 2) / (1+X^2) dX
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 August 2006
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    D B Owen,
%    Tables for computing the bivariate normal distribution,
%    Annals of Mathematical Statistics,
%    Volume 27, pages 1075-1090, 1956.
%
%    J C Young and C E Minder,
%    Algorithm AS 76,
%    An Algorithm Useful in Calculating Non-Central T and
%    Bivariate Normal Distributions,
%    Applied Statistics,
%    Volume 23, Number 3, 1974, pages 455-457.
%
%  Parameters:
%
%    Input, real H, A, the arguments of the T function.
%
%    Output, real VALUE, the value of the T function.
%
  ngauss = 10;

  two_pi_inverse = 0.1591549430918953;
  tv1 = 1.0E-35;
  tv2 = 15.0;
  tv3 = 15.0;
  tv4 = 1.0E-05;
  weight = [ ...
    0.666713443086881375935688098933E-01, ...
    0.149451349150580593145776339658E+00, ...
    0.219086362515982043995534934228E+00, ...
    0.269266719309996355091226921569E+00, ...
    0.295524224714752870173892994651E+00, ...
    0.295524224714752870173892994651E+00, ...
    0.269266719309996355091226921569E+00, ...
    0.219086362515982043995534934228E+00, ...
    0.149451349150580593145776339658E+00, ...
    0.666713443086881375935688098933E-01];
  xtab = [
   -0.973906528517171720077964012084E+00, ...
   -0.865063366688984510732096688423E+00, ...
   -0.679409568299024406234327365115E+00, ...
   -0.433395394129247190799265943166E+00, ...
   -0.148874338981631210884826001130E+00, ...
    0.148874338981631210884826001130E+00, ...
    0.433395394129247190799265943166E+00, ...
    0.679409568299024406234327365115E+00, ...
    0.865063366688984510732096688423E+00, ...
    0.973906528517171720077964012084E+00 ];
%
%  Test for H near zero.
%
  if ( abs ( h ) < tv1 )
    value = atan ( a ) * two_pi_inverse;
%
%  Test for large values of abs(H).
%
  elseif ( tv2 < abs ( h ) )
    value = 0.0;
%
%  Test for A near zero.
%
  elseif ( abs ( a ) < tv1 )
    value = 0.0;
%
%  Test whether abs(A) is so large that it must be truncated.
%  If so, the truncated value of A is H2.
%
  else

    hs = - 0.5 * h * h;
    h2 = a;
    as = a * a;
%
%  Computation of truncation point by Newton iteration.
%
    if ( tv3 <= log ( 1.0 + as ) - hs * as )

      h1 = 0.5 * a;
      as = 0.25 * as;

      while ( 1 )

        rt = as + 1.0;
        h2 = h1 + ( hs * as + tv3 - log ( rt ) ) ...
          / ( 2.0 * h1 * ( 1.0 / rt - hs ) );
        as = h2 * h2;

        if ( abs ( h2 - h1 ) < tv4 )
          break
        end

        h1 = h2;

      end

    end
%
%  Gaussian quadrature on the interval [0,H2].
%
    rt = 0.0;
    for i = 1 : ngauss
      x = 0.5 * h2 * ( xtab(i) + 1.0 );
      rt = rt + weight(i) * exp ( hs * ( 1.0 + x * x ) ) / ( 1.0 + x * x );
    end

    value = rt * ( 0.5 * h2 ) * two_pi_inverse;

  end

  return
end


% This example shows how to find the modes of a birefringent
% (uniaxial) waveguide.  This waveguide is the same as the one
% considered in 'uniaxial_channel.m', except that the c-axis
% is now rotated by an angle of -pi/4 relative to the x axis.

n1 = 1.55;
n2x = 2.156;
n2y = 2.232;
n2z = 2.232;
theta = -pi/4;

e2xx = n2x^2*cos(theta)^2 + n2y^2*sin(theta)^2;
e2yy = n2y^2*cos(theta)^2 + n2x^2*sin(theta)^2;
e2xy = cos(theta)*sin(theta)*(n2x^2-n2y^2);
e2yx = e2xy;

Rx = 0.30;
Ry = 0.20;
side = 0.2;

dx = 0.0025;        % grid size (x)
dy = dx;            % grid size (y)

lambda = 1.00;      % wavelength
nmodes = 2;         % number of modes to compute

[x,y,xc,yc,nx,ny,epsxx,edges] = ...
    waveguidemeshfull([n1,sqrt(e2xx),n1],[side,2*Ry,side],2*Ry,Rx, ...
                  side,dx,dy);
[x,y,xc,yc,nx,ny,epsxy,edges] = ...
    waveguidemeshfull([0,sqrt(e2xy),0],[side,2*Ry,side],2*Ry,Rx, ...
                  side,dx,dy);
[x,y,xc,yc,nx,ny,epsyx,edges] = ...
    waveguidemeshfull([0,sqrt(e2yx),0],[side,2*Ry,side],2*Ry,Rx, ...
                  side,dx,dy);
[x,y,xc,yc,nx,ny,epsyy,edges] = ...
    waveguidemeshfull([n1,sqrt(e2yy),n1],[side,2*Ry,side],2*Ry,Rx, ...
                  side,dx,dy);
[x,y,xc,yc,nx,ny,epszz,edges] = ...
    waveguidemeshfull([n1,n2z,n1],[side,2*Ry,side],2*Ry,Rx, ...
                  side,dx,dy);

% Now we stretch out the mesh at the boundaries:
[x,y,xc,yc,dx,dy] = stretchmesh(x,y,[80,80,80,80],[4,4,4,4]);

[Hx,Hy,neff] = wgmodes (lambda, n2y, nmodes, dx, dy, epsxx, epsxy, epsyx, epsyy, epszz, '0000');

fprintf(1,'neff = %7.5f\n',neff);

figure(1);

for ii = 1:nmodes,
  subplot(nmodes,2,2*(ii-1)+1);
  contourmode(x,y,Hx(:,:,ii));
  title(sprintf('Hx (mode %d)',ii));
  for v = edges, line(v{:}); end
  subplot(nmodes,2,2*(ii-1)+2);
  contourmode(x,y,Hy(:,:,ii));
  title(sprintf('Hy (mode %d)',ii));
  for v = edges, line(v{:}); end
end


%% Dimensional Splitting: Front Tracking
% In this example, we consider the 2D scalar conservation law
%
% $$ u_t + (u^2/2)_x + (u^3/3)_y = 0, \qquad u(x,y,0)=u_0(x,y)$$
%
% which we solve using dimensional splitting. That is, we introduce two
% one-dimensional operators
%
% $$ S_x(t): \quad v_t + (v^2/2)_x = 0, \qquad v(x,0)=v_0(x)$$
%
% $$ S_y(t): \quad w_t + (w^3/3)_y = 0, \qquad w(y,0)=w_0(y)$$
%
% and construct the approximate solution from the formula
%
% $$u(x,t)\approx [S_x(0.5\Delta t)\circ S_y(\Delta t)\circ S_x(0.5\Delta t) ]^n u_0(x)$$
%
% As a one-dimensional solver, we will use front tracking. This algorithm
% makes a piecewise constant approximation to the flux function
% and then solves the 1-D hyperbolic problem *exactly*, given piecewise
% constant initial data.
%
% *Disclaimer*: The front-tracking code is built using arrays and is
% admittedly very slow, e.g., compared with the <testNTds.html NT
% central-difference code>. It is only meant to illustrate the concepts.
% For serious computing, one should use e.g., a C/C++ code built using
% pointers.

%% Initial setup
xmin=-1.0; xmax=1.0;
T = 2.0;
N = 50;
h = (xmax-xmin)/N;
x = xmin:h:xmax; y = 0.5*(x(1:end-1)+x(2:end));
[X,Y] = meshgrid(y,y);

%%
% The initial function u0 is equal -1 inside a circle of radius 0.4
% centered at (-1/2,-1/2), equal 1 inside a circle of radius 0.4 centered
% at (1/2,1/2), and zero otherwise. For later use, we define an anonymous
% function to do the computation of u0.
initData = (@(x,y) 1.0*((x+0.5).^2 + (y+0.5).^2 < 0.16) ...
   - 1.0*((x-0.5).^2 + (y-0.5).^2 < 0.16));
u0 = initData(X,Y);
contourf(X,Y,u0,-1:0.25:1); axis equal; colorbar, title('Initial data')

%% Number of time steps
% In the first example, we fix the grid resolution and compare the
% approximate solutions generated with four different splitting steps (n=1,
% 4, 16, 64). Generally, it makes sense to match the resolution of the
% front-tracking algorithm with the grid resolution. The resolution of the
% front-tracking method is determined by segments in the piecewise linear
% approximation of the flux functions. Here, we simply scale these segments
% to be inversely proportional with sqrt(N).
for i=1:4,
   tic;
   u=DimSplit(u0,x,x,'burgerRsol','cubRsol',0.1/sqrt(N),4^(i-1), T,...
      'wbar','periodic',[xmin xmax],[xmin xmax]);
   t=toc; st=sprintf('%4.2f',t);

   subplot(2,2,i);
   contourf(y,y,u,30), axis equal image; colorbar
   title( sprintf('Grid: %dx%d  Steps: %d', N, N, 4^(i-1)));
   xlabel(['Time used: ', st,' sec.']);
   p=get(gca,'position'); p([3 4])=p([3 4])+0.03;
   set(gca,'position',p,'XTickLabel',[]);
end
%%
% Looking at the plots, it is amazing to observe how well the operator
% splitting method resolves the dynamics of the problem using only one
% splitting step. The qualitative behavior of the red and blue "plumes" is
% captured almost correctly, even though the shape and position of the
% curved  shock is not correct. Increasing the number of splitting steps to
% four (CFL number of 12.5) ensures that all qualitative features of the
% solution are captured correctly. For 64 time steps, the effective CFL
% number is less than one and the front-tracking method is equivalent to a
% standard Godunov method. By considering accuracy versus runtime, the
% optimal number of splitting steps is most likely somewhere between four
% and sixteen.

%% Increasing grid resolution
% In the second example, we fix the CFL number to 20 and consider four
% different grid resolutions.
CFL=20;
for i=1:4,
   N= 32*(2^(i-1));
   h = (xmax-xmin)/N; delta=0.1/sqrt(N);
   x = xmin:h:xmax;
   y = 0.5*(x(1:end-1)+x(2:end));
   [X,Y] = meshgrid(y,y);
   u0=initData(X,Y);

   tic;
   Nstep=ceil(T/(CFL*h));
   u=DimSplit(u0,x,x,'burgerRsol','cubRsol',delta,Nstep,T,...
      'wbar','periodic',[xmin xmax],[xmin xmax]);
   t=toc; st=sprintf('%4.2f',t);

   subplot(2,2,i);
   pcolor(y,y,u), axis equal image; shading flat; colorbar
   title( sprintf('Grid: %dx%d, Steps: %d', N, N, Nstep));
   xlabel(['Time used: ', st,' sec.']);
   p=get(gca,'position'); p([3 4])=p([3 4])+0.03;
   set(gca,'position',p,'XTickLabel',[]);
end


% ir_example_kurtosis1
% example of kurtosis for edge-preserving denoising
% Copyright 2012-07-28, Jeff Fessler, University of Michigan

if ~exist('xtrue')
	N = 2^12;
	xtrue = ones(N,1);
	xtrue(end/2+1:end) = 2;
	plot(xtrue)

	sig = 0.2;
	rng(3)
	yi = xtrue + sig * randn(N,1);

	ax = [1 N 0 3];
	plot(yi, '.-'), axis(ax)

	ah = [0 3];
	hh = linspace(0, 3, 121);
	hp = @(y, c) bar(hh, hist(y, hh), c);

	sf = @(xh) text(.1, get(gca, 'ylim') * [0; 0.7], ...
		sprintf('\\sigma = %3.2f', std(xh(1:round(0.9*N/2)))));

	k1f = @(xh) mean((xh-mean(xh)).^4) / std(xh)^4 - 3;
	kf = @(xh) text(.1, get(gca, 'ylim') * [0; 0.4], ...
		sprintf('\\gamma_2 = %3.2f', k1f(xh(1:round(0.9*N/2)))));
end

% use local psf to help select beta
if ~isvar('R1'), printm 'R1'
	f.l2b = 2;
	mask = true(N,1);
	R1 = Reg1(mask, 'beta', 2^f.l2b);
%	qpwls_psf(1, R1, 1, mask, 1, 'loop', 0); % choose beta
end

if ~isvar('init'), printm 'init'
	psf = qpwls_psf(1, R1, 1, mask, 1);
	init = conv2(psf, yi, 'same');
end

	nn = N/2 + (-100:102);
%	nn = 1:N;
	ax = [minmax(nn)' 0 3];
	clf, pl = @(i,j) subplot(420+(i-1)*2+j);

	pl(1,1)
	plot(nn, xtrue(nn), 'g.-'), axis(ax), xtick(N/2)
	title 'true signal'

	pl(2,1)
	plot(nn, yi(nn), 'r.-'), axis(ax), xtick(N/2)
	title 'data with additive white gaussian noise'
	pl(2,2)
	hp(yi, 'r'), axisx(ah), title 'Histogram'
	sf(yi), kf(yi)

	pl(4,1)
	plot(nn, init(nn), 'm.-'), axis(ax), xtick(N/2)
	pl(4,2)
	hp(init, 'm'), axisx(ah)
	sf(init), kf(init)

if 0
	pl(1,2)
	ii = N/2+1+[-13:13];
	plot(ii, xtrue(ii), 'g.-', ii, init(ii), 'm.-')
	axis([minmax(ii)' 0.5 2.5])
end

if ~isvar('xpwls1'), printm 'pwls1'
	f.niter1 = 20;
	xpwls1 = pwls_pcg1(init(mask), 1, 1, yi, R1, 'niter', f.niter1);
	plot(xpwls1), axis(ax)
end

	pl(3,1)
	plot(nn, xpwls1(nn), 'y.-'), axis(ax), xtick(N/2)
	title 'PWLS with quadratic regularization'
	pl(3,2)
	hp(xpwls1, 'y'), axisx(ah)
	sf(xpwls1), kf(xpwls1)

if ~isvar('R2'), printm 'R2' % use small delta to show kurtosis
	R2 = Reg1(mask, 'beta', 6*2^f.l2b, 'pot_arg', {'huber', 0.01});
%	qpwls_psf(1, R2, 1, mask, 1);
end

if 0 || ~isvar('xpwls2'), printm 'pwls2'
	f.niter2 = 400;
	xpwls2 = pwls_pcg1(init(mask), 1, 1, yi(:), R2, 'niter', f.niter2);
end

	pl(4,1)
	plot(nn, xpwls2(nn), 'c.-'), axis(ax), xtick(N/2)
	title 'PWLS with TV (strongly edge-preserving) regularization'
	pl(4,2)
	hp(xpwls2, 'c'), axisx(ah)
	axis([0 3 0 300])
	sf(xpwls2), kf(xpwls2)

if 0
	pl(1,2)
	ii = N/2+1+[-13:13];
	plot(ii, xtrue(ii), 'g.-', ii, xpwls1(ii), 'y.-', ii, xpwls2(ii), 'c.-')
	axis([minmax(ii)' 0.5 2.5])
end

%	ir_savefig c ir_example_kurtosis1a


function y = R3R(x,batch)
% R3R is a repeated running medians of 3.
%
% Usage: y = R3R(x)
%
%   where  x is the input vector with length at least 3
%          y is the return vector of the same length as x
%

% See John Wilder Tukey, "EXPLORATORY DATA ANALYSIS".
% Addison-Wesley Publishing Co. 1977. Chpt 7A, 7D

if min(size(x)) ~= 1, error('Input must be a vector'); end
x = x(:); xlen = length(x); cont = 1; y = x;
if nargin<2, batch = 0; end
if xlen < 3,
   if ~batch, warning('Input vector must be at least 3 elements long'); end
   cont = 0;
end
if cont,
   % running median
   for ii = 2:xlen-1,
      y(ii) = median(x(ii-1:ii+1));
   end
   % compute the low-end point
   delta = abs( y(3)-y(2) );
   slope = sign( y(3)-y(2) );
   switch slope
   case 1
      if y(2)-y(1)<=0 | y(2)-y(1)>=2*delta, y(1) = y(2) - 2*delta; end
   case -1
      if y(1)-y(2)<=0 | y(1)-y(2)>=2*delta, y(1) = y(2) + 2*delta; end
   case 0
      y(1) = y(2);
   end
   % compute the high-end point
   delta = abs( y(xlen-1)-y(xlen-2) );
   slope = sign( y(xlen-1)-y(xlen-2) );
   switch slope
   case 1
      if y(xlen)-y(xlen-1)<=0 | y(xlen)-y(xlen-1)>=2*delta,y(xlen)=y(xlen-1)+2*delta;end
   case -1
      if y(xlen-1)-y(xlen)<=0 | y(xlen-1)-y(xlen)>=2*delta,y(xlen)=y(xlen-1)-2*delta;end
   case 0
      y(xlen) = y(xlen-1);
   end
end
% 3-ing to death?
if ~isequal(y(2:xlen-1),x(2:xlen-1)) & xlen > 3, y = R3R(y); end

return


function N = facenorm(X,Y,Z)

% facenorm compute alternate surface normals for OpenGL surface plots
%
% N = facenorm(X,Y,Z);
%
% X,Y,Z surface coordinates as used with surf
% N     3D array with normal coordinates to be used as value for
%       'VertexNormals' property in surface plots that use OpenGL renderer
%       and flat lighting
%
% EXAMPLE:
%
% % generate some demo data
% [Y,Z,X] = cylinder([0.8 1 1 0.8],144);
% idxShift = mod(1:size(X,2),4)>1;
% X(2,idxShift) = X(2,idxShift)-0.2;
% X(3,idxShift) = X(3,idxShift)+0.2;
%
%
% % standard surf plot
% figure(1)
% surf(X,Y,Z,'EdgeAlpha',0.2,'FaceColor','c')
% axis equal
% light('Position',[0 0 1],'Style','infinite')
% view(0,60)
%
%
% % same plot with alternate surface normals
% % (giving symmetrical lighting, as it should)
% figure(10)
% surf(X,Y,Z,'EdgeAlpha',0.2,'FaceColor','c',...
% 'VertexNormals',facenorm(X,Y,Z))
% axis equal
% light('Position',[0 0 1],'Style','infinite')
% view(0,60)
%
% See also surfo

% Andres, 2009-07-09
% v1.01  with improved code efficiency as suggested by Jan Simon

% input checking left to surf et.al. ...

if numel(Z) > numel(X) || numel(Z) > numel(Y);
    [X,Y] = meshgrid(X,Y);
end

coord = cat(3,X,Y,Z);

% edge vectors
d1 = diff(coord,1,1);
d2 = diff(coord,1,2);

% normals of opposing pairs of edge vectors
% (i.e. at the opposing corners of the quadrilaterals)
n1 = cross_plain(d2(1:end-1,:,:), d1(:,1:end-1,:));
n2 = cross_plain(d2(2:end, :, :), d1(:, 2:end, :));

% add the normals to get an average normal of the face
n = n1 + n2;

% normalize
mag = sqrt(sum(n.^2,3));
mag(mag==0)=eps;
n = n./repmat(mag,[1 1 3]);

% arrange data for surf's 'VertexNormals' property
N = NaN(size(n)+[1 1 0]);
N(2:end,2:end,:) = n;

function c = cross_plain(a,b)

% cross_plain vector cross product without overhead
%
% c = cross_plain(a,b) returns the cross product of the vectors a and b.
%
% Faster direct cross product calculation without input checking.

c = cat(3, ...
    a(:, :, 2) .* b(:, :, 3) - a(:, :, 3) .* b(:, :, 2), ...
    a(:, :, 3) .* b(:, :, 1) - a(:, :, 1) .* b(:, :, 3), ...
    a(:, :, 1) .* b(:, :, 2) - a(:, :, 2) .* b(:, :, 1));


% TIMEDEP This code solves the nonlinear parabolic pde
%
% u_t = u_xx + exp(u); u(0,t) = u(1,t) = 0; u(x,0) = 0; 0 < t < 1.
%
% with the backward Euler discretization. Newton's method is used
% for the nonlinear solver. The Jacobian is tridiagonal, so we
% use the banded differencing function.
%
% The value of u at the current time and the time step are passed
% to the nonlinear residual as MATLAB global variables.
%
% This problem is 1-D, so we can store the time history of the
% integration and draw a surface plot.
%
global uold dt
dt=.1;
nx=63; nt=1+1/dt;
dx=1/(nx+1);
tval=0:dt:1;
xval=0:dx:1;
%
% Use tight tolerances, Newton's method, and a tridiagonal Jacobian.
%
tol=[1.d-6,1.d-6];
parms=[40, 1, 0, 1, 1, 1];
uhist=zeros(nx+2,nt);
uold=zeros(nx,1);
for it=1:nt-1
    [unew,it_hist,ierr]=nsold(uold,'ftime',tol,parms);
    uhist(2:nx+1,it+1)=unew;
    uold=unew;
end
%
% Plot the results.
%
mesh(tval,xval,uhist)


function [param]=db3w(input)
% [param] = db3w(input)
% Dead beat controller for processes of 3rd order (weak version).
% This function computes parameters of the controller (r0, q0, q1, q2, p1, p2).
% Output of the controller is calculated follows:
%
%                  r0                            q0 + q1*z^-1 + q2*z^-2
% U(z^-1) = ----------------------- * W(z^-1) - ------------------------ * Y(z^-1)
%            1 + p1*z^-1 + p2*z^-2                1 + p1*z^-1 + p2*z^-2
%
% where q2=0 and p2=0
% The controller parameters are calculated for step change of W.
%
%% Transfer function of the controlled system is:
%
%               b1*z^-1 + b2*z^-2 + b3*z^-3
% Gs(z^-1) = ---------------------------------
%             1 + a1*z^-1 + a2*z^-2 + a3*z^-3
%
% Input: input ... input parameters
%                  input(1) ... a1
%                  input(2) ... b1
%                  input(3) ... a2
%                  input(4) ... b2
%                  input(5) ... a3
%                  input(6) ... b3
% Output: param ... controller parameters
%                   param(1) ... r0
%                   param(2) ... q0
%                   param(3) ... q1
%                   param(4) ... q2
%                   param(5) ... p1
%                   param(6) ... p2

a1=input(1);
b1=input(2);
a2=input(3);
b2=input(4);
a3=input(5);
b3=input(6);

r0 = 1/b1;
q0 = -a1/b1;
q1 = -a2/b1;
q2 = -a3/b1;
p1 = b2/b1;
p2 = b3/b1;

param=[r0; q0; q1; q2; p1; p2];


function [] = main(file, k, iterations)
    %=======================================
    %           Initialising Data
    %=======================================
    % k = 3;
    % iterations = 20;
    % file = 'yeast_test.txt';
    data = load(file);
    rows = size(data, 1);
    cols = size(data, 2);
    data = data(1:rows, 1:cols-1);
    clusters = randi([1 k], rows, 1);
    clustered_data = [data clusters];
    mean_matrix = zeros(k, cols-1);

    %=======================================
    %           Calculating Mean
    %=======================================
    for i = 1:k
       index = clustered_data(:, end) == i;
       indexed_data = clustered_data(index, 1:end-1);
       mean_matrix(i, :) = mean(indexed_data);

    end

    %=======================================
    %           Computing Error
    %=======================================
    error = get_error(clustered_data, mean_matrix);
    fprintf('After initialization: error = %.4f \n', error);

    %=======================================
    %           Starting Iterations
    %=======================================
    for p = 1:iterations
       for q = 1:rows
          %=======================================
          % Deciding which Cluster data belongs
          %=======================================
          dist = get_euclidean(data(q, :), mean_matrix);
          [minimum_row, minimum_col] = min(dist);
          clusters(q) = minimum_col;
       end
       clustered_data = [data, clusters];

       %=======================================
       %          Calculating Mean
       %=======================================
       for i = 1:k
          index = clustered_data(:, end) == i;
          indexed_data = clustered_data(index, 1:end-1);
          mean_matrix(i, :) = mean(indexed_data);
       end
       %=======================================
       %           Computing Error
       %=======================================
       error = get_error(clustered_data, mean_matrix);
       fprintf('After iteration %d: error = %.4f \n', p, error);
    end
end

function [error] = get_error(data, mean_matrix)
    %=======================================
    %           Computing Error
    %=======================================
    error = 0;
    for j = 1: size(data, 1)
       c = data(j, end);
       dist = get_euclidean(data(j, 1:end-1), mean_matrix(c, 1:end));
       error = error + dist;
    end
end

function [distance_matrix] = get_euclidean(data, mean_matrix)
    %=======================================
    %           Calculating Euclidean
    %=======================================
    dist = data - mean_matrix;
    dist = dist.^2;
    dist = sum(dist, 2);
    distance_matrix = sqrt(dist);
end


function mColormap = gui_Colormap_RedGrayGreen(nSize)

% If size is not specified, set it to 256
if nargin < 1
  nSize = 256;
end
nPart = floor(nSize / 2);

mRedPart = [];
mGreenPart = [];

for nCnt = 1:nPart
  mRedPart = [mRedPart; 0.75  (nCnt*(0.75/nPart)) (nCnt*(0.75/nPart))];
  mGreenPart = [mGreenPart; (0.75 - (nCnt*(0.75/nPart))) (0.75 - (nCnt*(0.75/nPart))) 0.75];
end

mColormap = [mRedPart; mGreenPart];


function u = u_hat ( x )

%*****************************************************************************80
%
%% U_HAT evaluates the target function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 March 2011
%
%  Author:
%
%    Jeff Borggaard, John Burkardt, Catalin Trenchea, Clayton Webster
%
%  Parameters:
%
%    Input, real X(*), the evaluation points.
%
%    Output, real U(*), the function values.
%
  u = x .* ( 1 - x.^2 );

  return
end


function mean = gamma_mean ( a, b, c )

%*****************************************************************************80
%
%% GAMMA_MEAN returns the mean of the Gamma PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A, B, C, the parameters of the PDF.
%    0.0 < B,
%    0.0 < C.
%
%    Output, real MEAN, the mean of the PDF.
%
  mean = a + b * c;

  return
end


%% compile
%mex -O ba_interp2.cpp

%% The mandrills eye
clear
IMG=load('mandrill');
IMG = ind2rgb(IMG.X, IMG.map);
[Dx Dy] = meshgrid(-25:0.1:25, -25:0.1:25);

R = [cos(pi/18) sin(pi/18); -sin(pi/18) cos(pi/18)];
RD = R * [Dx(:)'; Dy(:)'];
RDx = reshape(RD(1,:), size(Dx))+320;
RDy = reshape(RD(2,:), size(Dy))+42;

methods = {'nearest', 'linear', 'cubic'};
la=nan(1,3);
for i=1:3
  tic;
  IMG_R = ba_interp2(IMG, RDx, RDy, methods{i});
  elapsed=toc;

  IMG_R_M = nan(size(IMG_R));
  tic;
  for c=1:size(IMG,3)
    IMG_R_M(:,:,c) = interp2(IMG(:,:,c), RDx, RDy, ['*' methods{i}]);
  end
  elapsed_matlab=toc;

  la(i) = subplot(2,2,i);
  imshow(IMG_R);
  difference = max(max(max(abs(IMG_R-IMG_R_M))));
  title({...
    sprintf('Rotation and zoom using %s interpolation took %gs.', methods{i}, elapsed), ...
    sprintf('Speedup against inbuilt method by a factor of %g', elapsed_matlab/elapsed), ...
    sprintf('The maximum difference with the built in method was %g', difference)});
  end
linkaxes(la(:));

%% The mandrills eye single
clear
IMG=load('mandrill');
IMG = single(ind2rgb(IMG.X, IMG.map));
[Dx Dy] = meshgrid(single(-25:0.1:25), single(-25:0.1:25));

R = single([cos(pi/18) sin(pi/18); -sin(pi/18) cos(pi/18)]);
RD = R * [Dx(:)'; Dy(:)'];
RDx = reshape(RD(1,:), size(Dx))+320;
RDy = reshape(RD(2,:), size(Dy))+42;

methods = {'nearest', 'linear', 'cubic'};
la=nan(1,3);
for i=1:3
  tic;
  IMG_R = ba_interp2(IMG, RDx, RDy, methods{i});
  elapsed=toc;

  IMG_R_M = nan(size(IMG_R));
  tic;
  for c=1:size(IMG,3)
    IMG_R_M(:,:,c) = interp2(IMG(:,:,c), RDx, RDy, ['*' methods{i}]);
  end
  elapsed_matlab=toc;

  la(i) = subplot(2,2,i);
  imshow(IMG_R);
  difference = max(max(max(abs(IMG_R-IMG_R_M))));
  title({...
    sprintf('Rotation and zoom using %s interpolation took %gs.', methods{i}, elapsed), ...
    sprintf('Speedup against inbuilt method by a factor of %g', elapsed_matlab/elapsed), ...
    sprintf('The maximum difference with the built in method was %g', difference)});
  end
linkaxes(la(:));

%% Cumulative effect of resampling.
clear
IMG=load('mandrill');
IMG = ind2rgb(IMG.X, IMG.map);
[Dx Dy] = meshgrid(-349.5:1:349.5, -349.5:1:349.5);

R = [cos(pi/18) sin(pi/18); -sin(pi/18) cos(pi/18)];
RD = R * [Dx(:)'; Dy(:)'];
RDx = reshape(RD(1,:), size(Dx))+350;
RDy = reshape(RD(2,:), size(Dy))+350;

methods = {'nearest', 'linear', 'cubic'};
la=nan(1,numel(methods));
for i=1:numel(methods)
  IMG_R{i} = IMG;
  IMG_R{i}(end+1:700,:,:) = 0;
  IMG_R{i}(:,end+1:700,:) = 0;
  IMG_R{i} = circshift(IMG_R{i}, ceil([[700-size(IMG,1) 700-size(IMG,2)]/2, 0]));
  imshow(IMG_R{i});
end
[X Y] = meshgrid(1:700, 1:700);
mask = ((X-350).^2+(Y-350).^2)<350^2;
for j=1:36
  for i=1:numel(methods)
    tic;
    IMG_R{i} = ba_interp2(IMG_R{i}, RDx, RDy, methods{i});
    IMG_R{i}(repmat(~mask, [1 1 3])) = 0;
    elapsed=toc;

    la(i) = subplot(1,3,i);
    imshow(IMG_R{i});
    title(sprintf('Rotating a mandrill %g times by 10degree using %s interpolation.', j, methods{i}));
    axis([100 600 100 600]);
  end
  drawnow
end
linkaxes(la(:));

for i=1:numel(methods)
  imwrite(IMG_R{i}, sprintf('mandril_%s.png', methods{i}), 'Alpha', double(mask));
end


function Ip=perm2PermMatrix(p)
%%PERM2PERMMATRIX Given a permutation of the values 1:n, obtain the
%                 permutation matrix that corresponds to the permutation.
%
%INPUTS: p A 1Xn or nX1 permutation of the values 1:n.
%
%OUTPUTS: Ip A permutation matrix such that Ip*(1:n).'=p.
%
%The creation of a permutation matrix from a permutation basically involves
%rearranging the columns of an identity matrix.
%
%EXAMPLE:
% p=[3;1;4;5;2];
% Ip=perm2PermMatrix(p);
% all(Ip*(1:5).'==p)
%
%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

n=length(p);
Ip=zeros(n,n);
for i=1:n
    Ip(i,p(i))=1;
end
end

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


function X = find_line_intersection(P1,V1,P2,V2)

if(length(P1) ~= 2)
    error('This function only works in 2D');
end

A = [V1(1),-V2(1) ; V1(2) -V2(2)];
B = P2-P1;
if(det(A) == 0)
    X = [];
    return;
end

K = inv(A)*B;

X = P1 + K(1)*V1;


clear;clc;
ts = 0 : 550;   % 时间

x0=[0.000001];   % 最初感染率，百万分之一

% lambda   日接触率
lambdas = [0.15, 0.07, 0.05, 0.025, 0.0125];
infective_matrix = zeros(length(ts),length(lambdas));

for i = 1 : length(lambdas)
  lambda = lambdas(i);
  [t,x] = ode45(@(t,y) ill_si(t,y,lambda), ts, x0);
  infective_matrix(:,i) = x(:,1);
end

plot(t, infective_matrix);
legend(num2str(lambdas(1)), num2str(lambdas(2)), num2str(lambdas(3)), num2str(lambdas(4)), num2str(lambdas(5)));
title('SI模型');
grid;


function y = gam_lpdf(x,a,b)
%GAM_LPDF Log of Gamma probability density function (lpdf).
%
%   Y = GAM_LPDF(X,A,B) Returns the gamma lpdf with
%   shape A and inverse scale B, at the values in X.
%
%   The size of X is the common size of the input arguments. A
%   scalar input functions as a constant matrix of the same size as
%   the other inputs.
%
%   The parameterization is as in Gelman, Carlin, Stern, Dunson, Vehtari,
%   and Rubin (2013). Bayesian Data Analysis, third edition.
%
% Copyright (c) 1998-2004 Aki Vehtari

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

if nargin < 3,
  error('Requires three input arguments.');
end

%y = b.^a/gamma(a)*x^(a-1)*exp(-b*x);
y = a.*log(b)-gammaln(a)+(a-1).*log(x)-b.*x;


%% MULTIGRID OF FOR THE STOKES EQNS IN 2D
%
% This example is to show the convergence of multigrid methods for various
% finite element approximation of the Stokes equation on the unit square:
%
%       -div(mu*grad u) + grad p = f in \Omega,
%                        - div u = 0  in \Omega,
%                              u = g_D  on \Gamma.
%
% with the pure Dirichlet boundary condition.
%
% Reference
%
% M. Wang and L. Chen. Multigrid Methods for the Stokes equations
% using Distributive Gauss-Seidel Relaxations based on the Least Squares
% Commutator. Journal of Scientific Computing. 56(2): 409-431, 2013.

clear variables;
close all;

%% Setting
[node,elem] = squaremesh([0,1,0,1],0.125);
% [node,elem] = circlemesh(0,0,1,0.25);
% [node,elem] = uniformrefine(node,elem);
bdFlag = setboundary(node,elem,'Dirichlet');
mesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);
figure;
showmesh(node,elem); pause(0.5);
% pde
pde = Stokesdata1;
%  pde = StokesZulehnerdata;
option.L0 = 0;
option.maxIt = 4;
option.printlevel = 1;
option.plotflag = 0;
option.rateflag = 0;

%% MG options
option.solver = 'asmg';
option.smoothingstep = 2;
option.smootherbarSp = 'SGS';

%% CR-P0 element
disp('CR-P0')
option.elemType = 'CRP0';
femStokes(mesh,pde,option);

%% P2-P0 element
disp('P2-P0')
option.elemType = 'P2P0';
femStokes(mesh,pde,option);

%% P2-P1 element
disp('P2-P1')
option.elemType = 'P2P1';
option.solver = 'asmg';
femStokes(mesh,pde,option);

%% isoP2-P0 element
disp('isoP2-P0')
option.elemType = 'isoP2P0';
femStokes(mesh,pde,option);

%% isoP2-P1 element
disp('isoP2-P1')
option.elemType = 'isoP2P1';
femStokes(mesh,pde,option);

%% P1b-P1 element
disp('P1b-P1')
option.elemType = 'P1bP1';
femStokes(mesh,pde,option);


function fI = faceinterpolate3(f,node,face,quadOrder)
%% FACEINTERPOLATE3 interpolate to face elements RT0.
%
% uI = faceinterpolate3(u,node,face) interpolates a given function u
% into the lowesr order RT0. The coefficient is given by the face integral
% int_f u*n ds.
%
% Example
%
%
%    [node,elem] = cubemesh([-1,1,-1,1,-1,1],1);
%    maxIt = 3;
%    pde = polynomialdata0;
%    err = zeros(maxIt,1);
%    N = zeros(maxIt,1);
%    for i =1:maxIt
%      [node,elem] = uniformrefine3(node,elem);
%      uI = faceinterpolate3(pde.u,node,elem);
%      err(i) = getL2error3RT0(node,elem,pde.u,uI);
%      N(i) = size(u,1);
%    end
%     figure;
%     showrate(N,err,2,'r-+','||u - u_I||');
%
% See also edgeinterpolate, edgeinterpolate1, edgeinterpolate2
%
% Created by Lin Zhong and Ming Wang at July, 2012.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

%%
NF = size(face,1);
v12 = node(face(:,2),:) - node(face(:,1),:);
v13 = node(face(:,3),:) - node(face(:,1),:);
nVec = mycross(v12,v13);

%% assemble the right hand side
if ~exist('quadOrder','var'), quadOrder = 2; end
[lambda,weight] = quadpts(quadOrder);
nQuad = size(lambda,1);
bt = zeros(NF,3);
for p = 1:nQuad
    pxy = lambda(p,1)*node(face(:,1),:) ...
		+ lambda(p,2)*node(face(:,2),:) ...
		+ lambda(p,3)*node(face(:,3),:);
    bt = bt + weight(p)*f(pxy);
end
fI = dot(nVec,bt,2)/2;


% Compute empirical p-vals under the null hypothesis that observed samples
% come from a given surrogate distribution. P-values for Type I error in
% rejecting the null hypothesis are obtained by finding the proportion of
% samples in the distribution that
% (a) are larger than the observed sample (one-sided test)
% (b) are larger or smaller than the observed sample (two-sided test).
%
% This function is based on Arnaud Delorme's statcond:COMPUTE_PVALS
% function from EEGLAB
%
% Inputs:
%
%   distribution:   [d1 x d2 x ... x dM x N] matrix of surrogate samples.
%                   distribution(i,j,k,...,:) is a collection of N samples
%                   from a surrogate distribution.
%   observed:       [d1 x d2 x ... x dM] matrix of observations.
%   tail:           can be 'one' or 'both' indicating a one-tailed or
%                   two-tailed test
% Outputs:
%
%   pvals:          [d1 x d2 x ... x dM] matrix of p-values specifying
%                   probability of Type I error in rejecting the null
%                   hypothesis
%
% Author: Tim Mullen and Arnaud Delorme, SCCN/INC/UCSD

% Copyright: Tim Mullen and Arnaud Delorme
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. 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.
%
% 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.

function pvals = stat_surrogate_pvals(distribution,observed,tail)
numDims = ndims(distribution);
if iscolumn(distribution)
	numDims = 1;
end

n = size(distribution, numDims);
% once support for matlab <= R2016b is dropped:
% pvals = sum(distribution >= observed, numDims) / n;
pvals = sum(bsxfun(@ge, distribution, observed), numDims) / n;

if any(strcmpi(tail, {'right', 'one'}))
	% nothing to be done
	return;
end

p_left = 1 - pvals + sum(bsxfun(@eq, distribution, observed), numDims) / n;

if strcmpi(tail, 'both')
	pvals = 2 * min(pvals, p_left);
elseif strcmpi(tail, 'left')
	pvals = p_left;
else
	error('invalid value for tail: "%s", should be left, right, one or both', tail);
end

end


% Chapter 15 - Local and Global Bifurcations.
% Programs_15a - Determining the coefficients of the Lyapunov function
% for a Lienard system.
% Copyright Birkhauser 2013. Stephen Lynch.

% V3=[V30;V21;V12;V03], V4=[V40;V31;V22;V13;V04;eta4],
% V5=[V50;V41;V32;V23;V14;V05],V6=[V60;V51;V42;V33;V24;V15;V06;eta6]
% Symbolic Math toolbox required.

% When determining coefficients of V_{4m} set V_{2m,2m}=0.
% When determining coefficients of V_{4m+2} set V_{2m,2m+2}+V_{2m+2,2m}=0.

clear all

syms a1 a2 b2 a3 b3 a4 b4 a5 b5;
A=[3 0 -2 0;0 0 1 0;0 -1 0 0;0 2 0 -3];
B=[b2; 0; a2; 0];

V3=A\B

A=[0 -1 0 0  0 -1;0 3 0 -3 0 -2;0 0 0 1 0 -1;4 0 -2 0 0 0;0 0 2 0 -4 0; 0 0 1 0 0 0];
B=[a3; -2*a2*b2; 0; b3-2*a2^2;0;0];

V4=A\B

A=[5 0 -2 0 0 0;0 0 3 0 -4 0;0 0 0 0 1 0;0 -1 0 0 0 0;0 4 0 -3 0 0;0 0 0 2 0 -5];
B=[b4-10*a2^2*b2/3;0;0;a4-2*a2^3;-2*a2*b3;0];

V5=A\B

A=[6 0 -2 0 0 0 0 0;0 0 4 0 -4 0 0 0;0 0 0 0 2 0 -6 0;0 0 1 0 1 0 0 0;
   0 -1 0 0 0 0 0 -1;0 5 0 -3 0 0 0 -3;0 0 0 3 0 -5 0 -3;0 0 0 0 0 1 0 -1];
B=[b5-6*a2*a4-4*a2^2*b2^2/3+8*a2^4;16*a2^4/3+4*a2^2*b3/3-8*a2*a4/3;0;0;
   a5-8*a2^3*b2/3;-2*a2*b4+8*a2^3*b2+2*a2*b2*b3-4*a4*b2;
   16*a2^3*b2/3+4*a2*b2*b3/3-8*a4*b2/3;0];

V6=A\B

L0=-a1
eta4=V4(6,1);
[n,d]=numden(-3/8*a3+1/4*a2*b2);
L1=n
a3=2*a2*b2;
eta6=V6(8,1);
[n,d]=numden(-5/16*a5+1/8*a2*b4-5/24*a2*b2*b3+5/12*a4*b2);
L2=n

% End of Programs_15a.


function c=ref_rdgtii(f,g,a,M)
%REF_RDGTII  Reference Real DGT type II
%   Usage:  c=ref_rdgt(f,g,a,M);
%
%   Linear algebra version of the algorithm. Create big matrix
%   containing all the basis functions and multiply with the transpose.

L=size(f,1);

b=L/M;
N=L/a;

Mhalf=ceil(M/2);

F=zeros(L,M*N);

l=(0:L-1).';

for n=0:N-1

  % Do the unmodulated coefficient.
  F(:,M*n+1)=circshift(g,n*a+floor(a/2));

  for m=1:Mhalf-1
    F(:,M*n+2*m)=sqrt(2)*cos(2*pi*m*(l+.5)/M).*circshift(g,n*a+floor(a/2));

    F(:,M*n+2*m+1)=sqrt(2)*sin(2*pi*m*(l+.5)/M).*circshift(g,n*a+floor(a/2));

  end;

  if mod(M,2)==0
    F(:,M*(n+1))=cos(pi*l).*circshift(g,n*a+floor(a/2));
  end;

end;

% dot-transpose will work because F is real.
c=F.'*f;


function [x1,y1,x2,y2] = retrieveCoordinates(index,scale)
% compute coordinates [x1,y1,x2,y2] from an index which represent the a
% window in the scale^4 space of all the windows

image_area = scale*scale;
index1 = mod(index, image_area);
index2 = floor(index/image_area);

x1 = mod(index1, scale) + 1;
y1 = floor(index1/scale) + 1;

x2 = mod(index2, scale) + 1;
y2 = floor(index2/scale) + 1;

return


function [ grid_weight, grid_point ] = sparse_grid_cfn ( dim_num, level_max, ...
  rule, point_num )

%*****************************************************************************80
%
%% SPARSE_GRID_CFN computes a sparse grid based on a CFN 1D rule.
%
%  Discussion:
%
%    The 1D quadrature rule is assumed to be Closed Fully Nested.
%
%    Closed Fully Nested rules include Clenshaw Curtis rules.
%
%    A Smolyak construction is used to create a multidimensional sparse grid.
%
%    The user specifies:
%    * the spatial dimension of the quadrature region,
%    * the level that defines the Smolyak grid.
%    * the quadrature rule.
%    * the number of points.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 March 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Fabio Nobile, Raul Tempone, Clayton Webster,
%    A Sparse Grid Stochastic Collocation Method for Partial Differential
%    Equations with Random Input Data,
%    SIAM Journal on Numerical Analysis,
%    Volume 46, Number 5, 2008, pages 2309-2345.
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer LEVEL_MAX, controls the size of the final
%    sparse grid.
%
%    Input, integer RULE, the index of the rule.
%    1, "CC", Clenshaw Curtis Closed Fully Nested rule.
%    2, "F1", Fejer 1 Open Fully Nested rule.
%    3, "F2", Fejer 2 Open Fully Nested rule.
%    4, "GP", Gauss Patterson Open Fully Nested rule.
%    5, "GL", Gauss Legendre Open Weakly Nested rule.
%    6, "GH", Gauss Hermite Open Weakly Nested rule.
%    7, "LG", Gauss Laguerre Open Non Nested rule.
%
%    Input, integer POINT_NUM, the number of points in the grid,
%    as determined by LEVELS_INDEX_SIZE.
%
%    Output, real GRID_WEIGHT(POINT_NUM), the weights.
%
%    Output, real GRID_POINT(DIM_NUM,POINT_NUM), the points.
%
  if ( rule ~= 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'SPARSE_GRID_CFN - Fatal error!\n' );
    fprintf ( 1, '  Illegal input rule index = %d\n', rule );
    error ( 'SPARSE_GRID_CFN - Fatal error!' );
  end
%
%  Determine the index vector, relative to the full product grid,
%  that identifies the points in the sparse grid.
%
  [ grid_index, grid_base ] = levels_index_cfn ( dim_num, level_max, point_num );
%
%  Compute the physical coordinates of the abscissas.
%
  if ( 0 == level_max )
    order_max = 1;
  else
    order_max = 2^level_max + 1;
  end

  grid_point = zeros ( dim_num, point_num );

  for point = 1 : point_num
    for dim = 1 : dim_num

      if ( rule == 1 )
        grid_point(dim,point) = ...
          cc_abscissa ( order_max, grid_index(dim,point) + 1 );
      end

    end
  end
%
%  Gather the weights.
%
  grid_weight = sparse_grid_weights_cfn ( dim_num, level_max, rule, ...
    point_num, grid_index );

  return
end


function fem = genFEM3D(mesh,femtype,bcind,option)

%% Usage: Form FEM global degrees of freedom on 3D tetrahedron mesh
%
% INPUTS:
% mesh --- a struct data contains rich mesh information.
% bcind --- [bc1,bc2,bc3,bc4,bc5,bc6] denotes the boundary condition of
%            bc1: x = xmin  bc2: x = xmax
%            bc3: y = ymin  bc4: y = ymax
%            bc5: z = zmin  bc6: z = zmax
%            if bc = 1: Dirichlet boundary condition
%               bc = 2: Neumann boundary condition
%               bc = 3: Robin boundary condition
% femtype --- the type of finite element methods
%             Conforming: P1, P2
%
% OUTPUTS:
% fem --- a struct data contains the following fields:
%         fem.p: (x,y,z) coordinate of each vertex w.r.t a global DoF
%         fem.t: indices of global DoF in each element
%         fem.bc: indices of global DoF on the boundary
%         fem.mapper: a vector to extract unknowns from global DoF.
%         fem.type: type of finite element methods
%         fem.ldof: number of local DoF on each element
%         fem.ng: number of Gaussian quadrature points on each element

% Last Modified: 08/07/2020 by Xu Zhang

%% 0. Inputs
if nargin == 2
    bcind = [1,1,1,1,1,1];  option.ng = 4;
end
if nargin == 3
    option.ng = 4;
end
if ~isfield(option,'ng')
    option.ng = 4;
end
ng = option.ng;

%% 1. Form fem p, t, and basis functions
if strcmp(femtype,'P1')
    fem = genP1FEM3D(mesh); option.ngauss = 4;
elseif strcmp(femtype,'P2')
    fem = genP2FEM3D(mesh); option.ngauss = 11;
end

%% 2. Form Gaussian Quadrature
p = mesh.p; t = mesh.t;
X1 = p(t(:,1),:); X2 = p(t(:,2),:); X3 = p(t(:,3),:); X4 = p(t(:,4),:);
gw = gaussWtetra(ng);
[gx,gy,gz] = gaussPtetra(X1,X2,X3,X4,ng);
A = tetraArea(X1,X2,X3,X4);
fem.gw = gw; fem.gx = gx; fem.gy = gy; fem.gz = gz; fem.area = A;

%% 3. Form bc mapper
[bc,mapper] = boundaryNode3D(mesh,fem.p,bcind);
fem.bc = bc; fem.mapper = mapper; fem.ng = option.ng; fem.bcind = bcind;


function gaussian_test ( )

%*****************************************************************************80
%
%% GAUSSIAN_TEST examines the gaussian correlation.
%
%  Discussion:
%
%    Note that I can't use the original value EIGEN_NUM = 20.  The
%    EIGS function fails to converge.  In fact, it still fails at 12.
%
%    This code is based substantially on a document by Toby Driscoll.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 February 2012
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Toby Driscoll,
%    Mercer's theorem and the Karhunen-Loeve expansion,
%    Oxford University Mathematical Institute,
%    http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf
%
  rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' )
  addpath ( '../chebfun' )

  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GAUSSIAN_TEST:\n' );
  fprintf ( 1, '  Demonstrate Mercer''s theorem and the KL expansion\n' );
  fprintf ( 1, '  for the gaussian kernel.\n' );
%
%  Set the interval.
%
  a = 0.0;
  b = 10.0;
  fprintf ( 1, '  Using interval [%g,%g]\n', a, b );
  s_num = 21;
  s_vec = linspace ( a, b, s_num );
%
%  FRED is a function from the CHEBFUN library.
%
%  It constructs a "chebop" representing the Fredholm integral operator
%  with kernel K for functions in domain [A,B].
%
  F = fred ( @gaussian_correlation, domain ( [ a, b ] ) );
%
%  EIGS has been extended to be able to compute the eigenvalues Lambda
%  and eigenfunctions Psi of the Fredholm integral operator represented by F.
%
%  The "LM" switch requests that we return the eigenvalues of largest magnitude.
%
%  Each Psi is a CHEBFUN, that is, it takes a real number argument.
%
  eigen_num = 20;
  [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' );

  eigen_found = length ( Lambda );
  fprintf ( 1, '  Requested %d eigenmodes, computed %d\n', eigen_num, eigen_found );
  eigen_num = min ( eigen_num, eigen_found );
%
%  Print the eigenvalues.
%
  lambda_vec = diag ( Lambda );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   I       Lambda(I)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : eigen_num
    fprintf ( 1, '  %2d  %10g\n', i, lambda_vec(i) );
  end
%
%  Plot the eigenvalues.
%
  figure ( 1 )
  clf
  plot ( lambda_vec, 'Linewidth', 2 );
  hold on
  plot ( lambda_vec, 'b.', 'Markersize', 20 );
  title ( 'gaussian: Mercer eigenvalues' );
  xlabel ( '<--- N --->')
  grid on
  print -dpng 'gaussian_figure1.png'
%
%  Plot selected eigenfunctions.
%
  figure ( 2 )
  subplot ( 4, 1, 1 )
  plot ( Psi(:,1), 'Linewidth', 2 );
  title ( 'gaussian: Mercer eigenfunction PSI(1)' )
  grid on
  subplot ( 4, 1, 2 )
  plot ( Psi(:,2), 'Linewidth', 2 );
  title ( 'gaussian: Mercer eigenfunction PSI(2)' )
  grid on
  subplot ( 4, 1, 3 )
  plot ( Psi(:,5), 'Linewidth', 2 );
  title ( 'gaussian: Mercer eigenfunction PSI(5)' )
  grid on
  subplot ( 4, 1, 4 )
  plot ( Psi(:,10), 'Linewidth', 2 );
  title ( 'gaussian: Mercer eigenfunction PSI(10)' )
  grid on
  print -dpng 'gaussian_figure2.png'
%
%  Orthonormality check.
%
  ptp = Psi' * Psi;
  error_frobenius = r8mat_is_identity ( eigen_num, ptp );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Frobenius norm of I - Psi'' * Psi = %g\n', error_frobenius );
%
%  K(S,S) should be exactly 1.
%  Because we are using a truncated representation of K, our estimate of K(S,S)
%  will be smaller than 1.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Truncated estimate of K(s,s) = 1 for S in the interval.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '        S        K(s,s) estimate\n' );
  fprintf ( 1, '\n' );
  for i = 1 : 21
    s = s_vec(i);
    ptlp = Psi(s,:) * Lambda * Psi(s,:)';
    fprintf ( 1, '  %10g  %14g\n', s, ptlp );
  end
%
%  Look at eigenvalue decay.
%
  x = diff ( log ( ( 1:eigen_num ) ) );
  y = diff ( log ( lambda_vec ) )';
  c = y ./ x;
  figure ( 3 );
  clf
  plot ( c, 'Linewidth', 2 );
  grid on
  hold on
  plot ( c, 'b.', 'Markersize', 20 );
  xlabel ( '<-- N -->' )
  title ( 'gaussian: Eigenvalue decay rate' );
  print -dpng 'gaussian_figure3.png'
%
%  Look at eigenvalue sum.
%
%  The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b],
%  that is, b - a.
%
%  We compare the trace to the partial sums of the lambda's to see how much
%  of the variance of the process we have captured.
%
  trace_K = b - a;
  lambda_cum = cumsum ( lambda_vec ) / trace_K;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Index    Cumulative Eigenvalue sum\n' );
  fprintf ( 1, '\n' );
  for i = 1 : eigen_num
    fprintf ( 1, '  %5d  %10g\n', i, lambda_cum(i) );
  end
%
%  We decide to use the first 10 eigenfunctions.
%
  eigen_use = 10;
%
%  Find 400 realizations of the process by selecting, for each realization,
%  10 random parameters Z in the truncated KL expansion.
%
  Z = randn ( eigen_use, 400 );
  X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z );
%
%  Plot 40 of the realizations;
%  Plot their mean, computed from all 400.
%
  figure ( 4 )
  clf
  plot ( X(:,1:40) )
  mu = sum ( X, 2 ) / 400;
  hold on;
  plot ( mu, 'k', 'linewidth', 3 );
  title ( 'gaussian: 40 Random Realizations X(t,omega), and their Mean.' )
  print -dpng 'gaussian_figure4.png'
%
%  Estimate the covariance from the data.
%
  figure ( 5 )
  clf
  [ S, T ] = meshgrid ( s_vec, s_vec );
  C = cov ( X(s_vec,:)' );
  mesh ( S, T, C );
  hold on;
  D = gaussian_correlation ( S, T );
  plot3 ( S, T, D, 'k.', 'markersize', 10 )
  title ( 'gaussian: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' )
  print -dpng 'gaussian_figure5.png'
%
%  Using just 10 functions in the expansion,
%  reduce the correlation length,
%  and examine the sum of the lambda's.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Use a fixed number of eigenfunctions = %d\n', eigen_use );
  fprintf ( 1, '  but vary the correlation length RHOBAR.\n' );
  fprintf ( 1, '  (We used RHOBAR = 1 above.)\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The sum of the eigenvalues, divided by (B-A),\n' );
  fprintf ( 1, '  discloses the relative amount of the total variation\n' );
  fprintf ( 1, '  that is captured by the truncated expansion.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      RHOBAR      VARSUM\n' );
  fprintf ( 1, '\n' );
  rhobar = 4.0;
  for i = 1 : 10
    K = @ ( s, t ) exp ( - ( ( s - t ) / rhobar ).^2 );
    F = fred ( K, domain ( [ a, b ] ) );
    lambda_vec = eigs ( F, eigen_use, 'lm' );
    varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a );
    fprintf ( 1, '  %10g  %10g\n', rhobar, varsum );
    rhobar = rhobar / 2.0;
  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GAUSSIAN_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  rmpath ( '../chebfun' )

  return
end


function [os,os1] = getosmatrix_bb(boxes,gts)
%% Given two sets of bounding boxes, N1 in the first one, and N2 in
%% the second one, compute a N1xN2 overlap score matrix where the
%% overlap score is the ratio of the intersection to union
%% Tomasz Malisiewicz (tomasz@cmu.edu)

if ~exist('gts','var')
  gts = boxes;
end

if numel(boxes) == 0 || numel(gts) == 0
  os = zeros(size(boxes,1),size(gts,1));

  return;
end

x1 = boxes(:,1);
y1 = boxes(:,2);
x2 = boxes(:,3);
y2 = boxes(:,4);

area = (x2-x1+1) .* (y2-y1+1);

xa1 = gts(:,1);
ya1 = gts(:,2);
xa2 = gts(:,3);
ya2 = gts(:,4);

area2 = (xa2-xa1+1) .* (ya2-ya1+1);

os = zeros(size(boxes,1),size(gts,1));
if size(boxes,1)*size(gts,1)==0
  return;
end

if nargout == 2
  os1 = os;
end

for i = 1:size(boxes,1)

  xx1 = max(boxes(i,1),gts(:,1));
  yy1 = max(boxes(i,2),gts(:,2));
  xx2 = min(boxes(i,3),gts(:,3));
  yy2 = min(boxes(i,4),gts(:,4));

  w = xx2-xx1+1;
  h = yy2-yy1+1;

  o = w.*h;
  o( (w<0) | (h<0) ) = 0;

  os(i,:) = o ./ (eps + (area(i) + area2 - o));

  if nargout == 2
    os1(i,:) = (o ./ (eps + area2));
    %os1(i,:) = o ./ area(i);
  end
end


s = [1 1 1 1 1]';
t = [2 3 4 5 6]';
G = graph(s',t');
I = full(incidence(G))

n = length(s);

ind = (1:n)'
A = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));

A

I

A - I

s = [1 1 1 1 1]';
t = [6 3 4 5 2]';
G = graph(s',t');
I = full(incidence(G))

ind = (1:n)'
A = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));

A

I

A - I

s = [1 1 1 1 1 6]';
n = length(s);
t = [6 3 4 5 2 1]';
G = graph(s',t');%switches orientation of duplicates
I = full(incidence(G))

ind = (1:n)'
A = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));

A

I

A - I

s = [1 1 1 1 1 6]';
n = length(s);
t = [6 3 4 5 2 1]';
G = digraph(s',t'); %does not switch orientation of duplicates
I = full(incidence(G))

ind = (1:n)'
A = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));

A

I

A - I


function chol_example
%CHOL_EXAMPLE simple Cholesky factorization example
% Example
%   chol_example
% See also: testall

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

D = 10 ;
X = 1 ;
o = 0 ;

A = sparse ([
D o X o o o o X o o
o D o o X o o o o X
X o D o o o X o o o
o o o D o o o o X X
o X o o D o o o X X
o o o o o D X X o o
o o X o o X D o o o
X o o o o X o D X X
o o o X X o o X D o
o X o X X o o X o D ]) ;

disp ('A = ') ; disp (A) ;

L = chol(A)' ;

disp ('L = ') ; disp (L) ;

clf
subplot (1,2,1) ; spy (A) ;
subplot (1,2,2) ; spy (L+L') ;


function d = p03_fd ( p )

%*****************************************************************************80
%
%% P03_FD is a signed distance function for problem 3.
%
%  Licensing:
%
%    (C) 2004 Per-Olof Persson.
%    See COPYRIGHT.TXT for details.
%
%  Modified:
%
%    06 February 2006
%
%  Parameters:
%
%    Input, real P, one or more points.
%
%    Output, real D, the signed distance of each point to the boundary of the region.
%
  d1 = drectangle ( p, -1.0, 1.0, -1.0, 1.0 );
  d2 = dcircle ( p, 0.0, 0.0, 0.4 );

  d = ddiff ( d1, d2 );

  return
end


function I=gausslaguerr(f2,a,b,n)

%I=gausslaguerr(f,a,b,n)
%Aproximates integral using Gauss-Laguerre method

%Laguerre polynomial
p=polelague(n);
%Roots
x=roots(p(n+1,:));

G=feval(f2,x);		%Function evaluation on the nodes

%Coeficients
for i=1:n
   C(i)=((factorial(n).^2).*x(i))./(polyval(p(n+1,:),(x(i))).^2);
end

I=dot(C,G);


function f = p31_f ( n, x )

%*****************************************************************************80
%
%% P31_F evaluates the objective function for problem 31.
%
%  Discussion:
%
%    The minimal function value is -10.15320.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Zbigniew Michalewicz,
%    Genetic Algorithms + Data Structures = Evolution Programs,
%    Third Edition,
%    Springer Verlag, 1996,
%    ISBN: 3-540-60676-9,
%    LC: QA76.618.M53.
%
%  Parameters:
%
%    Input, integer N, the number of variables.
%
%    Input, real X(N), the argument of the objective function.
%
%    Output, real F, the value of the objective function.
%
  m = 5;
  a = [ 4.0, 4.0, 4.0, 4.0; ...
        1.0, 1.0, 1.0, 1.0; ...
        8.0, 8.0, 8.0, 8.0; ...
        6.0, 6.0, 6.0, 6.0; ...
        3.0, 7.0, 3.0, 7.0 ]';

  c = [ 0.1, 0.2, 0.2, 0.4, 0.6 ]';

  f = 0.0;
  for j = 1 : m
    f = f - 1.0 / ( c(j) + sum ( ( x(1:n) - a(1:n,j) ).^2 ) );
  end

  return
end


function w = wf_fft(w);

% WAVEFORM = WF_FFT(WAVEFORM)  calculate frequency spectrum of a waveform.
% The results of the fast fourier transform is added as new fields
% in the waveform:
%   FFT_FREQ is a vector of frequencies with N samples
%   FFT_AMP is a vector of spetral amplitudes
%   FFT_PHASE is a vector of phases
%   FFT_DOM is the scalar frequency of the maximum amplitude
%           peak (or dominant frequency. This could change)

% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$

admin.deprecated(mfilename,'wf_fft.compute');

% CHECK ARGUMENTS
if ~strcmpi(class(w),'waveform')
    error('First input must be a waveform object');
end

% STEP THROUGH WAVFORMS ADDING NEW FIELDS
[N,M] = size(w);
for i = 1:N*M
    Fn = get(w(i),'NYQ');
    x = get(w(i),'DATA');
    NFFT=2.^(ceil(log(length(x))/log(2)));  % Next highest power of 2
    FFTX=fft(x,NFFT);                       % Take fft, padding with zeros.
    NumUniquePts = ceil((NFFT+1)/2);
    FFTX=FFTX(1:NumUniquePts);              % throw out neg frequencies
    MX=abs(FFTX);                           % Take magnitude of X
    MX=MX*2;                                % Multiply by 2
    MX=MX/length(x);
    PX=phase(FFTX);                           % Take magnitude of X
    f=(0:NumUniquePts-1)*2/NFFT;
    f=f*Fn;
    w(i) = addfield(w(i),'FFT_FREQ',f');
    w(i) = addfield(w(i),'FFT_AMP',MX);
    w(i) = addfield(w(i),'FFT_PHASE',PX);
    a = find(MX == max(MX));
    w(i) = addfield(w(i),'FFT_DOM',f(a));
end;


%  演示调用 平方根法 分解
clear;
A=[6 7 5; 7 13 8; 5 8 6];   %对称正定矩阵
b=[9; 10; 9];

% 平方根分解法
[L, x] = my_cholesky(A, b)

% 直接调用matlab左除运算符
x_ = A\b


function val = straight_line_integral_2(xs,ys,zs,data3d,x1,y1,z1,x2,y2,z2)
%
%   Deshan Yang, PhD
%	Department of radiation oncology
%	Washington University in Saint Louis
%   01/16/2011, Saint Louis, MO, USA
%
%   val = straight_line_integral_2(xs,ys,zs,data3d,x1,y1,z1,x2,y2,z2)
%
%   Perform straight line integration on the 3D data from point 1 to point
%   2
%
%   Deshan Yang, PhD
%   01/16/2011, Saint Louis, MO, USA
%
%   This function assumes that the point positions are given in the same
%   coordinate system as the 3D data. Any coordination transformation or
%   scaling should be done priorly.
%
%   Both data and points should be in single, or double
%
dim = [size(data3d) 1];
% if numel(xs)~=length(xs) || length(xs) ~= dim(2) || ...
% 		numel(ys)~=length(ys) || length(ys) ~= dim(1) || ...
% 		numel(zs)~=length(zs) || length(zs) ~= dim(3)
% 	fprintf('Incorrect image data: length does not match to the image dimension.\n');
% 	return;
% end

% Make sure the image and the voxel coordinate be positively increasing. If not, then flip it
[xs,ys,zs,data3d] = make_sure_positive(xs,ys,zs,data3d);
psrc = [x1,y1,z1];
pcdet = [x2,y2,z2];

corner_points = [...
	xs(1) ys(1) zs(1);...
	xs(1) ys(1) zs(end);...
	xs(1) ys(end) zs(1);...
	xs(1) ys(end) zs(end);...
	xs(end) ys(1) zs(1);...
	xs(end) ys(1) zs(end);...
	xs(end) ys(end) zs(1);...
	xs(end) ys(end) zs(end)...
	];

corner_points_t = zeros(8,1);
for k =1:8
	p = corner_points(k,:);
	[q,corner_points_t(k)] = project_1_point_to_a_line(psrc,pcdet,p);
end

t_min = min(corner_points_t);
t_max = max(corner_points_t);

dist = norm(psrc-pcdet);

N = ceil(dist*(t_max-t_min));	% N planes
dt = (t_max-t_min)/N;
ts = t_min:dt:t_max;

xst = psrc(1)+(pcdet(1)-psrc(1))*ts;
yst = psrc(2)+(pcdet(2)-psrc(2))*ts;
zst = psrc(3)+(pcdet(3)-psrc(3))*ts;

val = sum(interp3(xs,ys,zs,data3d,xst,yst,zst,'linear',0))*dt;

% % Transform the point coordinate into the image voxel index
% x1 = (x1 - xs(1))/dx+0.5;
% x2 = (x2 - xs(1))/dx+0.5;
% y1 = (y1 - ys(1))/dy+0.5;
% y2 = (y2 - ys(1))/dy+0.5;
% z1 = (z1 - zs(1))/dz+0.5;
% z2 = (z2 - zs(1))/dz+0.5;
%
%
% nx = ceil(min(x1,x2)):floor(max(x1,x2));
% tx = (nx-x1)/(x2-x1);
%
% ny = ceil(min(y1,y2)):floor(max(y1,y2));
% ty = (ny-y1)/(y2-y1);
%
% nz = ceil(min(z1,z2)):floor(max(z1,z2));
% tz = (nz-z1)/(z2-z1);
%
%
%
% ts = sort([tx ty tz]);    % It may be slow here
% dist = sqrt((x2-x1).^2+(y2-y1).^2+(z2-z1).^2);
%
% nx = (x2-x1)*ts+x1;
% ny = (y2-y1)*ts+y1;
% nz = (z2-z1)*ts+z1;
%
% idxes = find(nx>=0 & nx<=dim(2) & ny>=0 & ny<=dim(1) & nz>=0 & nz<=dim(3));
% nx = nx(idxes);
% ny = ny(idxes);
% nz = nz(idxes);
% N_1 = length(nx)-1;
%
% xidx = max(ceil((nx(1:N_1)+nx(2:end))/2),1);
% yidx = max(ceil((ny(1:N_1)+ny(2:end))/2),1);
% zidx = max(ceil((nz(1:N_1)+nz(2:end))/2),1);
%
% if ~isempty(xidx)
%     if x2~=x1
%         lengths = diff(nx)/(x2-x1);
%     else
%         lengths = diff(ny)/(y2-y1);
%     end
%
%     val = sum(data3d(sub2ind(dim,yidx,xidx,zidx)).*lengths)*dist;
% 	val = val*dx*dy*dz;	% Convert the length back to the original image coordinate length
% else
%     val = 0;
% end
%
%
%
%


function T = tn_vector()

    T.expectation = @TN_vector_expectation;
    function [exp] = TN_vector_expectation(mus, taus)

        sigmas = 1.0 ./ sqrt(taus);
        x = - mus ./ sigmas;
        %lambdax = norm.pdf(x)/(0.5*erfc(x/sqrt(2)));
        lambdax = pdf('Normal',x,0,1) ./ (0.5 * erfc(x/sqrt(2)));
        exp = mus + sigmas .* lambdax;

        for i = 1 : length(exp)
            v = exp(i);
            mu = mus(i);
            tau = taus(i);
            sigma = sigmas(i);

            if mu < -30 * sigma
                v = 1/(abs(mu)*tau);
            else
                % do nothing;
            end

            if isnan(v)
                v = 0;
            end

            exp(i) = v;
        end

        exp(isinf(exp)) = 0;

    end

    T.variance = @TN_vector_variance;
    function [var] = TN_vector_variance(mus, taus)

        sigmas = 1.0 ./ sqrt(taus);
        x = - mus ./ sigmas;
        %lambdax = norm.pdf(x)/(0.5*erfc(x/math.sqrt(2)));
        lambdax = pdf('Normal',x,0,1) ./ (0.5 * erfc(x/sqrt(2)));
        deltax = lambdax .* (lambdax-x);
        var = sigmas.^2 .* ( 1 - deltax );

        for i = 1 : length(var)
            v = var(i);
            mu = mus(i);
            tau = taus(i);
            sigma = sigmas(i);

            if mu < -30 * sigma
                v = (1/(abs(mu)*tau)).^2;
            else
                % do nothing;
            end

            if isnan(v)
                v = 0;
            end

            var(i) = v;
        end

        var(isinf(var)) = 0;
    end
end


function out = getqr(a)
% =======================================================================
% QR factorization of a matrix a.
% =======================================================================
% out = getqr(a)
% -----------------------------------------------------------------------
% INPUT
%	- a: Matrix to factorize
% -----------------------------------------------------------------------
% OUTPUT
%   - out: factorized matrix such that out*out'=I
% =======================================================================
% VAR Toolbox 3.0
% Ambrogio Cesa-Bianchi
% ambrogiocesabianchi@gmail.com
% December 2021
% -----------------------------------------------------------------------

[q,r]=qr(a);
for i=1:size(q,1)
    if r(i,i)<0
        q(:,i)=-q(:,i);
    end
end
out=q;
end