function sincos_test ( )

%*****************************************************************************80
%
%% SINCOS_TEST demonstrates SPINTERP on a function of a 2D argument.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 August 2012
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SINCOS_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Demonstrate the use of SPINTERP to construct an\n' );
  fprintf ( 1, '  interpolant to the function z(x,y) = sin(x) + cos(y)\n' );
%
%  We need to have the spinterp program in the Matlab path.
%
  addpath ( '../spinterp' );
%
%  To alter the default spinterp options, we must call spset().
%  We want to use a grid that uses Chebyshev spacing, and we
%  want to use at least 5 levels of interpolation.
%
  OPTIONS = spset ( 'GridType', 'Chebyshev', ...
                    'MinDepth', 5 );
%
%  Now we call spvals() to set up in C the data defining
%  the sparse grid interpolant.  C is a Matlab structure.
%
  m = 2;

  box = [ 0.0, pi; ...
          0.0, pi ];

  c = spvals ( @sincos_f, m, box, OPTIONS );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Here is the sparse interpolant structure:\n' );
  fprintf ( 1, '\n' );

  c
%
%  Just for information, print out the grid points added at each level.
%
  l_max = 4;
  for l = 0 : l_max
    fprintf ( 1, '\n' );
    label = sprintf ( '  Grid points added at level %d', l );
    x = spgrid ( l, m, OPTIONS );
    [ n, ~ ] = size ( x );
    r8mat_print ( n, m, x, label );
  end

  figure ( 1 )
  l_max = 5;
  plotgrid ( l_max, m );
  grid on
  xlabel ( '<---X--->' );
  ylabel ( '<---Y--->' );
  title ( sprintf ( 'Spinterp Chebyshev Grid of level %d', l_max ) )

  filename = 'sincos_grid.png';
  print ( '-dpng', filename )
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Grid plot stored as "%s".\n', filename );
%
%  Evaluate the interpolant at some random points in the region.
%
  n = 25;
  x = pi * rand ( 1, n );
  y = pi * rand ( 1, n );
  z = spinterp ( c, x, y );

  e = max ( abs ( z - sincos_f ( x, y ) ) );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Maximum approximation error at %d random points is %g\n', n, e );
%
%  Display plots of the function and interpolant.
%
  figure ( 2 )
  subplot ( 1, 2, 1 );
  ezmesh ( @sincos_f, [ 0.0, pi ] );
  title ( 'z(x,y) = sin(x) + cos(y)' );

  subplot ( 1, 2, 2 );
  ezmesh ( @(x,y) spinterp ( c, x, y ), [ 0, pi ] );
  title ( 'Sparse grid interpolant' );

  filename = 'sincos_interp.png';
  print ( '-dpng', filename )
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Interpolant plot stored as "%s".\n', filename );

  rmpath ( '../spinterp' )
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SINCOS_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function point = intersectLinePlane(line, plane, varargin)
%INTERSECTLINEPLANE Intersection point between a 3D line and a plane
%
%   PT = intersectLinePlane(LINE, PLANE)
%   Returns the intersection point of the given line and the given plane.
%   LINE:  [x0 y0 z0 dx dy dz]
%   PLANE: [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]
%   PT:    [xi yi zi]
%   If LINE and PLANE are parallel, return [NaN NaN NaN].
%   If LINE (or PLANE) is a matrix with 6 (or 9) columns and N rows, result
%   is an array of points with N rows and 3 columns.
%
%   PT = intersectLinePlane(LINE, PLANE, TOL)
%   Specifies the tolerance factor to test if a line is parallel to a
%   plane. Default is 1e-14.
%
%   Example
%     % define horizontal plane through origin
%     plane = [0 0 0   1 0 0   0 1 0];
%     % intersection with a vertical line
%     line = [2 3 4  0 0 1];
%     intersectLinePlane(line, plane)
%     ans =
%        2   3   0
%     % intersection with a line "parallel" to plane
%     line = [2 3 4  1 2 0];
%     intersectLinePlane(line, plane)
%     ans =
%       NaN  NaN  NaN
%
%   See also:
%   lines3d, planes3d, points3d, clipLine3d
%

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

%   HISTORY
%   24/11/2005 add support for multiple input
%   23/06/2006 correction from Songbai Ji allowing different number of
%       lines or plane if other input has one row
%   14/12/2006 correction for parallel lines and plane normals
%   05/01/2007 fixup for parallel lines and plane normals
%   24/04/2007 rename as 'intersectLinePlane'
%   11/19/2010 Added bsxfun functionality for improved speed (Sven Holcombe)
%   01/02/2011 code cleanup, add option for tolerance, update doc

% extract tolerance if needed
tol = 1e-14;
if nargin > 2
    tol = varargin{1};
end

% unify sizes of data
nLines  = size(line, 1);
nPlanes = size(plane, 1);

% N planes and M lines not allowed
if nLines ~= nPlanes && min(nLines, nPlanes) > 1
    error('MatGeom:geom3d:intersectLinePlane', ...
        'Input must have same number of rows, or one must be 1');
end

% plane normal
n = crossProduct3d(plane(:,4:6), plane(:,7:9));

% difference between origins of plane and line
dp = bsxfun(@minus, plane(:, 1:3), line(:, 1:3));

% dot product of line direction with plane normal
denom = sum(bsxfun(@times, n, line(:,4:6)), 2);

% relative position of intersection point on line (can be inf in case of a
% line parallel to the plane)
t = sum(bsxfun(@times, n, dp),2) ./ denom;

% compute coord of intersection point
point = bsxfun(@plus, line(:,1:3),  bsxfun(@times, [t t t], line(:,4:6)));

% set indices of line and plane which are parallel to NaN
par = abs(denom) < tol;
point(par,:) = NaN;


function [ l, p, u ] = r8mat_lu ( m, n, a )

%*****************************************************************************80
%
%% R8MAT_LU computes the LU factorization of an R8MAT.
%
%  Discussion:
%
%    The routine is given an M by N matrix A, and produces
%
%      L, an M by M unit lower triangular matrix,
%      U, an M by N upper triangular matrix, and
%      P, an M by M permutation matrix P,
%
%    so that
%
%      A = P' * L * U.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows in A.
%
%    Input, integer N, the number of columns in A.
%
%    Input, real A(M,N), the M by N matrix to be factored.
%
%    Output, real L(M,M), the M by M unit lower triangular factor.
%
%    Output, real P(M,M), the M by M permutation matrix.
%
%    Output, real U(M,N), the M by N upper triangular factor.
%

%  Initialize:
%
%    U:=A
%    L:=Identity
%    P:=Identity
%
  u(1:m,1:n) = a(1:m,1:n);

  l = r8mat_identity ( m );

  p(1:m,1:m) = l(1:m,1:m);
%
%  On step J, find the pivot row, IPIV, and the pivot value PIVOT.
%
  for j = 1 : min ( m - 1, n )

    pivot = 0.0;
    ipiv = 0;

    for i = j : m

      if ( pivot < abs ( u(i,j) ) )
        pivot = abs ( u(i,j) );
        ipiv = i;
      end

    end
%
%  Unless IPIV is zero, swap rows J and IPIV.
%
    if ( ipiv ~= 0 )

      u = r8row_swap ( m, n, u, j, ipiv );

      l = r8row_swap ( m, m, l, j, ipiv );

      p = r8row_swap ( m, m, p, j, ipiv );
%
%  Zero out the entries in column J, from row J+1 to M.
%
      for i = j+1 : m

        if ( u(i,j) ~= 0.0 )

          l(i,j) = u(i,j) / u(j,j);

          u(i,j) = 0.0;

          u(i,j+1:n) = u(i,j+1:n) - l(i,j) * u(j,j+1:n);

        end

      end

    end

  end

  return
end


function tensor_product_test ( )

%*****************************************************************************80
%
%% TENSOR_PRODUCT_TEST tests TENSOR_PRODUCT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 April 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TENSOR_PRODUCT_TEST:\n' );
  fprintf ( 1, '  Given a sequence of 1D quadrature rules, construct the\n' );
  fprintf ( 1, '  tensor product rule.\n' );
%
%  1D rule.
%
  n1D = { [ -1.0; +1.0 ] };
  w1D = { [ 1.0; 1.0 ] };

  [ x, w ] = tensor_product ( n1D, w1D );

  x = x';

  [ m, n ] = size ( x );

  quad_rule_print ( m, n, x, w, '  A 1D rule over [-1,+1]:' );
%
%  2D rule.
%
  n1D{2} = [ 2.0; 2.5; 3.0 ];
  w1D{2} = [ 0.25; 0.50; 0.25 ];

  [ x, w ] = tensor_product ( n1D, w1D );
  x = x';

  [ m, n ] = size ( x );

  quad_rule_print ( m, n, x, w, '  A 2D rule over [-1,+1] x [2.0,3.0]:' );
%
%  3D rule.
%
  n1D{3} = [ 10.0; 15.0 ];
  w1D{3} = [ 2.50; 2.50 ];

  [ x, w ] = tensor_product ( n1D, w1D );
  x = x';
  [ m, n ] = size ( x );

  quad_rule_print ( m, n, x, w, '  A 3D rule over [-1,+1] x [2.0,3.0] x [10.0,15.0]:' );

  return
end


%% Machine Learning Online Class - Exercise 1: Linear Regression

%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  linear exercise. You will need to complete the following functions
%  in this exericse:
%
%     warmUpExercise.m
%     plotData.m
%     gradientDescent.m
%     computeCost.m
%     gradientDescentMulti.m
%     computeCostMulti.m
%     featureNormalize.m
%     normalEqn.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%
% x refers to the population size in 10,000s
% y refers to the profit in $10,000s
%

%% Initialization
clear ; close all; clc

%% ==================== Part 1: Basic Function ====================
% Complete warmUpExercise.m
fprintf('Running warmUpExercise ... \n');
fprintf('5x5 Identity Matrix: \n');
warmUpExercise()

fprintf('Program paused. Press enter to continue.\n');
pause;

%% ======================= Part 2: Plotting =======================
fprintf('Plotting Data ...\n')
data = load('ex1data1.txt'); % read comma separated data
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples

% Plot Data
% Note: You have to complete the code in plotData.m
plotData(X, y);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =================== Part 3: Gradient descent ===================
fprintf('Running Gradient Descent ...\n')

X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1); % initialize fitting parameters

% Some gradient descent settings
iterations = 1500;
alpha = 0.01;

% compute and display initial cost
computeCost(X, y, theta)

% run gradient descent
theta = gradientDescent(X, y, theta, alpha, iterations);

% print theta to screen
fprintf('Theta found by gradient descent: ');
fprintf('%f %f \n', theta(1), theta(2));

% Plot the linear fit
hold on; % keep previous plot visible
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off % don't overlay any more plots on this figure

% Predict values for population sizes of 35,000 and 70,000
predict1 = [1, 1.8] *theta;
fprintf('For population = 18,000, we predict a profit of %f\n',...
    predict1*10000);
predict2 = [1, 2.5] * theta;
fprintf('For population = 25,000, we predict a profit of %f\n',...
    predict2*10000);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% ============= Part 4: Visualizing J(theta_0, theta_1) =============
fprintf('Visualizing J(theta_0, theta_1) ...\n')

% Grid over which we will calculate J
theta0_vals = linspace(-10, 10, 100);
theta1_vals = linspace(-1, 4, 100);

% initialize J_vals to a matrix of 0's
J_vals = zeros(length(theta0_vals), length(theta1_vals));

% Fill out J_vals
for i = 1:length(theta0_vals)
    for j = 1:length(theta1_vals)
	  t = [theta0_vals(i); theta1_vals(j)];
	  J_vals(i,j) = computeCost(X, y, t);
    end
end

% Because of the way meshgrids work in the surf command, we need to
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
% Surface plot
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1');

% Contour plot
figure;
% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
xlabel('\theta_0'); ylabel('\theta_1');
hold on;
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);


function [ w, x ] = line_o02 ( )

%*****************************************************************************80
%
%% LINE_O02 returns a 2 point quadrature rule for the unit line.
%
%  Discussion:
%
%    The integration region is:
%
%    - 1.0 <= X <= 1.0
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Carlos Felippa,
%    A compendium of FEM integration formulas for symbolic work,
%    Engineering Computation,
%    Volume 21, Number 8, 2004, pages 867-890.
%
%  Parameters:
%
%    Output, real W(2), the weights.
%
%    Output, real X(2), the abscissas.
%
  w(1:2) = [ ...
    0.5, ...
    0.5 ];

  x(1:2) = [ ...
    -0.57735026918962576451, ...
     0.57735026918962576451 ];

  return
end


function lambda = herndon_eigenvalues ( n )

%*****************************************************************************80
%
%% HERNDON_EIGENVALUES returns the eigenvalues of the HERNDON matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real LAMBDA(N,1), the eigenvalues.
%
  lambda = zeros ( n, 1 );

  p = 3.0 + sqrt ( ( 4 * n - 3 ) * ( n - 1 ) * 3 ) / ( n + 1 ) );

  lambda(1:n-2,1) = 1.0;
  lambda(n-1,1) = 6.0 / ( p * ( n + 1 ) );
  lambda(n,1) = p / ( n * ( 5 - 2 * n ) );

  return
end


function y = rms(f,varargin)
%RMS RMS value of signal
%   Usage: y = rms(f);
%          y = rms(f,...);
%
%   `RMS(f)` computes the RMS (Root Mean Square) value of a finite sampled
%   signal sampled at a uniform sampling rate. This is a vector norm
%   equal to the $l^2$ averaged by the length of the signal.
%
%   If the input is a matrix or ND-array, the RMS is computed along the
%   first (non-singleton) dimension, and a vector of values is returned.
%
%   The RMS value of a signal *x* of length *N* is computed by
%
%   ..                       N
%      rms(f) = 1/sqrt(N) ( sum |f(n)|^2 )^(1/2)
%                           n=1
%
%   .. math:: rms(f) = \frac{1}{\sqrt N} \left( \sum_{n=1}^N |f(n)|^2
%      \right)^{\frac{1}{2}}
%
%   `RMS` takes the following flags at the end of the line of input
%   parameters:
%
%     'ac'       Consider only the AC component of the signal (i.e. the mean is
%                removed).
%
%     'dim',d    Work along specified dimension. The default value of `[]`
%                means to work along the first non-singleton one.
%

%   AUTHOR : Peter L. Søndergaard

%% ------ Checking of input parameters ---------

if ~isnumeric(f)
  error('%s: Input must be numerical.',upper(mfilename));
end;

if nargin<1
  error('%s: Too few input parameters.',upper(mfilename));
end;

definput.keyvals.dim=[];
definput.flags.mean={'noac','ac'};
[flags,kv]=ltfatarghelper({'dim'},definput,varargin);

%% ------ Computation --------------------------

% It is better to use 'norm' instead of explicitly summing the squares, as
% norm (hopefully) attempts to avoid numerical overflow.

[f,L,Ls,W,dim,permutedsize,order]=assert_sigreshape_pre(f,[],kv.dim, ...
                                                  upper(mfilename));
permutedsize(1)=1;
y=zeros(permutedsize);
if flags.do_ac

  for ii=1:W
    y(1,ii) = norm(f(:,ii)-mean(f(:,ii)))/sqrt(L);
   end;

else

  for ii=1:W
    y(1,ii)=norm(f(:,ii))/sqrt(L);
  end;

end;

y=assert_sigreshape_post(y,kv.dim,permutedsize,order);


function bernstein_poly_01_values_test ( )

%*****************************************************************************80
%
%% BERNSTEIN_POLY_01_VALUES_TEST demonstrates the use of BERNSTEIN_POLY_01_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BERNSTEIN_POLY_01_VALUES_TEST:\n' );
  fprintf ( 1, '  BERNSTEIN_POLY_01_VALUES returns values of \n' );
  fprintf ( 1, '  the Bernstein polynomials.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     N     K       X      BERNSTEIN(N,K)(X)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, n, k, x, b ] = bernstein_poly_01_values ( n_data );

    if ( n_data == 0 )
      break
    end

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

  end

  return
end


function [V2D] = Vandermonde2D(N,r,s)

% function [V2D] = Vandermonde2D(N, r, s);
% Purpose : Initialize the 2D Vandermonde Matrix,  V_{ij} = phi_j(r_i, s_i);

V2D = zeros(length(r),(N+1)*(N+2)/2);

% Transfer to (a,b) coordinates
[a, b] = rstoab(r, s);

% build the Vandermonde matrix
sk = 1;
for i=0:N
  for j=0:N - i
    V2D(:,sk) = Simplex2DP(a,b,i,j);
    sk = sk+1;
  end
end
return;


function nseq = bal_seq_enum ( n )

%*****************************************************************************80
%
%% BAL_SEQ_ENUM enumerates the balanced sequences.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 January 2011
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Donald Kreher, Douglas Simpson,
%    Combinatorial Algorithms,
%    CRC Press, 1998,
%    ISBN: 0-8493-3988-X,
%    LC: QA164.K73.
%
%  Parameters:
%
%    Input, integer N, the number of 0's (and 1's) in the sequence.
%    N must be nonnegative.
%
%    Output, integer NSEQ, the number of balanced sequences.
%
  nseq = i4_choose ( 2*n, n ) / ( n + 1 );

  return
end


function [ n_data, x, fx ] = bessel_j0_values ( n_data )

%*****************************************************************************80
%
%% BESSEL_J0_VALUES returns some values of the J0 Bessel function.
%
%  Discussion:
%
%    In Mathematica, the function can be evaluated by:
%
%      BesselJ[0,x]
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Milton Abramowitz and Irene Stegun,
%    Handbook of Mathematical Functions,
%    US Department of Commerce, 1964.
%
%    Stephen Wolfram,
%    The Mathematica Book,
%    Fourth Edition,
%    Wolfram Media / Cambridge University Press, 1999.
%
%  Parameters:
%
%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the
%    first call.  On each call, the routine increments N_DATA by 1, and
%    returns the corresponding data; when there is no more data, the
%    output value of N_DATA will be 0 again.
%
%    Output, real X, the argument of the function.
%
%    Output, real FX, the value of the function.
%
  n_max = 21;

  fx_vec = [ ...
     -0.1775967713143383E+00, ...
     -0.3971498098638474E+00, ...
     -0.2600519549019334E+00, ...
      0.2238907791412357E+00, ...
      0.7651976865579666E+00, ...
      0.1000000000000000E+01, ...
      0.7651976865579666E+00, ...
      0.2238907791412357E+00, ...
     -0.2600519549019334E+00, ...
     -0.3971498098638474E+00, ...
     -0.1775967713143383E+00, ...
      0.1506452572509969E+00, ...
      0.3000792705195556E+00, ...
      0.1716508071375539E+00, ...
     -0.9033361118287613E-01, ...
     -0.2459357644513483E+00, ...
     -0.1711903004071961E+00, ...
      0.4768931079683354E-01, ...
      0.2069261023770678E+00, ...
      0.1710734761104587E+00, ...
     -0.1422447282678077E-01 ];

  x_vec = [ ...
     -5.0E+00, ...
     -4.0E+00, ...
     -3.0E+00, ...
     -2.0E+00, ...
     -1.0E+00, ...
      0.0E+00, ...
      1.0E+00, ...
      2.0E+00, ...
      3.0E+00, ...
      4.0E+00, ...
      5.0E+00, ...
      6.0E+00, ...
      7.0E+00, ...
      8.0E+00, ...
      9.0E+00, ...
     10.0E+00, ...
     11.0E+00, ...
     12.0E+00, ...
     13.0E+00, ...
     14.0E+00, ...
     15.0E+00 ];

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

  if ( n_max < n_data )
    n_data = 0;
    x = 0.0;
    fx = 0.0;
  else
    x = x_vec(n_data);
    fx = fx_vec(n_data);
  end

  return
end


function [ d ] = dist2(x0,Y)
% Evaluate the distance between a point X in R^2 and each point Y(1,:)

d = sqrt((x0(1)-Y(:,1)).^2+(x0(2)-Y(:,2)).^2);

end


function boundary = p06_boundary_nearest ( m, n, point )

%*****************************************************************************80
%
%% P06_BOUNDARY_NEAREST returns a nearest boundary point in problem 06.
%
%  Discussion:
%
%    The given input point need not be inside the region.
%
%    In some cases, more than one boundary point may be "nearest",
%    but only one will be returned.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real POINT(M,N), the coordinates of the points.
%
%    Output, real BOUNDARY(M,N), points on the boundary
%    that are nearest to each point.
%
  r1 = 1.0;
  r2 = 0.5;

  for j = 1 : n

    x = point(1,j);
    y = point(2,j);

    if ( x == 0.0 & y == 0.0 )

      boundary(1:2,j) = [ r2, 0.0 ]';
%
%  Determine the angle formed by (0,0) and the point.
%
    else

      t = atan4 ( y, x );
%
%  Find the nearest point on the superellipse x^4 + y^4 = 1^4.
%
      t1 = t - pi / 4.0;
      t2 = t + pi / 4.0;

      status = 0;
      dstar1 = 0.0;

      while ( 1 )

        [ t1, t2, tstar1, status ] = fmin_rc ( t1, t2, status, dstar1 );

        if ( status == 0 )
          break
        end

        cm = abs ( cos ( tstar1 ) );
        cs = r8_sign ( cos ( tstar1 ) );
        sm = abs ( sin ( tstar1 ) );
        ss = r8_sign ( sin ( tstar1 ) );

        dstar1 = ( x - r1 * cs * sqrt ( cm ) ).^2 ...
               + ( y - r1 * ss * sqrt ( sm ) ).^2;

      end

      boundary(1,j) = r1 * cs * sqrt ( cm );
      boundary(2,j) = r1 * ss * sqrt ( sm );
%
%  Find the nearest point on the superellipse x^4 + y^4 = 1/2^4.
%
      t1 = t - pi / 4.0;
      t2 = t + pi / 4.0;

      status = 0;
      dstar2 = 0.0;

      while ( 1 )

        [ t1, t2, tstar2, status ] = fmin_rc ( t1, t2, status, dstar2 );

        if ( status == 0 )
          break
        end

        cm = abs ( cos ( tstar2 ) );
        cs = r8_sign ( cos ( tstar2 ) );
        sm = abs ( sin ( tstar2 ) );
        ss = r8_sign ( sin ( tstar2 ) );

        dstar2 = ( x - r2 * cs * sqrt ( cm ) ).^2 ...
               + ( y - r2 * ss * sqrt ( sm ) ).^2;

      end
%
%  Because of some MATLAB idiocy I don't have the patience to figure out,
%  involving SQRT having the wrong number of arguments(!),
%  I must replace the line
%    boundary(1:2,j) = [ r2 * cs * sqrt ( cm ), r2 * ss * sqrt ( sm ) ]';
%
      if ( dstar2 < dstar1 )
        boundary(1,j) = r2 * cs * sqrt ( cm );
        boundary(2,j) = r2 * ss * sqrt ( sm );
      end

    end

  end

  return
end


function [qn,QNq] = normquat(q)

% NORMQUAT Normalize quaternion to unit length
%   NORMQUAT(Q) returns a unit length quaternion Q/norm(Q)
%
%   [qn,QNq] = NORMQUAT(Q) returns also the Jacobian wrt Q. Note that this
%   Jacobian is a symmetric 4x4 matrix.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

nq = sqrt(q(:)'*q(:));
qn = q/nq;

if nargout > 1

    a = q(1);
    b = q(2);
    c = q(3);
    d = q(4);

    nq3 = nq^3;

    QNq = [...
        [ (b^2+c^2+d^2)/nq3,          -a/nq3*b,          -a/nq3*c,          -a/nq3*d]
        [          -a/nq3*b, (a^2+c^2+d^2)/nq3,          -b/nq3*c,          -b/nq3*d]
        [          -a/nq3*c,          -b/nq3*c, (a^2+b^2+d^2)/nq3,          -c/nq3*d]
        [          -a/nq3*d,          -b/nq3*d,          -c/nq3*d, (a^2+b^2+c^2)/nq3]];
end
return

%%

syms a b c d real
q = [a;b;c;d];
[qn,QNq] = normquat(q);

QNq - simple(jacobian(qn,q))

QNq - QNq'

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function [ x, ierror ] = r8mat_solve2 ( n, a, b, x )

%*****************************************************************************80
%
%% R8MAT_SOLVE2 computes the solution of an N by N linear system.
%
%  Discussion:
%
%    The linear system may be represented as
%
%      A*X = B
%
%    If the linear system is singular, but consistent, then the routine will
%    still produce a solution.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 October 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of equations.
%
%    Input, real A(N,N), the coefficient matrix to be inverted.
%
%    Input, real B(N), the right hand side of the system.
%
%    Output, real X(N), the solution of the linear system.
%
%    Output, integer IERROR.
%    0, no error detected.
%    1, consistent singularity.
%    2, inconsistent singularity.
%
  ierror = 0;

  ipiv(1:n) = 0;
  x(1:n) = 0.0;
%
%  Process the matrix.
%
  for k = 1 : n
%
%  In column K:
%    Seek the row IMAX with the properties that:
%      IMAX has not already been used as a pivot;
%      A(IMAX,K) is larger in magnitude than any other candidate.
%
    amax = 0.0;
    imax = 0;
    for i = 1 : n
      if ( ipiv(i) == 0 )
        if ( amax < abs ( a(i,k) ) )
          imax = i;
          amax = abs ( a(i,k) );
        end
      end
    end
%
%  If you found a pivot row IMAX, then,
%    eliminate the K-th entry in all rows that have not been used for pivoting.
%
    if ( imax ~= 0 )

      ipiv(imax) = k;
      a(imax,k+1:n) = a(imax,k+1:n) / a(imax,k);
      b(imax) = b(imax) / a(imax,k);
      a(imax,k) = 1.0;

      for i = 1 : n

        if ( ipiv(i) == 0 )
          a(i,k+1:n) = a(i,k+1:n) - a(i,k) * a(imax,k+1:n);
          b(i) = b(i) - a(i,k) * b(imax);
          a(i,k) = 0.0;
        end

      end
    end
  end
%
%  Now, every row with nonzero IPIV begins with a 1, and
%  all other rows are all zero.  Begin solution.
%
  for j = n : -1 : 1

    imax = 0;
    for k = 1 : n
      if ( ipiv(k) == j )
        imax = k;
      end
    end

    if ( imax == 0 )

      x(j) = 0.0;

      if ( b(j) == 0.0 )
        ierror = 1;
        fprintf ( 1, '\n' );
        fprintf ( 1, 'R8MAT_SOLVE2 - Warning:\n' );
        fprintf ( 1, '  Consistent singularity, equation = %d\n', j );
      else
        ierror = 2;
        fprintf ( 1, '\n' );
        fprintf ( 1, 'R8MAT_SOLVE2 - Error:\n' );
        fprintf ( 1, '  Inconsistent singularity, equation = %d\n', j );
      end

    else

      x(j) = b(imax);

      for i = 1 : n
        if ( i ~= imax )
          b(i) = b(i) - a(i,j) * x(j);
        end
      end

    end
  end

  return
end


function [pc_vec]=pca_kpm(features,N, method);
% PCA_KPM Compute top N principal components using eigs or svd.
% [pc_vec]=pca_kpm(features,N)
%
% features(:,i) is the i'th example - each COLUMN is an observation
% pc_vec(:,j) is the j'th basis function onto which you should project the data
% using pc_vec' * features

[d ncases] = size(features);
fm=features-repmat(mean(features,2), 1, ncases);

if method==1 % d*d < d*ncases
  fprintf('pca_kpm eigs\n');
  options.disp = 0;
  C = cov(fm'); % d x d matrix
  [pc_vec, evals] = eigs(C, N, 'LM', options);
else
  % [U,D,V] = SVD(fm), U(:,i)=evec of fm fm', V(:,i) = evec of fm' fm
  fprintf('pca_kpm svds\n');
  [U,D,V] = svds(fm', N);
  pc_vec = V;
end

if 0
X = randn(5,3);
X = X-repmat(mean(X),5,1);
C = X'*X;
C2=cov(X)
[U,D,V]=svd(X);
[V2,D2]=eig(X)
end


function Results=weightedfit(data)
% This code fits makes a linear fit to a data set (using y =bx+a) where each data point
% has a different or constant standard deviation. Your data should have three or two columns.
% The first column should be the independent variable(x) and the second
% column should be the dependent variable(y). Column three should contain
% your standard deviations for each datapoint. In the situations where you
% do not specify a column three, the code assigns a weight of one to all
% data points and this corresponds to the regular linear fits.
%==========
% INPUTS
%==========
%data = 3 columns; column 1 = x, column2 = y and column 3 = standard dev.

%==========
%OUTPUTS
%==========
%Result.slope= b; Fitted slope
%Result.Intercept = a; Fitted intercept

%Coded by Ebo Ewusi-Annan (University of Florida, 2011)
%============
%REFERENCES
%===========
%1. Willam H. Press, Saul A. Teukolsky and Willan T. Vetterling (1997).
%Numerical Recipes in Fortran.
%2. Philip R. Bevington and D. Keith Robinson (2003). Data Reduction and
%Error Analysis for the Physical Sciences.

x= data(:,1);
y=data(:,2);
[s t]= size(data);
stdv=ones(s,1);
if t==3
stdv=data(:,3);
end
w = 1./stdv.^2;
S = sum(w);
Sx = sum(w.*x);
Sy = sum(w.*y);
Sxx= sum(w.*x.^2);
Sxy= sum(w.*x.*y);
Delta = S*Sxx - (Sx)^2;
a = (Sxx*Sy - Sx*Sxy)./Delta;
b = (S*Sxy - Sx*Sy)./Delta;
fprintf('\n slope=%f Int=%f \n',b,a)
Results.slope=b;
Results.Intercept= a;
y_fit = a + b*x;
  if t==2
    h=plot(x,y,'rs','MarkerFaceColor','r');
     title('Unweighted fit')
  else
     clf;set(gcf,'color','w');
     h=errorbar(x,y,stdv,'rs','MarkerFaceColor','r');
     title('Weighted fit')
  end
hold on; q=plot(x,y_fit,'b.--','linewidth',2);
xlabel('x (Column 1)')
ylabel('y (Column 2)')
legend([h(1),q(1)],'Data',sprintf('\nSlope=%f\nIntercept=%f\n',b,a),'location','Southeast')

end


function [MSE, SNR, PSNR] = Calc_MSE_SNR(I1,I2,b)
% This function computes MSE, SNR and PSNR between two gray
% images excluding a border of width b on all four sides.
% The two gray images must have the same size.
%
%          I1(:,:)      first input original image, range 0~255
%          I2(:,:)      second input observed image, range 0~255
%          b            width of border on each side of the image to exclude
%                       from error calculations
%          MSE          output, mean square error
%          SNR          output, signal noise ratio
%          PSNR         output, peak signal noise ratio
%
% Copyright (c) Apr., 2006. Dengwen Zhou. All rights reserved.
% Department of Computer Science & Technology
% North China Electric Power University(NCEPU)
%
% Last time modified: Oct. 11, 2012
%

% Exclude b border pixels
I1 = double(I1); I2 = double(I2);
I1 = I1(b+1:end-b,b+1:end-b);
I2 = I2(b+1:end-b,b+1:end-b);

% Compute the errors
num = numel(I1);
d = sum((I1(:)-I2(:)).^2);
s = sum(I1(:).^2);
MSE = d/num;
SNR = 10*log10(s/d);
PSNR = 10*log10(255*255/MSE);


function [ x, obj_val] = QCQP_LB1( H_wave,y_wave,N,l,u)
%UNTITLED9 Summary of this function goes here
%   Detailed explanation goes here
Q = 2*H_wave*H_wave.';
f = -2*H_wave*y_wave;
c = y_wave.'*y_wave;
A = zeros(N,2*N);
for ii = 1:N
    A(ii,ii) = cos((l(ii)+u(ii))/2);
    A(ii,ii+N) = sin((l(ii)+u(ii))/2);         %Linear Constraint
end

function [y,grady] = quadobj(x,Q,f,c)         %Objective Function
    y = 1/2*x.'*Q*x+f.'*x+c;
    if nargout>1
        grady = Q*x + f;
    end
end

function [y_con,yeq,grady,gradyeq] = quadconstr(x)      %Nonlinear Constraint
    for nn = 1:N
        y_con(nn) = x(nn)^2+x(nn+N)^2 - 1;
    end
    yeq = [];
    if nargout>2
       gradyeq = zeros(length(x),N);
       for nn = 1:N
           grady(nn,nn) = 2*x(nn);
           grady(nn+N,nn) = 2*x(nn+N);
       end
    end
    gradyeq = [];
end

Acon = -A;

for ii = 1:N
    b(ii) = -cos((u(ii)-l(ii))/2);
end

% options = optimoptions(@fmincon,'Algorithm','sqp',...
%     'SpecifyObjectiveGradient',true,'SpecifyConstraintGradient',true,...
%     'Display','off','OptimalityTolerance',1e-6,'MaxIterations',400);

options = optimoptions('fmincon','Algorithm','sqp', 'GradObj','on');

fun = @(x)quadobj(x,Q,f,c);
nonlconstr = @(x)quadconstr(x);
x1 = ones(2*N,1);
x = fmincon(fun,x1,Acon,b,[],[],[],[],nonlconstr,options);
obj_val = objval_func(x,H_wave,y_wave);
end

github-repos/MATLAB/yuanhao-cui-Must-Reading-on-ISAC/Must-Reading-on-ISAC-34cd6615c52ebca121428a979e756c608b195040/Codes/Fan2018TSP/Codes for DFRC Waveform Design/Constant Modulus/QCQP_LB1.m


function [D,G,B] = autoGen_acrobotDynamics(q1,q2,dq1,dq2,m1,m2,g,l1,l2)
%AUTOGEN_ACROBOTDYNAMICS
%    [D,G,B] = AUTOGEN_ACROBOTDYNAMICS(Q1,Q2,DQ1,DQ2,M1,M2,G,L1,L2)

%    This function was generated by the Symbolic Math Toolbox version 6.2.
%    12-Jun-2015 16:56:47

t2 = cos(q1);
t3 = l1.^2;
t4 = sin(q1);
t5 = cos(q2);
t6 = l1.*t2;
t7 = l2.*t5;
t8 = t6+t7;
t9 = sin(q2);
t10 = l1.*t4;
t11 = l2.*t9;
t12 = t10+t11;
t13 = l2.^2;
D = reshape([-m1.*t2.^2.*t3-m1.*t3.*t4.^2-l1.*m2.*t2.*t8-l1.*m2.*t4.*t12,-l1.*l2.*m2.*t2.*t5-l1.*l2.*m2.*t4.*t9,-l2.*m2.*t5.*t8-l2.*m2.*t9.*t12,-m2.*t5.^2.*t13-m2.*t9.^2.*t13],[2, 2]);
if nargout > 1
    t14 = dq1.^2;
    t15 = dq2.^2;
    t16 = l1.*t2.*t14;
    t17 = l2.*t5.*t15;
    t18 = t16+t17;
    t19 = l1.*t4.*t14;
    t20 = l2.*t9.*t15;
    t21 = t19+t20;
    G = [-g.*m2.*t12+m2.*t8.*t21-m2.*t12.*t18-g.*l1.*m1.*t4;-g.*l2.*m2.*t9+l2.*m2.*t5.*t21-l2.*m2.*t9.*t18];
end
if nargout > 2
    B = [0.0;-1.0];
end


%% PLANEWAVEMAXWELL1 plane wave solutions to Maxwell equations in a cube.
%
% Test Maxwell function can solve problems with complex solution and
% indefinite case.
%
% See also  planewaveMaxwell, planewaveMaxwell2
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

close all;

%% Generate an initial mesh
[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);
bdFlag = setboundary3(node,elem,'Neumann');

%% Parameters
maxIt = 4;
N = zeros(maxIt,1);
h = zeros(maxIt,1);
energyErr = zeros(maxIt,1);
L2Err = zeros(maxIt,1);
energyErrImag = zeros(maxIt,1);
L2ErrImag = zeros(maxIt,1);

%% Get the data of the pde
global d P omega
d = [1, pi/2, pi/2];  % in sphereical coordinate
P = [1, 0, 0];
omega = 1;
r = d(1); theta = d(2); phi = d(3);
d = [r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)];
% pde = planewavedataC; % plane wave with complex coefficients
pde = planewavedata; % plane wave with real coefficients and complex solution

%% Finite Element Method
for k = 1:maxIt
    % refine grid
    [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);
    % solve the equation
%     [u,edge,A,M] = Maxwell(node,elem,HB,pde,bdFlag);
    [u,edge,eqn] =  Maxwell1(node,elem,bdFlag,pde);
    % compute the error
    uI = edgeinterpolate1(pde.exactu,node,edge);
    L2Err(k) = sqrt(abs(real(u-uI)'*eqn.M*real(u-uI)));
    energyErr(k) = sqrt(abs(real(u-uI)'*eqn.A*real(u-uI)) + L2Err(k)^2);
    L2ErrImag(k) = sqrt(abs(imag(u-uI)'*eqn.M*imag(u-uI)));
    energyErrImag(k) = sqrt(abs(imag(u-uI)'*eqn.A*imag(u-uI)) + L2ErrImag(k)^2);
%     energyErr(k) = getHcurlerror3ND1(node,elem,pde.curlu,u);
%     L2Err(k) = getL2error3ND1(node,elem,pde.exactu,u);
    N(k) = length(u);
    h(k) = 1./(size(node,1)^(1/3)-1);
end

%% Plot convergence rates
figure(1); clf;
showrateh2(h,energyErr,1,'r-+','|| Re(u-u_h)||_A',...
           h,L2Err,1,'b-+','|| Re(u-u_h)||');
figure(2); clf;
showrateh2(h,energyErrImag,1,'r-+','|| Img(u-u_h)||_A',...
           h,L2ErrImag,1,'b-+','|| Img(u-u_h)||');


function [lp,dlp] = priorLaplaceMulti(mu,s2,x)

% Multivariate Laplace hyperparameter prior distribution.
% Compute log-likelihood and its derivative or draw a random sample.
% The prior distribution is parameterized as:
%
%   p(x) = exp(-sqrt(2)*sqrt(r2))/sqrt(det(2*s2)),
%          where r2(x) = (x-mu)'*inv(s2)*(x-mu),
%
% further mu(Dx1) is the mean parameter, s2(Dx1) or s2(DxD) is the variance
% parameter and x(DxN) contains query hyperparameters for prior evaluation.
%
% For more help on design of priors, try "help priorDistributions".
%
% Copyright (c) by Hannes Nickisch, 2014-10-15.
%
% See also PRIORDISTRIBUTIONS.M, PRIORLAPLACE.M.

if nargin<2, error('mu and s2 parameters need to be provided'), end
if ndims(mu)~=2 || size(mu,2)~=1, error('mu needs to be (Dx1)'), end
D = size(mu,1);
s2_ok = ndims(s2)==2 && all(size(s2)==[D,1] | size(s2)==[D,D]);
if ~s2_ok, error('s2 needs to be (DxD) or (Dx1)'), end
if size(s2,2)==D                                        % full multivariate case
  s = chol(s2)'; lds = sum(log(diag(s)));                 % lds = log(det(s2))/2
else                                                       % diagonal covariance
  s = sqrt(s2);  lds = sum(log(s));
end
if nargin<3                                             % return a random sample
  u = rand(D,1)-1/2; lp = sign(u).*log(1-2*abs(u))/sqrt(2);        % unit sample
  if size(s,2)==D, lp = s*lp+mu; else lp = s.*lp+mu; end % affine transformation
  return
end
if D==1 && size(x,1)>1                            % both mu/s2 scalar => inflate
  D = size(x,1); mu = mu*ones(D,1); s = s*ones(D,1); lds = D*lds;
end
if ~(ndims(x)==2 && size(x,1)==D), error('x needs to be (Dxn)'), end

oN = ones(1,size(x,2));
if size(s,2)==D
  xm = x-mu*oN; xs = s\xm;
else
  xm = x-mu*oN; xs = xm./(s*oN);
end

dlp = -sqrt(2)*sign(xs);
lp = -sqrt(2)*sum(abs(xs),1) - D*log(2)/2 - lds;
if size(s,2)==D, dlp = s'\dlp; else dlp = dlp./(s*oN); end


function [dprime, prefCond] = mv_dprime(mv, conditions, verbose);
% [dprime, prefCond] = mv_dprime(mv, [conditions=all], [verbose=1]);
%
%
% Compute a 'd prime' form of selectivity index for a multi-voxel UI, given the selected
% conditions and threshold.
%
% This measure of d-prime performs a series of pairwise comparisons between
% each voxel's 'preferred' condition (the condition which elicits the highest
% response) to each of the other 'nonpreferred' conditions. For each
% comparison, it computes the 'd-prime', separation over spread, between
% those 2 conditions. This is defined (for conditions A and B) as:
%
%    d' = (meanA - meanB) / sqrt((varianceA + varianceB) / 2)
%
% Response amplitudes are computed according the to
% event-related paramter 'ampType': see er_setParams, er_defaultParams.
%
% In addition to coding the degree of response, this also returns a list of
% the preferred condition for each category.
%
% If the verbose flag is set to 1 (default), will report how many voxels prefer each
% condition.
%
% ras 09/06: written.
if notDefined('verbose'), verbose = prefsVerboseCheck; end
if notDefined('conditions'),
    conditions = mv.trials.condNums(mv.trials.condNums>0);
end

mv.params.selConds = conditions;
amps = mv_amps(mv);
amps = amps(:,conditions);
varAll = (mv_stdev(mv)) .^ 2; % variance = sigma^2
nVoxels = size(amps,1);
nConds = size(amps,2);

%%%%% step 1: find preferred cond for each condition
mx = max(amps,[],2); % max values
for i = 1:nVoxels
    if isnan(mx(i)) | sum( amps(i,:)==mx(i) ) > 1
        prefCond(i) = NaN;
        other(i,:) = NaN;
        varA(i,:) = NaN;
        varB(i,:) = NaN;
        continue;
    end

    % preferred condition
    prefCond(i) = find(amps(i,:)==mx(i));

    % amplitudes of other conditions
    other(i,:) = amps(i,setdiff(1:nConds,prefCond(i)));

    % get variance estimates for max, nonmax conds
    varA(i,1) = varAll(i,prefCond(i));
    varB(i,:) = varAll(i,setdiff(1:nConds,prefCond(i)));
end

% remove entries with NaNs
ok = ~isnan(prefCond);
prefCond = prefCond(ok);
other = other(ok,:);
varA = varA(ok,:);
varB = varB(ok,:);
mx = mx(ok,:);

%%%%% step 2: do pairwise comparisons
dprime = [];
for i = 1:size(other, 2)
    dprime(:,i) = [mx - other(:,i)] ./ sqrt([varA + varB(:,i)]./2);
end

% take mean across comparisons for each voxel
dprime = nanmean(dprime, 2);

% report breakdown by condition, if requested
if verbose==1
    for i=1:nConds
        fprintf(1,'cond %i numvoxels %i\n', i, sum(prefCond==i));
    end
end

return


function example4 ( )

%*****************************************************************************80
%
%% EXAMPLE4 demonstrates the use of PDEPE on a variable coefficient PDE system.
%
%  Discussion:
%
%    Solve the system of convection-diffusion equations.
%
%    PDE:
%      ut - 2 ux -   vx = uxx
%      vt -   ux - 2 vx - ( 3 (ubar(x))^2 u ) = vxx
%    BC:
%      u(t,-oo) = u(t,+oo) = 0
%      v(t,-oo) = v(t,+oo) = 0
%    IC:
%      u(0,x) = exp ( - (x-5)^2 )
%      v(0,x) = exp ( - (x+5)^2 )
%
%    Here, ubar(x) is the first component in the solution of the boundary value
%    problem:
%
%      ubarx = - 2 ( ubar + 2 ) - vbar
%      vbarx = - ( ubar + 2 ) - 2 vbar - ( ubar^3 + 8 )
%      ubar(-oo) = -2, ubar(+oo) = 1
%      vbar(-oo) = 0, vbar(+00) = -6
%
%    Although the mathematical problem has boundary conditions at infinity,
%    we approximate this by the interval [-25,+25].
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2013
%
%  Author:
%
%    Original formulation by P Howard.
%    This version by John Burkardt.
%
%  Reference:
%
%    P Howard,
%    Partial Differential Equations in Matlab 7.0,
%    Spring 2005.
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'EXAMPLE4:\n' );
  fprintf ( 1, '  A convection-diffusion system:\n' );
  fprintf ( 1, '  ut - 2 ux -   vx = uxx\n' );
  fprintf ( 1, '  vt -   ux - 2 vx - ( 3 (ubar(x))^2 u ) = vxx\n' );
  fprintf ( 1, '  u(t,-oo) = u(t,+oo) = 0\n' );
  fprintf ( 1, '  v(t,-oo) = v(t,+oo) = 0\n' );
  fprintf ( 1, '  u(0,x) = exp ( - (x-5)^2 )\n' );
  fprintf ( 1, '  v(0,x) = exp ( - (x+5)^2 )\n' );
%
%  M defines the coordinate system:
%  0: cartesian
%  1: cylindrical
%  2: spherical
%
  m = 0;
%
%  Define the spatial mesh.
%
  nx = 101;
  xmesh = linspace ( -25.0, +25.0, nx );
%
%  Define the time mesh.
%
  nt = 21;
  tspan = linspace ( 0.0, 2.0, nt );
%
%  Call PDEPE() for the solution.
%
  sol = pdepe ( m, @pdefun, @icfun, @bcfun, xmesh, tspan );
%
%  Copy out the two components of the solution.
%
  u = sol(:,:,1);
  v = sol(:,:,2);

  figure ( 1 )
  subplot(2,1,1)
  surf ( xmesh, tspan, u, 'EdgeColor', 'None' );
  title ( 'Example 4: Solution U Over Time', 'Fontsize', 16 );
  xlabel ( '<--- X --->' )
  ylabel ( '<--- T --->' );
  zlabel ( '<---U(X,T)--->' );
  subplot(2,1,2)
  surf ( xmesh, tspan, v, 'EdgeColor', 'None' );
  title ( 'Example 4: Solution V Over Time', 'Fontsize', 16 );
  xlabel ( '<--- X --->' )
  ylabel ( '<--- T --->' );
  zlabel ( '<---V(X,T)--->' );
  filename = 'example4.png';
  print ( '-dpng', filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Saved solution plot in file "%s"\n', filename );
%
%  Plot the initial condition, U at time 0.
%
  figure ( 2 )
  subplot(2,1,1)
  plot ( xmesh, u(1,:), 'LineWidth', 3 );
  grid on
  title ( 'Example 4: Initial Condition U(X,0)', 'Fontsize', 16 );
  xlabel ( '<--- X --->' )
  ylabel ( '<--- U(X,T0) --->' );
  subplot(2,1,2)
  plot ( xmesh, v(1,:), 'LineWidth', 3 );
  grid on
  title ( 'Example 4: Initial Condition V(X,0)', 'Fontsize', 16 );
  xlabel ( '<--- X --->' )
  ylabel ( '<--- V(X,T0) --->' );
  filename = 'example4_ic.png';
  print ( '-dpng', filename );
  fprintf ( 1, '  Saved initial condition plot in file "%s"\n', filename );
%
%  Plot the solution at a fixed point, with time varying.
%
  mid = ( nx + 1 ) / 2;

  figure ( 3 )
  subplot(2,1,1)
  plot ( tspan, u(:,mid), 'LineWidth', 3 );
  grid on
  title ( 'Example 4: Time evolution of U(0,T)', 'Fontsize', 16 );
  xlabel ( '<--- T --->' )
  ylabel ( '<--- U(0.0,T) --->' );
  subplot(2,1,2)
  plot ( tspan, v(:,mid), 'LineWidth', 3 );
  grid on
  title ( 'Example 4: Time evolution of V(0,T)', 'Fontsize', 16 );
  xlabel ( '<--- T --->' )
  ylabel ( '<--- V(0.0,T) --->' );
  filename = 'example4_profile.png';
  print ( '-dpng', filename );
  fprintf ( 1, '  Saved time evolution plot in file "%s"\n', filename );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'EXAMPLE4:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function xprime = degode ( t, x )

%*****************************************************************************80
%
%% DEGODE stores an ODE for a standing wave.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real T, the current time.
%
%    Input, real X, the spatial location.
%
%    Output, real XPRIME(2,1), the right hand side of the differential
%    equation satisfied by ( UBAR, VBAR ).
%
  xprime(1,1) =  - 2.0 * ( x(1) + 2.0 ) - x(2);
  xprime(2,1) = - ( x(1) + 2.0 ) - 2.0 * x(2) - ( x(1)^3 + 8.0 );

  return
end
function ubar = pdegwave ( x )

%*****************************************************************************80
%
%% PDEGWAVE determines the value of UBAR in the equation.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the spatial location.
%
%    Output, real UBAR, the value of UBAR at X.
%
  small = 0.000001;

  if ( x < -20.0 )
    ubar = -2.0;
    vbar = 0.0;
  else
    tspan = [ -20, x ];
    x0 = [ -2.0 + small, - small ];
    [ t, x ] = ode45 ( @degode, tspan, x0 );
    ubar = x(end,1);
    vbar = x(end,2);
  end

  return
end
function [ c, f, s ] = pdefun ( x, t, u, dudx )

%*****************************************************************************80
%
%% PDEFUN defines the components of the PDE.
%
%  Discussion:
%
%    The PDE has the form:
%
%      c * du/dt = x^(-m) d/dx ( x^m f ) + s
%
%    where m is 0, 1 or 2,
%    c, f and s are functions of x, t, u, and dudx,
%    and most typically, f = dudx.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the spatial location.
%
%    Input, real T, the current time.
%
%    Input, real U(:,1), the estimated solution at T and X.
%
%    Input, real DUDX(:,1), the estimated spatial derivative of U at T and X.
%
%    Output, real C(:,1), the coefficients of du/dt.
%
%    Output, real F(:,1), the flux terms.
%
%    Output, real S(:,1), the source terms.
%
  c = [ 1.0; 1.0 ];
  ubar = pdegwave ( x );
  f(1) = dudx(1) + 2.0 * u(1) + u(2);
  f(2) = dudx(2) + u(1) + 2.0 * u(2) + 3.0 * ubar^2 * u(1);
  s = [ 0.0; 0.0 ];

  return
end
function u0 = icfun ( x )

%*****************************************************************************80
%
%% ICFUN defines the initial conditions.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the spatial location.
%
%    Output, real U0(:,1), the value of the solution at the initial time,
%    and location X.
%
  u0(1) = exp ( - ( x - 5.0 )^2 );
  u0(2) = exp ( - ( x + 5.0 )^2 );

  return
end
function [ pl, ql, pr, qr ] = bcfun ( xl, ul, xr, ur, t )

%*****************************************************************************80
%
%% BCFUN defines the boundary conditions.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real XL, the spatial coordinate of the left boundary.
%
%    Input, real UL(:,1), the solution estimate at the left boundary.
%
%    Input, real XR, the spatial coordinate of the right boundary.
%
%    Input, real UR(:,1), the solution estimate at the right boundary.
%
%    Output, real PL(:,1), the Dirichlet portion of the left boundary condition.
%
%    Output, real QL(:,1), the coefficient of the flux portion of the left
%    boundary condition.
%
%    Output, real PR(:,1), the Dirichlet portion of the right boundary condition.
%
%    Output, real QR(:,1), the coefficient of the flux portion of the right
%    boundary condition.
%
  pl = [ ul(1); ul(2) ];
  ql = [ 0.0; 0.0 ];
  pr = [ ur(1); ur(2) ];
  qr = [ 0.0; 0.0 ];

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


function [price, stdErr] = Price_MC_Lookback_func(Spath, call, M, mult, disc)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% About: Calculates Looback option price, given the simulatd paths
% Author: Justin Lars Kirkby
%
% -----------------
% Params
% -----------------
% Contract Types
% Floating Strike (Lookback) Put:  max{S_m: 0<=m<=M} - S_T
% Floating Strike (Lookback) Call: S_T - min{S_m: 0<=m<=M}
%
% Spath = paths of underlying, dimension N_sim x M+1, where M = number of time steps (since includes S_0)
% call = 1 for call (else put)
% M = number of monitoring points, e.g. 252 for "daily" monitoring
% mult = time partitioning multiplier to reduce bias (e.g. mult = 2 or 5)
% S_0 = initial price
% disc = discount factor (e.g. exp(-r*T))
% T = Time (in years)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

N_sim = size(Spath,1);  % number of paths

M_mult = M*mult;  %time partitioning to reduce bias

if call ~= 1
    curr_max = zeros(N_sim, 1);
    for n = 1:N_sim
        curr_max(n) = max(Spath(n, 1:mult:M_mult+1));
    end
else  % find_min
    curr_min = zeros(N_sim, 1);
    for n = 1:N_sim
        curr_min(n) = min(Spath(n, 1:mult:M_mult+1));
    end
end

if call ==1  % Floating Strike (Lookback) Call: S_T - min{S_m: 0<=m<=M}
   payoffs  = Spath(:, M_mult+1) - curr_min;

else  % Floating Strike (Lookback) Put:  max{S_m: 0<=m<=M} - S_T
    payoffs  = curr_max - Spath(:,M_mult+1);
end
price = disc*mean(payoffs);
stdErr = disc*std(payoffs) / sqrt(N_sim);

end


% To run unit tests:
%
% testCase = TestBspline;
% res = run(testCase);
%
classdef TestBspline < matlab.unittest.TestCase
    %
    % Test the spline scripts
    %

    properties
       cpts
    end

    methods (TestClassSetup)

       function setup(this)
            cpts = [0 2;
                        0 4;
                        0 6;
                        0 8;
                        0 10];

            cpts = cpts + 10*rand*randn(size(cpts));
            this.cpts = cpts;
       end

    end

    methods (Test)

        function recover(this)
            nland = size(this.cpts,1);
            sval = bspline_gen_s(nland);
            X = bspline_eval(sval,this.cpts);

            % Test fit of control points
            P = bspline_fit(sval,X,nland);
            if aeq(P,this.cpts)
               fprintf(1,'Landmarks recovered exactly! \n');
            else
               fprintf(1,'FAILED TO RECOVER landmarks \n');
            end

            % plot the spline
            figure(1);
            clf
            hold on
            x = X(:,1);
            y = X(:,2);
            plot(x,y,'b-');
            plot(this.cpts(:,1),this.cpts(:,2),'r.','MarkerSize',16);

        end
    end

end


function pde = StokesZulehnerdata
%% STOKESDATA2 data for Stokes equations
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

pde = struct('f', @f, 'exactp', @exactp, 'exactu', @exactu,'g_D',@g_D);

    function z = f(p)
        x = p(:,1); y = p(:,2);
        z(:,1) = zeros(size(x));
        z(:,2) = 4*cos(x).*cos(y);
    end
    % exact velocity
    function z = exactu(p)
        x = p(:,1); y = p(:,2);
        z(:,1) = sin(x).*sin(y);
        z(:,2) = cos(x).*cos(y);
    end
    % exact pressure
    function z = exactp(p)
        x = p(:,1); y = p(:,2);
        z = 2*cos(x).*sin(y) - 2*sin(1)*(1-cos(1));
    end
    % Dirichlet boundary condition of velocity
    function z = g_D(p)
        z = exactu(p);
    end
end


function [Utest, Vtest] = trainMF(X, MFparam)

% Input:
%          X: n*d, n is the number of images
%          ITQparam:
%                           ITQparam.pcaW---PCA of all the database
%                           ITQparam.nbits---encoding length
% Output:
%             ITQparam:
%                              ITQparam.pcaW---PCA of all the database
%                              ITQparam.nbits---encoding length
%                              ITQparam.r---ITQ rotation projection

gamma =0.0001;

lambda = 0.001;

iter = 1;
lastF = 99999999;
threshold = 0.001;

[n, d] = size(X);

%V = rand(bits, ntrain);

% initialize with a orthogonal random rotation

d = MFparam.nbits;

U = randn(n, d);

%V = randn(d, d);

% ITQ to find optimal rotation
while (true)

    V = (U'*U+gamma*eye(d))\(U'*X);

    U = (X*V')/(V*V'+lambda*eye(d));

%     U = (X*V')/(V*V'+lambda*eye(d)); % this is not good
%     V = (U'*U+gamma*eye(d))\(U'*X);

    % compute objective function
    norm1 = norm(X - U * V, 'fro');
    norm2 = lambda * norm(U, 'fro') + gamma * norm(V, 'fro');
    currentF= norm1 + norm2;

    fprintf('\nobj at iteration %d: %.4f\n reconstruction error for matrix factorization: %.4f,\n regularization term: %.4f\n\n', iter, currentF, norm1 , norm2);
    if (lastF - currentF) < threshold
        fprintf('algorithm converges...\n');
        fprintf('final obj: %.4f\n reconstruction error for matrix factorization: %.4f, \n regularization term: %.4f\n\n', currentF,norm1, norm2);

        Utest = U;
        Vtest = V;
        return
    end
    iter = iter + 1;
    lastF = currentF;
end

% make B binary
%B = UX;
%B(B<0) = 0;

%ITQTparam.r = R;


function [trend,cyclic] = beveridgenelson(y,parameters,constant,p,q)
% Beveridge-Nelson decomposition for a trending time series.
%
% USAGE:
%   [TREND,CYCLIC] = beveridgenelson(y,parameters,constant,p,q)
%
% INPUTS:
%   Y          - T by 1 column of trending data data
%   PARAMETERS - 1 by CONSTANT + length(P) + length(Q) vector of parameters estimated on diff(Y)
%   CONSTANT   - Scalar variable: 1 the the fit model included a constant
%   P          - Non-negative integer vector representing the AR orders of the fit model
%   Q          - Non-negative integer vector representing the MA orders of the fit model
%
% OUTPUTS:
%   TREND      - T by 1 vector of containing the trend.  First max(P)+1 observations are the same as Y
%   CYCLIC     - T by 1 vector of containing the cyclic component.  First max(P)+1 observations are
%                  the same as Y
%
% COMMENTS:
%   Uses the exact BN decomposition as presented in
%
%   Paul Newbold, "Precise and efficient computation of the Beveridge-Nelson decomposition of
%     economic time series", Journal of Monetary Economics, Volume 26, Issue 3, December 1990, Pages
%     453-457.
%
%   This decomposition is based on a demeaned ARMA model for the short-run dynamics.  If CONSTANT = 1,
%   this function will demeand the data using the model implied long-run mean (the constant
%   parameter divided by the sum of the AR coefficients).
%
% EXAMPLES:
%   BN decomposition for Real US GDP using an AR(1) for the SR component
%       load GDP
%       parameters = armaxfilter(diff(lnGDP),1,1);
%       [trend,cyclic] = beveridgenelson(lnGDP,parameters,1,1);
%   BN decomposition for Real US GDP using an ARMA(1,4) for the SR component
%       parameters = armaxfilter(diff(lnGDP),1,1,1:4);
%       [trend,cyclic] = beveridgenelson(lnGDP,parameters,1,1,1:4);
%
% See also ARMAXFILTER

% Copyright: Kevin Sheppard
% kevin.sheppard@economics.ox.ac.uk
% Revision: 1    Date: 11/1/2009

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Input Checking
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch nargin
    case 3
        p=[];
        q=[];
    case 4
        q=[];
    case 5
        % Nothing
    otherwise
        error('3 to 5 inputs required.');
end
if size(y,2)>size(y,1)
    y=y';
end
if size(y,2)~=1
    error('Y must be a T by 1 vector.');
end
if ~ismember(constant,[0 1])
    error('CONSTANT must be 0 or 1.')
end
np = length(p);
nq = length(q);
if np>0
    maxp = max(p);
else
    maxp = 0;
end
if nq>0
    maxq = max(q);
else
    maxq = 0;
end
if length(parameters)~=(constant+np+nq)
    error('PARAMETERS must have CONSTANT + length(P) + length(Q) parameters.');
end
% Remove the constant, if any
if constant
    constant = parameters(1);
    parameters = parameters(2:length(parameters));
    if np>0
        longRunMean = constant/(1-sum(parameters(1:np)));
    else
        longRunMean = constant;
    end
end
deltaY = diff(y) - longRunMean;
if maxp>0
    A = zeros(maxp);
    A(1,p) = parameters(1:np);
    for i=2:maxp
        A(i,i-1) = 1;
    end
    Aeigs = abs(eig(A));
    if  max(Aeigs)>=1
        error('The model for the short-run dynamics is not stationary. Stationarity is required for the BN decomposition to be well defined.');
    end
else
    A = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Input Checking
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

T = size(deltaY,1);
% Construct the errors
m = max(maxp,maxq);
zerosToPad = max(maxq-maxp,0);
deltaYAugmentedForMA = [zeros(zerosToPad,1);deltaY];
errors = armaxerrors(parameters,p,q,0,deltaYAugmentedForMA,[],m,ones(size(deltaYAugmentedForMA)));
errors = errors(zerosToPad+1:length(errors));

% Initialize the trend and cyclic component
trend = zeros(T+1,1);
trend(1:maxp+1) = y(1:maxp+1);
cyclic = zeros(T+1,1);
deltaYForecast = zeros(T+m,1);
errorsForecast = zeros(1,T+m);
% Initialize the coefficient needed
e = [1 zeros(1,maxp-1)];
longRunScale = (eye(maxp) - A)^(-1)*A;
longRunScale = e*longRunScale;
for t = maxp + 1 : T
    % Construct maxq forecasts, then use companion matrix to compute sum
    deltaYForecast(:) = 0;
    errorsForecast(:) = 0;
    deltaYForecast(1:t) = deltaY(1:t);
    errorsForecast(1:t) = errors(1:t);
    for h = 1 : maxq
        for j=1:np
            deltaYForecast(t+h) = deltaYForecast(t+h) + parameters(j) * deltaYForecast(t+h-p(j));
        end
        for j=1:nq
            if (t+h-q(j))>0
                deltaYForecast(t+h) = deltaYForecast(t+h) + parameters(np+j) * errorsForecast(t+h-q(j));
            end
        end
    end
    % Select the correct forecasts
    cumForecast = sum(deltaYForecast(t+1:t+maxq));
    if np>0
        deltaYHat=deltaYForecast(t+maxq-maxp+1:t+maxq);
        cumForecast = cumForecast + longRunScale*deltaYHat;
    end
    trend(t+1) = y(t+1) + cumForecast;
    cyclic(t+1) = -cumForecast;
end


%  MULTIPLICITY --> Computing the multiplicity and multiplicity structure
%  of a system of nonlinear equations at an isolated zero.
%
%  <Synopsis>
%          m = Multiplicity(f, variables, zero)
%          m = Multiplicity(f, variables, zero, options)
%  [m, D, H] = Multiplicity(f, variables, zero)
%  [m, D, H] = Multiplicity(f, variables, zero, options)
%
%  <Input Parameters>
%    1. f         --> a cell array containing the system of nonlinear
%                     equations as strings, e.g.,
%                         >>   f = { 'x^2 + sin(y) -1',  'x-cos(y)' };
%
%    2. variables --> a cell array containing the unknown variables as
%                     strings, e.g.,
%                         >>   variables = { 'x',  'y' };
%
%    3. zero      --> a vector containing numerical zero (root) of f, e.g.,
%                         >>   zero = [1, 0];
%
%    4. options   --> an optional parameter which includes the configuration
%                     settings:
%                     Display: Set to 2 to have all output (the dual space
%                              and Hilbert function) printed to the screen,
%                              and set to 1 to have depth and Hilbert
%                              function printed to the screen. Otherwise
%                              set the default value 0;
%                         Tol: The threshold for numerical rank-revealing.
%                              Singular values above Tol are counted as
%                              nonzero. The default value is 1e-8;
%                     EqnType: The equation type for MULTIPLICITY,
%                              polynomial system ('Poly') or nonlinear
%                              functions ('Nonlinear'). The default value is
%                              'Nonlinear'. By setting the value to 'Poly',
%                              MULTIPLICITY will transfer the polynomial
%                              system to the matrix representation
%                              internally and speed up the computation.
%                      MaxInt: Maximum multiplicity allowed in the recursive
%                              computation. If a zero is not isolated, the
%                              multiplicity will be infinity.  The code can
%                              be used for identifying a nonisolated zero by
%                              setting MaxInt to a known upper bound (e.g.
%                              the Bezout number). The default value is 1000.
%
%                     All the configuration settings may be changed by using
%                     optset function, i.e.,
%                         >>   options = optset('para', value);
%                     para could be any configuration setting, value is set
%                     to para. See OPTSET for details. Any configuration
%                     setting that is not changed will be set to its default
%                     value.
%
%  <Output Parameters>
%    1. m        --> the multiplicity of f at the zero;
%
%    2. D        --> a basis for the dual space as a cell array with
%                    each component being a matrix in the Matlab form of
%                                   D{i} = [c_1, j_1;
%                                           c_2, j_2;
%                                             ...
%                                           c_n, j_n ];
%                    representing a differential functional
%                            D_i = c_1*d_{j_1} + ... + c_n*d_{j_n}
%                    where d_{j_i}'s are differential monomial functionals
%                    (e.g. For a system of equations with variables {x,y,z}
%                     at the zero x=a, y=b, z=c, the functional d_{[i,j,k]}
%                     applied to any function g is the value of the partial
%                     derivative
%
%                                                         i+j+k
%                                             1          d
%                         d_{[i,j,k]}(g) = -------- * ----------- g(a,b,c)
%                                          i! j! k!     i   j   k
%                                                     dx  dy  dz
%
%                     The dual space is the vector space consists of such
%                     differential functionals that vanish on the nonlinear
%                     system while satisfying the so-called closedness
%                     condition);
%
%    3. H        --> values of the Hilbert function in a vector.
%
%  <Examples>
%   Consider the nonlinear system
%
%               sin(x)*cos(y)-x       = 0
%               sin(y)*sin(x)^2 - y^2 = 0
%
%   at the zero (x, y) = (0, 0), the multiplicity can be computed by the
%   following statements:
%
%     >> f = {'sin(x)*cos(y) - x', 'sin(y)*sin(x)^2 - y^2'};
%     >> variables = {'x', 'y'};
%     >> zero = [0, 0];
%     >> m = Multiplicity(f, variables, zero)
%
%   To create an options structure with Tol = 1e-10, MaxInt = 100:
%     >> options = optset('Tol', 1e-10, 'MaxInt', 100);
%     >>  m = Multiplicity(f, variables, zero, options)
%
%  <Algorithm>
%   This code implements a modified closedness subspace method for
%   multiplicity identification with a newly developed equation-by-equation
%   strategy for improving efficiency.
%
%  <References>
%  [1] An algorithm and software for computing multiplicity structures at
%      zeros of nonlinear systems, W. Hao, A. J. Sommesse and Z. Zeng
%  [2] The closedness subspace method for computing the multiplicity
%      structure of a polynomial system, Z. Zeng.
%
%  See also optset, cell


function ellipseXSection(lmsCov, planeDims, nPts, nSD, ThreeDflag)
% Plot the predictions within a plane for an ellipsoid
%
%    ellipseXSection(lmsCov, planeDims, nPts, nSD)
%
% For the L,M, set planeDims = [1,2], and for L,S set planeDims [1,3]
%
% Example:
%
%
% See also:
%
% Copyright HH, Vistalab 2010

if ieNotDefined('lmsCov'), lmsCov = eye(3,3); end
if ieNotDefined('planeDims'), planeDims = [1,2]; end
if ieNotDefined('nSD'), nSD = 2; end
if ieNotDefined('nPts'), nPts = 45; end
if ieNotDefined('ThreeDflag'), ThreeDflag = false; end

% Make points on a circle
[x,y] = circlePoints(2*pi/nPts);
spherePoints = zeros(length(x),3);
spherePoints(:,planeDims(1)) = x(:);
spherePoints(:,planeDims(2)) = y(:);

eVec = zeros(size(spherePoints,1),2);
for ii=1:size(spherePoints,1)
    l = spherePoints(ii,:)*(lmsCov\spherePoints(ii,:)');
    eVec(ii,:) = nSD*(spherePoints(ii,planeDims)/sqrt(l)); % + mn;
end

if ThreeDflag == false,
    plot(eVec(:,1),eVec(:,2),'r.'); axis equal; grid on

elseif ThreeDflag == true,
    z = zeros(size(spherePoints,1));

    switch num2str(planeDims)
        case '1  2'
            plot3(eVec(:,1),eVec(:,2),z,'r.');
        case '1  3'
            plot3(eVec(:,1),z,eVec(:,2),'r.');
        case '2  3'
            plot3(z,eVec(:,1),eVec(:,2),'r.');
        otherwise
            error('planeDims should be [1 2],[1 3],[2 3].');
    end
    axis equal; grid on
end

% Not sure if we need a square root to compute the ratio of the longest to
% shortest axes.
% axisLengths = sqrt(eig(cov(eVec)));
% cNum = axisLengths(end)/axisLengths(1);

return


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Author: Eugenio Alcala Baselga
% Date: 02/06/2018
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [ Ac, Bc ] = KinemError_Dyn_LPV_Model (omega_SV,vel_SV,theta_E_SV,delta_SV,alpha_SV) %#codegen

    % Vamos a empezar usando delta, pero es posible que haya que hhacer un
    % cambio de variable a sigma como se hizo anteriormente.

    % Vehicle parameters
    M       = 683;
    I       = 561;
    a       = 0.758;
    b       = 1.036;
    g       = 9.81;
    ro      = 1.2;
    Cf      = 15000;
    Cd      = 0.5;
    Area    = 4;
    mu_roz  = 0.1;

    epsilon = 10^-8;

    %% Model LPV parameters:

    F_drag  = 0.5*ro*Cd*Area*vel_SV*vel_SV;
    F_rozamiento = mu_roz*M*g;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Note:
% This the model used in the MPC-LPV. It has more trigonometric
% commbinations than the used in the IET paper. It is below.

    A1 = -(F_drag+F_rozamiento) / (M*(vel_SV+epsilon));

    A2 = Cf*(sin(delta_SV)*cos(alpha_SV)-sin(alpha_SV)*cos(delta_SV)-sin(alpha_SV)) / M;

    A3 = Cf*(a*(sin(delta_SV)*cos(alpha_SV)-sin(alpha_SV)*cos(delta_SV)) - b*sin(alpha_SV)) / (M*(vel_SV+epsilon));

    B1 = Cf*(sin(delta_SV)*cos(alpha_SV)-sin(alpha_SV)*cos(delta_SV)) / M;

    B2 = cos(alpha_SV) / M;

    A4 = -Cf*(cos(alpha_SV)*cos(delta_SV)+sin(alpha_SV)*sin(delta_SV)+cos(alpha_SV)) / (M*(vel_SV+epsilon));

    A5 = ( (-Cf*a*(cos(delta_SV)*cos(alpha_SV)+sin(alpha_SV)*sin(delta_SV)) + Cf*b*cos(alpha_SV)) / (M*(vel_SV*vel_SV)) ) - 1;

    B3 = Cf*(cos(alpha_SV)*cos(delta_SV)+sin(alpha_SV)*sin(delta_SV)) / (M*(vel_SV+epsilon));

    B4 = -sin(alpha_SV) / (M*(vel_SV+epsilon));

    A6 = Cf*(b-a*cos(delta_SV)) / I;

    A7 = -Cf*(a*a*cos(delta_SV) + b*b) / (I*(vel_SV+epsilon));

    B5 = (Cf*a*cos(delta_SV)) / I;

%     A9 = (v_d * sin(theta_E_SV)) / (theta_E_SV+epsilon);
    A9 = (vel_SV * sin(theta_E_SV)) / (theta_E_SV+epsilon); % This should be the reference
%     A10 = (vel_SV * cos(theta_E_SV)) / (theta_E_SV);        % This should be the reference
%     A10 = vel_SV / (theta_E_SV+epsilon);
%     A11 = omega_SV;                                         % This should be the reference

    Ac      = [     0     omega_SV  0   -1   0   0;
                -omega_SV    0      A9   0   0   0;
                    0        0      0    0   0   -1;
                    0        0      0    A1  A2  A3;
                    0        0      0    0   A4  A5;
                    0        0      0    0   A6  A7];

    Bc      = [ 0 0;
                0 0;
                0 0;
                B2 B1;
                B4 B3;
                0  B5];

    Bref = [ 1 0;
             0 0;
             0 1;
             0 0;
             0 0;
             0 0 ];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Note:
% This is the model used as dynamic LPV model in the IET paper.
% It is a little bit more simplifyied than the used in the MPC-LPV
% approach.
% % % % %     Cf = 433;
% % % % %     Cr = 367;
%     Cf = 15000;
%     Cr = 15000;

%     A1 = -(F_drag+F_rozamiento)/(M*vel_SV);
%     A2 = Cf*sin(delta_SV)/M;
%     A3 = Cf*sin(delta_SV)*a/(M*vel_SV);
%     A4 = -(Cf*cos(delta_SV)+Cr)/(M*vel_SV); %%% Might be a a mistake
%     A5 = -(Cf*a*cos(delta_SV)-Cr*b)/(M*vel_SV*vel_SV) - 1;
%     A6 = (Cr*b-Cf*a*cos(delta_SV))/I;
%     A7 = (-Cf*a*a*cos(delta_SV) + Cr*b*b)/(I*vel_SV);
%
%     B2 = 1/M;
%     B1 = Cf*sin(delta_SV)/M;
%     B3 = Cf*cos(delta_SV)/(M*vel_SV);
%     B4 = 0;
%     B5 = Cf*a*cos(delta_SV)/I;
%
%     A9 = (v_d * sin(theta_E_SV))/(theta_E_SV+epsilon);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function pde = fracLapdata1
%% FRACLAPDATA1 data for fractional Laplacian problem
%
% s a parameter in (0,1)
% k is given integer
% u = 2^(1-s)/gamma(s)*(k*pi*y)^s*besselk(s,k*pi*y).*sin(k*pi*x);
% u|_(y==0) =  sin(k*pi*x);
% g_N = ds*(k*pi)^(2*s)*sin(k*pi*x);
%
% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.

pde = struct('f',0,'exactu',@exactu,'g_D',0,'g_N',@g_N,'d',@d,'Du',@Du);

    % exact solution
    function u =  exactu(p)
        global s
        u = zeros(size(p,1),1);
        k = 3;
        x = p(:,1); y = p(:,2);
        idx = (y>eps);
        sqrtlambda = k*pi;
        z = sqrtlambda*y(idx);
        C = 2^(1-s)/gamma(s);
        u(idx) =  C*z.^s.*besselk(s,z).*sin(sqrtlambda*x(idx));
        u(~idx) = sin(sqrtlambda*x(~idx));  % at y = 0.  %% NOS 2013 p.31
    end
    function K =  d(p)  % Diffusion constant
        global s
        alpha = 1-2*s;
        %x = p(:,1);
        y = p(:,2);
        K = y.^alpha;
    end
    function z = g_N(p)
        global s
        k = 3;
        x = p(:,1); %y = p(:,2);
        ds = 2^(1-2*s)*gamma(1-s)/gamma(s);  % (2.23) in NOS 2013
        sqrtlambda = k*pi;
        z = ds*sqrtlambda^(2*s)*sin(sqrtlambda*x);
    end
    function uprime =  Du(p)
        global s
        k = 3;
        x = p(:,1); y = p(:,2);
        sqrtlambda = k*pi;
        z = sqrtlambda*y;
        uprime(:,1) = 2^(1-s)/gamma(s)*sqrtlambda*z.^s.*besselk(s,z).*cos(sqrtlambda*x);
        uprime(:,2) = -2^(1-s)/gamma(s)*sqrtlambda*z.^s.*besselk(1-s,z).*sin(sqrtlambda*x);
    end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Dh=hammingDist(B1, B2)
%
% Written by Rob Fergus
% Compute hamming distance between two sets of samples (B1, B2)
%
% Dh=hammingDist(B1, B2);
%
% Input
%    B1, B2: compact bit vectors. Each datapoint is one row.
%    size(B1) = [ndatapoints1, nwords]
%    size(B2) = [ndatapoints2, nwords]
%    It is faster if ndatapoints1 < ndatapoints2
%
% Output
%    Dh = hamming distance.
%    size(Dh) = [ndatapoints1, ndatapoints2]
%
% example query
% Dhamm = hammingDist(B2, B1);
% this will give the same result than:
%    Dhamm = distMat(U2>0, U1>0).^2;
% the size of the distance matrix is:
%    size(Dhamm) = [Ntest x Ntraining]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% loop-up table:
bit_in_char = uint16([...
    0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1 2 2 3 2 3 ...
    3 4 2 3 3 4 3 4 4 5 1 2 2 3 2 3 3 4 2 3 3 4 ...
    3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 1 2 ...
    2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 ...
    3 4 4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 ...
    5 6 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 1 2 2 3 ...
    2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 ...
    4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 ...
    3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 2 3 3 4 3 4 ...
    4 5 3 4 4 5 4 5 5 6 3 4 4 5 4 5 5 6 4 5 5 6 ...
    5 6 6 7 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 4 5 ...
    5 6 5 6 6 7 5 6 6 7 6 7 7 8]);

n1 = size(B1,1);
[n2, nwords] = size(B2);

Dh = zeros([n1 n2], 'uint16');
for j = 1:n1
    for n=1:nwords
        y = bitxor(B1(j,n),B2(:,n));
        Dh(j,:) = Dh(j,:) + bit_in_char(y+1);
    end
end


function H = normalize_H(H, type)
% function H = normalize_H(H, type)
%
% Normalize rows of H using type which can be:
%  1   - use 1-norm [default]
%  2   - use 2-norm
%  k   - multiply the 1-norm by k
%  'a' - means make sum(H(:))=1
%
% 2010-01-14 Graham Grindlay (grindlay@ee.columbia.edu)

% Copyright (C) 2008-2028 Graham Grindlay (grindlay@ee.columbia.edu)
%
% 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/>.

if nargin < 2
    type = 0;
end

switch type
    case 1
        for i = 1:size(H,1)
            H(i,:) = H(i,:) ./ norm(H(i,:),1);
        end

    case 2
        for i = 1:size(H,1)
            H(i,:) = H(i,:) ./ norm(H(i,:),2);
        end

    case 'a'
        H = H./sum(H(:));

    case 0

    otherwise
        for i = 1:size(H,1)
            H(i,:) = type*H(i,:) ./ norm(H(i,:),1);
        end
end


% TP model transformation based controller design for the parallel-type double inverted pendulum
% Szabolcs Nagy, Zoltan Petres, Peter Baranyi
% FUZZ-IEEE 2008 p1374-1380

m_k = 1.0; % kg
m_1 = 0.3; % kg
m_2 = 0.1; % kg
g   = 9.8; % m/s^2
l_1 = 0.6; % m
l_2 = 0.2; % m

F = @(p)(1-3/4*cos(p(1))^2)*m_1;
G = @(p)(1-3/4*cos(p(2))^2)*m_2;
H = @(p)4/3*(m_k+F(p)+G(p));

% state vector: pos, a, b, dpos, da, db
% parameter vector: a, b, da, db
LPV = {...
  @(p)0 @(p)0 @(p)0 @(p)1 @(p)0 @(p)0 @(p)0;
  @(p)0 @(p)0 @(p)0 @(p)0 @(p)1 @(p)0 @(p)0;
  @(p)0 @(p)0 @(p)0 @(p)0 @(p)0 @(p)1 @(p)0;
  @(p)0 @(p)-m_1*g*sinc(p(1)/pi)*cos(p(1))/H(p)                  @(p)-m_2*g*sinc(p(2)/pi)*cos(p(2))/H(p)                  @(p)0 @(p)4/3*m_1*l_1*p(3)*sin(p(1))/H(p)            @(p)4/3*m_2*l_2*p(4)*sin(p(2))/H(p)            @(p)4/3/H(p);
  @(p)0 @(p)(m_k+m_1+G(p))*g*sinc(p(1)/pi)/l_1/H(p)              @(p)3/4*m_2*g*sinc(p(2)/pi)*cos(p(2))*cos(p(1))/l_1/H(p) @(p)0 @(p)-m_1*p(3)*sin(p(1))*cos(p(1))/H(p)         @(p)-m_2*l_2*p(4)*sin(p(2))*cos(p(1))/l_1/H(p) @(p)-cos(p(1))/l_1/H(p);
  @(p)0 @(p)3/4*m_1*g*sinc(p(1)/pi)*cos(p(1))*cos(p(2))/l_2/H(p) @(p)(m_k+m_2+F(p))*g*sinc(p(2)/pi)/l_2/H(p)              @(p)0 @(p)-m_1*l_1*p(3)*sin(p(1))*cos(p(2))/l_2/H(p) @(p)-m_2*p(4)*sin(p(2))*cos(p(2))/H(p)         @(p)-cos(p(2))/l_2/H(p);
};

%Parameter relation tensor
dep = zeros([size(LPV) 4]);
dep(4,2,:) = [1 1 0 0];
dep(4,3,:) = [1 1 0 0];
dep(4,5,:) = [1 1 1 0];
dep(4,6,:) = [1 1 0 1];
dep(4,7,:) = [1 1 0 0];
dep(5,2,:) = [1 1 0 0];
dep(5,3,:) = [1 1 0 0];
dep(5,5,:) = [1 1 1 0];
dep(5,6,:) = [1 1 0 1];
dep(5,7,:) = [1 1 0 0];
dep(6,2,:) = [1 1 0 0];
dep(6,3,:) = [1 1 0 0];
dep(6,5,:) = [1 1 1 0];
dep(6,6,:) = [1 1 0 1];
dep(6,7,:) = [1 1 0 0];

n = 6;


% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni

%Relationship between FS coefficients

%b(k)=a(k)+a(-k)
%c(k)=j[a(k)-a(-k)]
syms t ;
x=exp(-t);
t0=0;
T=5;
w=2*pi/T;
k=-6:6;
n=1:6 ;
b=(2/T)*int(x*cos(n*w*t),t,t0,t0+T);
b=eval(b)
c=(2/T)*int(x*sin(n*w*t),t,t0,t0+T);
c=eval(c)
a=(1/T)*int(x*exp(-j*k*w*t), t,t0,t0+T);
a=eval(a);
for i=1:6
bb(7-i)=a(14-i)+a(i);
cc(7-i)=j*(a(14-i)-a(i));
end
bb
cc

% a(k)=0.5[b(k)-jc(k)]
an=(1/2)*(b-j*c)
ak(1:6)=a(8:13)


function theta = initializeParameters(hiddenSize, visibleSize)

%% Initialize Parameters Randomly Based on Layer Sizes
r  = sqrt(6) / sqrt(hiddenSize+visibleSize+1);
W1 = rand(hiddenSize, visibleSize) * 2 * r - r;
W2 = rand(visibleSize, hiddenSize) * 2 * r - r;

b1 = zeros(hiddenSize, 1);
b2 = zeros(visibleSize, 1);

%% Compress Parameters into a Single Vector (theta)
theta = [W1(:) ; W2(:) ; b1(:) ; b2(:)];

end


function quadrule_test087 ( )

%*****************************************************************************80
%
%% QUADRULE_TEST087 tests HERMITE_EK_COMPUTE.
%
%  Discussion:
%
%    I used this test to generate tabular values of weights and
%    abscissas for Gauss-Hermite quadrature.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2011
%
%  Author:
%
%    John Burkardt
%
  n = 31;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUADRULE_TEST087\n' );
  fprintf ( 1, '  HERMITE_EK_COMPUTE computes Gauss-Hermite data;\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Compute the data for N = %d\n', n );

  [ x, w ] = hermite_ek_compute ( n );

  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '    x(%d) = %24.16e;\n', i, x(i) );
  end
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '    w(%d) = %24.16e;\n', i, w(i) );
  end

  return
end


function [t,r] = db_index(D, cl, C, p, q)

% DB_INDEX Davies-Bouldin clustering evaluation index.
%
% [t,r] = db_index(D, cl, C, p, q)
%
%  Input and output arguments ([]'s are optional):
%    D     (matrix) data (n x dim)
%          (struct) map or data struct
%    cl    (vector) cluster numbers corresponding to data samples (n x 1)
%    [C]   (matrix) prototype vectors (c x dim) (default = cluster means)
%    [p]   (scalar) norm used in the computation (default == 2)
%    [q]   (scalar) moment used to calculate cluster dispersions (default = 2)
%
%    t     (scalar) Davies-Bouldin index for the clustering (=mean(r))
%    r     (vector) maximum DB index for each cluster (size c x 1)
%
% See also  KMEANS, KMEANS_CLUSTERS, SOM_GAPINDEX.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% input arguments

if isstruct(D),
    switch D.type,
    case 'som_map', D = D.codebook;
    case 'som_data', D = D.data;
    end
end

% cluster centroids
[~, dim] = size(D);
u = unique(cl);
c = length(u);
if nargin <3,
  C = zeros(c,dim);
  for i=1:c,
      me = nanstats(D(cl==u(i),:));
      C(i,:) = me';
  end
end

u2i = zeros(max(u),1); u2i(u) = 1:c;
D = som_fillnans(D,C,u2i(cl)); % replace NaN's with cluster centroid values

if nargin <4, p = 2; end % euclidian distance between cluster centers
if nargin <5, q = 2; end % dispersion = standard deviation

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% action

% dispersion in each cluster
S = zeros(1, c);
for i = 1:c
  ind = find(cl==u(i)); % points in this cluster
  l   = length(ind);
  if l > 0
    S(i) = (mean(sqrt(sum((D(ind,:) - ones(l,1) * C(i,:)).^2,2)).^q))^(1/q);
  else
    S(i) = NaN;
  end
end

% distances between clusters
%for i = 1:c
%  for j = i+1:c
%    M(i,j) = sum(abs(C(i,:) - C(j,:)).^p)^(1/p);
%  end
%end
M = som_mdist(C,p);

% Davies-Bouldin index
R = NaN * zeros(c);
r = NaN * zeros(c,1);
for i = 1:c
  for j = i+1:c
    R(i,j) = (S(i) + S(j))/M(i,j);
  end
  r(i) = max(R(i,:));
end

t = mean(r(isfinite(r)));

return;


function [ uout, vout ] = triasimp ( x, y )

%*****************************************************************************80
%
%% TRIASIMP maps a point from the reference triangle to the simplex.
%
%  Discussion:
%
%    Map the reference triangle with vertices
%      (-1,-1/sqrt(3)), (1,-1/sqrt(3)), (0,2/sqrt(3))
%    to the simplex with vertices
%      (0,0), (1,0), (0,1).
%
%  Licensing:
%
%    This code is distributed under the GNU GPL license.
%
%  Modified:
%
%    26 June 2014
%
%  Author:
%
%    Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.
%    This MATLAB version by John Burkardt.
%
%  Reference:
%
%    Hong Xiao, Zydrunas Gimbutas,
%    A numerical algorithm for the construction of efficient quadrature
%    rules in two and higher dimensions,
%    Computers and Mathematics with Applications,
%    Volume 59, 2010, pages 663-676.
%
%  Parameters:
%
%    Input, real X, Y, the coordinates of a point in the
%    reference triangle.
%
%    Output, real UOUT, VOUT, the coordinates of the corresponding
%    point in the simplex.
%
  scale = 1.0 / sqrt ( 3.0 );

  uout = 0.5 * ( x + 1.0 ) - 0.5 * scale * ( y + scale );

  vout = 1.0 * scale * ( y + scale );

  return
end


function y = gsp_norm_tik(G,x)
%GSP_NORM_TIK Squared L2 norm of the gradient on graph
%   Usage:  y = gsp_norm_tv(G,x);
%
%   Input parameters:
%         G     : Graph structure (or symetric positive matrix)
%         x     : Signal on graph
%   Output parameters:
%         y     : Norm
%
%   Compute the squared L2 norm of the gradient on graph. If x is a matrix
%   a vector of norm is returned.
%
%   This function can also be used for general symetric positive matrices
%
%   See also: gsp_prox_tik gsp_norm_tv

% Author: Nathanael Perraudin
% Date:   25 March 2014

if isa(x,'single')
   x = double(x);
end

if ~isnumeric(G)
    L = G.L;
else
    L = G;
end

[N,M ] = size(L);
if size(x,1) ~= M
    error('The dimension of x is not compatible with the dimension of L');
end
NL = M/N;
y = 0;
for ii = 1:NL;
    ind = (1:N)+(ii-1)*N;
    y = y + sum(x(ind,:) .* (L(:,ind)* x(ind,:)) );
end

% Previous implementation
% y = sum(x .* (L* x) );

end


function [ o, x, w ] = en_r2_05_2 ( n )

%*****************************************************************************80
%
%% EN_R2_05_2 implements the Stroud rule 5.2 for region EN_R2.
%
%  Discussion:
%
%    The rule has order O = 2 * N^2 + 1.
%
%    The rule has precision P = 5.
%
%    EN_R2 is the entire N-dimensional space with weight function
%
%      w(x) = exp ( - x1^2 - x2^2 ... - xn^2 )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 January 2010
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Arthur Stroud,
%    Approximate Calculation of Multiple Integrals,
%    Prentice Hall, 1971,
%    ISBN: 0130438936,
%    LC: QA311.S85.
%
%  Parameters:
%
%    Input, integer N, the spatial dimension.
%
%    Output, integer O, the order.
%
%    Output, real X(N,O), the abscissas.
%
%    Output, real W(O), the weights.
%
  o = 2 * n * n + 1;
  volume = sqrt ( pi^n );

  a = 2 * volume / ( n + 2 );
  b = ( 4 - n ) * volume / 2 / ( n + 2 )^2;
  c = volume / ( n + 2 )^2;

  r = sqrt ( ( n + 2 ) / 2 );
  s = sqrt ( ( n + 2 ) / 4 );

  x = zeros ( n, o );
  w = zeros ( o, 1 );

  k = 0;
%
%  1 point.
%
  k = k + 1;
% x(1:n,k) = 0;
  w(k) = a;
%
%  2 * N points.
%
  for i = 1 : n
    k = k + 1;
    x(i,k) = - r;
    w(k) = b;
    k = k + 1;
    x(i,k) = + r;
    w(k) = b;
  end
%
%  4 * ( N * ( N - 1 ) / 2 ) points.
%
  for i = 1 : n - 1
    for j = i + 1 : n
      k = k + 1;
      x(i,k) = - s;
      x(j,k) = - s;
      w(k) = c;
      k = k + 1;
      x(i,k) = - s;
      x(j,k) = + s;
      w(k) = c;
      k = k + 1;
      x(i,k) = + s;
      x(j,k) = - s;
      w(k) = c;
      k = k + 1;
      x(i,k) = + s;
      x(j,k) = + s;
      w(k) = c;
    end
  end

  return
end


function geometry_test192 ( )

%*****************************************************************************80
%
%% TEST192 tests SPHERE_UNIT_SAMPLE_3D_2.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
  dim_num = 3;

  n_sample = 1000;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST192\n' );
  fprintf ( 1, '  For the unit sphere in 3 dimensions:\n' );
  fprintf ( 1, '  SPHERE_UNIT_SAMPLE_3D_2 samples;\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  A few sample values: \n' );
  fprintf ( 1, '\n' );

  for i = 1 : 5
    [ x, seed ] = sphere_unit_sample_3d_2 ( seed );
    fprintf ( 1, '  %10f  %10f  %10f\n', x(1:dim_num) );
  end

  average(1:dim_num) = 0.0;

  for i = 1 : n_sample
    [ x, seed ] = sphere_unit_sample_3d_2 ( seed );
    average(1:dim_num) = average(1:dim_num) + x(1:dim_num);
  end

  average(1:dim_num) = average(1:dim_num) / n_sample;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Now average the points, which should get a value\n' );
  fprintf ( 1, '  close to zero, and closer as N_SAMPLE increases.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average:        %10f  %10f  %10f\n', average(1:dim_num) );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Now choose a random direction, sample the same\n' );
  fprintf ( 1, '  number of points, and compute the dot product with\n' );
  fprintf ( 1, '  the direction.\n' );
  fprintf ( 1, '  Take the absolute value of each dot product \n' );
  fprintf ( 1, '  and sum and average.\n' );

  for j = 1 : 5

    [ v, seed ] = sphere_unit_sample_3d_2 ( seed );

    dot_average = 0.0;

    for i = 1 : n_sample
      [ x, seed ] = sphere_unit_sample_3d_2 ( seed );
      dot_average = dot_average + abs ( x(1:dim_num) * v(1:dim_num)' );
    end

    dot_average = dot_average / n_sample;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  V:                %10f  %10f  %10f\n', v(1:dim_num) );
    fprintf ( 1, '  Average |(XdotV)| %10f\n', dot_average );

  end

  return
end


function f = p04_f ( n, x )

%*****************************************************************************80
%
%% P04_F returns the integrand for problem 4.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of variables.
%
%    Input, real X(N), the arguments.
%
%    Output, real F(N), the values of the integrand.
%
  f = 0.75 * x + 1.25 * sin ( 3.0 * pi * x + 0.4 );

  return
end


% % Search the elements that are lying within a specified interval.
% % Search the indexes of all elements in x (sorted vector of n elements) that
% % lie within the interval.
% % The algorithm uses binary searches, thus it runs in log(n)
% %
% % INPUT:
% % x: vector of numeric values sorted in ascending order
% %    (e.g. 2,7,20,...120)
% % ref: numeric value of the reference point (center of the interval)
% % tol: numeric value corresponding to 1/2 of the width of the interval
% % The fourth input argument: numeric value (optional). Allows to define the maximum
% % number of elements of x that can lie within the specified interval. This is useful
% % in order to speed up the search.
% %
% % OUTPUT:
% % indexes: indexes of elements of x which lie within the interval
% % [ref-tol ref+tol]
% % If ref is not found in x then indexes is empty.
% %
% % Revisions:
% % 14-jun-2010: - Added lines 38-55 in order to consider the case in which lower bound
% %                is less than the minimum value of x or the upper bound is more than
% %                the max value of x
% %              - Reinforced the conditions in line 93 and in line 117 in order to avoid
% %                an error when (to-1)==0 or (from+1)>length(x)
% % 15/apr/2011: - A bug with uint values of input array has been fixed.
% %                Thanks to Igor Varfolomeev

% % % --------------------------------
% % % Author: Dr. Roberto Olmi
% % % Email : robertoolmi at gmail.com
% % % --------------------------------

function indexes = BinaryIntervalSearch(x,ref,tol,varargin)
lbound = ref-tol;
ubound = ref+tol;
from=1;
to=length(x);

if lbound <= x(1)
    if ubound < x(1)
        indexes=[];
        return
    end
    lindex=1;
else
    lindex=0;
end
if ubound >= x(end)
    if lbound > x(end)
        indexes=[];
        return
    end
    uindex=length(x);
else
    uindex=0;
end

go=uindex==0 || lindex==0;
while go
    mid = ceil(from+(to-from)/2);
    %diff = x(mid)-ref;  15/apr/2011
    if x(mid) < ref %diff < 0  15/apr/2011
        if x(mid) >= lbound
            go=false;
        else
            from=mid+1;
            if x(from) >= lbound
                lindex=from;
                go=false;
            end
        end
    else       % x(mid) > ref
        if x(mid) <= ubound
            go=false;
        else
            to=mid-1;
            if x(to) <= ubound
                uindex=to;
                go=false;
            end
        end
    end
end

%remove this if at least one element of x is always in the interval:
if (lindex > 0 && x(lindex) > ubound)...
        || (uindex > 0 && x(uindex) < lbound)
    indexes=[];
    return
end

%search upper index
cfrom=from;
if from==length(x) || x(from+1) > ubound
    uindex=from;
end
if nargin == 4
    to=min([to mid+varargin{1}]);
end
while uindex == 0
    mid = ceil(from+(to-from)/2);
    if x(mid) <= ubound
        from=mid+1;
        if x(from) > ubound
            uindex=mid;
        end
    else
        to=mid-1;
        if x(to) < ubound
            uindex=to;
        end
    end
end

%search lower index
from=cfrom;
to=uindex;
if to==1 || x(to-1) < lbound
    lindex=to;
end
if nargin == 4
    from=max([from uindex-varargin{1}]);
end
while lindex == 0
    mid = ceil(from+(to-from)/2);
    if x(mid) < lbound
        from=mid+1;
        if x(from) > lbound
            lindex=from;
        end
    else
        to=mid-1;
        if x(to) < lbound
            lindex=mid;
        end
    end
end

indexes=lindex:uindex;

% % --------------------------------------------
% % Example code for Testing
% % tol=2;
% % ref=12;
% % maxi=10000;
% % numel=1000;
% % for i=1:maxi
% %     x = sort(randint(1,numel,[0,400]));
% %     indexes = BinaryIntervalSearch(x,ref,tol);
% %     if isempty (indexes)
% %         if any(abs(x-ref) < tol)
% %             disp('Doh!')
% %             break
% %         else
% %             continue
% %         end
% %     end
% %     if indexes(1)>1 && ~(x(indexes(1)-1) < x(indexes(1)))...
% %             || indexes(end)<numel && ~(x(indexes(end)) < x(indexes(end)+1))...
% %             || any(abs(x(indexes)-ref) > tol)
% %         disp('Doh!')
% %         break
% %     end
% %     if i==maxi
% %         disp('OK!!!')
% %     end
% % end
% % --------------------------------------------

% % % --------------------------------
% % % Author: Dr. Roberto Olmi
% % % Email : robertoolmi at gmail.com
% % % --------------------------------


function output = minmod(a,b)
% minmod is the minmod function in (2.9b) in the paper
% m(a,b) = minmod(a,b) = (\frac{sgn(a)+sgn(b)}{2}) min(|a|,|b|)

output = (sign(a) + sign(b)) / 2 * min(abs(a), abs(b));

github-repos/MATLAB/YimianDai-Image-Processing-Codes-for-Easier-Understanding/Image-Processing-Codes-for-Easier-Understanding-874302799e48852624bc3760b58b46bd9360f238/src/(Physica D 1992) Nonlinear Total Variation based noise removal algorithms/version_1/support/minmod.m


function [node,face,elem]=meshunitsphere(tsize,maxvol)
%
% [node,face,elem]=meshunitsphere(tsize,maxvol)
%
% create the surface and/or volumetric mesh of a unit sphere
% centered at [0 0 0] and radius 1
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% input:
%   tsize: maximum size of the surface triangles (from 0 to 1)
%   maxvol: maximum volume of the tetrahedron; if one wants to return
%           elem without specifying maxvol, maxvol=tsize^3
%
% output:
%   node: node coordinates, 3 columns for x, y and z respectively
%   face: integer array with dimensions of NB x 3, each row represents
%         a surface mesh face element
%   elem: integer array with dimensions of NE x 4, each row represents
%         a tetrahedron. If ignored, this function only produces the surface
%
% example:
%   [node,face]=meshunitsphere(0.05);
%   [node,face,elem]=meshunitsphere(0.05,0.01);
%   plotmesh(node,elem,'x>0'); axis equal;
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

dim=60;
esize=tsize*dim;
thresh=dim/2-1;
[xi,yi,zi]=meshgrid(0:0.5:dim,0:0.5:dim,0:0.5:dim);
dist=thresh-sqrt((xi-30).^2+(yi-30).^2+(zi-30).^2);
dist(find(dist<0))=0;
clear xi yi zi;

% extract a level-set at v=thresh, being a sphere with R=thresh
% the maximum element size of the surface triangles is tsize*dim

[node,face]=vol2restrictedtri(dist,1,[dim dim dim],dim*dim*dim,30,esize,esize,40000);
node=(node-0.5)*0.5;

[node,face]=removeisolatednode(node,face);

node=(node-30)/28;
r0=sqrt(sum((node.*node)'));
node=node.*repmat(1./r0(:),1,3);

if(nargout==3)
   if(nargin==1) maxvol=tsize*tsize*tsize; end
   [node,elem,face]=surf2mesh(node,face,[-1 -1 -1]*1.1,[1 1 1]*1.1,1,maxvol,[],[]);
   elem=elem(:,1:4);
end
face=face(:,1:3);


function a = moler4 ( )

%*****************************************************************************80
%
%% MOLER4 returns the MOLER4 matrix.
%
%  Example:
%
%    0  2  0 -1
%    1  0  0  0
%    0  1  0  0
%    0  0  1  0
%
%  Properties:
%
%    A is integral, therefore det ( A ) is integral, and
%    det ( A ) * inverse ( A ) is integral.
%
%    A is the companion matrix of the polynomial X^4-2X^2+1=0.
%
%    A has eigenvalues -1, -1, +1, +1.
%
%    A can cause problems to a standard QR algorithm, which
%    can fail to converge.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 February 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A(4,4), the matrix.
%

%
%  Note that matrix entries are listed by row.
%
  a = [ ...
    0.0,  2.0,  0.0, -1.0; ...
    1.0,  0.0,  0.0,  0.0; ...
    0.0,  1.0,  0.0,  0.0; ...
    0.0,  0.0,  1.0,  0.0 ];

  return
end%