function fem1d_bvp_linear_test09 ( )

%*****************************************************************************80
%
%% FEM1D_BVP_LINEAR_TEST09 carries out test case #9.
%
%  Location:
%
%    http://people.sc.fsu.edu/~jburkardt/m_src/fem1d_bvp_linear/fem1d_bvp_linear_test09.m
%
%  Discussion:
%
%    Use A9, C9, F9, EXACT9, EXACT_UX9.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Dianne O'Leary,
%    Scientific Computing with Case Studies,
%    SIAM, 2008,
%    ISBN13: 978-0-898716-66-5,
%    LC: QA401.O44.
%
  n = 11;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'FEM1D_BVP_LINEAR_TEST09\n' );
  fprintf ( 1, '  Solve -( A(x) U''(x) )'' + C(x) U(x) = F(x)\n' );
  fprintf ( 1, '  for 0 < x < 1, with U(0) = U(1) = 0.\n' );
  fprintf ( 1, '  A9(X)  = 1.0\n' );
  fprintf ( 1, '  C9(X)  = 0.0\n' );
  fprintf ( 1, '  F9(X)  = X * ( X + 3 ) * exp ( X ),   X <= 2/3\n' );
  fprintf ( 1, '         = 2 * exp ( 2/3),                   2/3 < X\n' );
  fprintf ( 1, '  U9(X)  = X * ( 1 - X ) * exp ( X ),   X <= 2/3\n' );
  fprintf ( 1, '         = X * ( 1 - X ),                    2/3 < X\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of nodes = %d\n', n );
%
%  Geometry definitions.
%
  x_first = 0.0;
  x_last = 1.0;
  x = linspace ( x_first, x_last, n );
  x = x(:);

  u = fem1d_bvp_linear ( n, @a9, @c9, @f9, x );

  uexact = exact9 ( x );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     I    X         U         Uexact    Error\n' );
  fprintf ( 1, '\n' );

  for i = 1 : n
    fprintf ( 1, '  %4d  %8f  %8f  %8f  %8e\n', ...
      i, x(i), u(i), uexact(i), abs ( u(i) - uexact(i) ) );
  end

  e1 = l1_error ( n, x, u, @exact9 );
  e2 = l2_error_linear ( n, x, u, @exact9 );
  h1s = h1s_error_linear ( n, x, u, @exact_ux9 );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  l1 norm of error  = %g\n', e1 );
  fprintf ( 1, '  L2 norm of error  = %g\n', e2 );
  fprintf ( 1, '  Seminorm of error = %g\n', h1s  );

  return
end
function value = a9 ( x )

%*****************************************************************************80
%
%% A9 evaluates A function #9.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the evaluation point.
%
%    Output, real VALUE, the value of A(X).
%
  value = 1.0;

  return
end
function value = c9 ( x )

%*****************************************************************************80
%
%% C9 evaluates C function #9.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the evaluation point.
%
%    Output, real VALUE, the value of C(X).
%
  value = 0.0;

  return
end
function value = exact9 ( x )

%*****************************************************************************80
%
%% EXACT9 evaluates exact solution #9.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the evaluation point.
%
%    Output, real VALUE, the value of U(X).
%
  value = x .* ( 1.0 - x ) .* exp ( x )         .* ( x <= 2.0 / 3.0 ) ...
        + x .* ( 1.0 - x )                      .* ( 2.0 / 3.0 < x );

  return
end
function value = exact_ux9 ( x )

%*****************************************************************************80
%
%% EXACT_UX9 evaluates the derivative of exact solution #9.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the evaluation point.
%
%    Output, real VALUE, the value of dUdX(X).
%
  value = ( 1.0 - x - x .* x ) .* exp ( x )         .* ( x <= 2.0 / 3.0 ) ...
        + ( 1.0 - 2.0 * x )                         .* (      2.0 / 3.0 < x );

  return
end
function value = f9 ( x )

%*****************************************************************************80
%
%% F9 evaluates right hand side function #9.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the evaluation point.
%
%    Output, real VALUE, the value of F(X).
%
  value = x .* ( x + 3.0 ) .* exp ( x )         .* ( x <= 2.0 / 3.0 ) ...
        +               2.0                     .* (      2.0 / 3.0 < x );

  return
end


function jed = ymd_to_jed_common ( y, m, d )

%*****************************************************************************80
%
%% YMD_TO_JED_COMMON converts a Common YMD date to a JED.
%
%  Discussion:
%
%    The "common" calendar is meant to be the calendar which is Julian up to
%    day JED = 2299160, and Gregorian from day JED = 2299161 and after.
%
%    The Julian Ephemeris Date is essentially a count of the number
%    of days that have elapsed since noon, 1 January 4713 BC, at
%    Greenwich, England.  Strictly speaking, the Julian Ephemeris Date
%    is counted from noon, and thus day "0" began at noon on 1 January 4713 BC,
%    and ended at noon on 2 January 4713 BC.
%
%    The Julian Ephemeris Date was devised by Joseph Scaliger in 1583.
%
%    The Julian Ephemeris Date has been adopted by astronomers as
%    a convenient reference for dates.
%
%  Example:
%
%       Y   M     D         JED
%    --------------     -------
%    BC 4713 Jan  1           0
%    AD 1968 May 23     2440000
%    AD 1984 Dec 31     2446065
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 October 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, the YMD date.
%
%    Output, real JED, the Julian Ephemeris Date.
%

%
%  Copy the month and year.
%
  y2 = 1582;
  m2 = 10;
  d2 = 4+1;

  cmp = ymd_compare ( y, m, d, y2, m2, d2 );

  if ( cmp == '<' )
    jed = ymd_to_jed_julian ( y, m, d );
    return
  end
%
%  Use the Gregorian calendar for dates strictly after 1752/9/13.
%
  y2 = 1582;
  m2 = 10;
  d2 = 15-1;

  cmp = ymd_compare ( y, m, d, y2, m2, d2 );

  if ( cmp == '>' )
    jed = ymd_to_jed_gregorian ( y, m, d );
    return
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'YMD_TO_JED_COMMON - Fatal error!\n' );
  fprintf ( 1, '  Illegal date!\n' );
  error ( 'YMD_TO_JED_COMMON - Fatal error!' );

  return
end


function [snr_mean, segsnr_mean]= comp_SNR(cleanFile, enhdFile);
%
%   Segmental Signal-to-Noise Ratio Objective Speech Quality Measure
%
%     This function implements the segmental signal-to-noise ratio
%     as defined in [1, p. 45] (see Equation 2.12).
%
%   Usage:  [SNRovl, SNRseg]=comp_snr(cleanFile.wav, enhancedFile.wav)
%
%         cleanFile.wav - clean input file in .wav format
%         enhancedFile  - enhanced output file in .wav format
%         SNRovl        - overall SNR (dB)
%         SNRseg        - segmental SNR (dB)
%
%     This function returns 2 parameters.  The first item is the
%     overall SNR for the two speech signals.  The second value
%     is the segmental signal-to-noise ratio (1 seg-snr per
%     frame of input).  The segmental SNR is clamped to range
%     between 35dB and -10dB (see suggestions in [2]).
%
%   Example call:  [SNRovl,SNRseg]=comp_SNR('sp04.wav','enhanced.wav')
%
%  References:
%
%     [1] S. R. Quackenbush, T. P. Barnwell, and M. A. Clements,
%	    Objective Measures of Speech Quality.  Prentice Hall
%	    Advanced Reference Series, Englewood Cliffs, NJ, 1988,
%	    ISBN: 0-13-629056-6.
%
%     [2] P. E. Papamichalis, Practical Approaches to Speech
%	    Coding, Prentice-Hall, Englewood Cliffs, NJ, 1987.
%	    ISBN: 0-13-689019-9. (see pages 179-181).
%
%  Authors: Bryan L. Pellom and John H. L. Hansen (July 1998)
%  Modified by: Philipos C. Loizou  (Oct 2006)
%
% Copyright (c) 2006 by Philipos C. Loizou
% $Revision: 0.0 $  $Date: 10/09/2006 $
%-------------------------------------------------------------------------

if nargin ~=2
    fprintf('USAGE: [snr_mean, segsnr_mean]= comp_SNR(cleanFile, enhdFile) \n');
    return;
end

[data1, Srate1, Nbits1]= wavread(cleanFile);
[data2, Srate2, Nbits2]= wavread(enhdFile);
if (( Srate1~= Srate2) | ( Nbits1~= Nbits2))
    error( 'The two files do not match!\n');
end

len= min( length( data1), length( data2));
data1= data1( 1: len);
data2= data2( 1: len);

[snr_dist, segsnr_dist]= snr( data1, data2,Srate1);

snr_mean= snr_dist;
segsnr_mean= mean( segsnr_dist);

% =========================================================================
function [overall_snr, segmental_snr] = snr(clean_speech, processed_speech,sample_rate)

% ----------------------------------------------------------------------
% Check the length of the clean and processed speech.  Must be the same.
% ----------------------------------------------------------------------

clean_length      = length(clean_speech);
processed_length  = length(processed_speech);

if (clean_length ~= processed_length)
  disp('Error: Both Speech Files must be same length.');
  return
end

% ----------------------------------------------------------------------
% Scale both clean speech and processed speech to have same dynamic
% range.  Also remove DC component from each signal
% ----------------------------------------------------------------------

%clean_speech     = clean_speech     - mean(clean_speech);
%processed_speech = processed_speech - mean(processed_speech);

%processed_speech = processed_speech.*(max(abs(clean_speech))/ max(abs(processed_speech)));

overall_snr = 10* log10( sum(clean_speech.^2)/sum((clean_speech-processed_speech).^2));

% ----------------------------------------------------------------------
% Global Variables
% ----------------------------------------------------------------------

winlength   = round(30*sample_rate/1000); %240;		   % window length in samples for 30-msecs
skiprate    = floor(winlength/4); %60;		   % window skip in samples
MIN_SNR     = -10;		   % minimum SNR in dB
MAX_SNR     =  35;		   % maximum SNR in dB

% ----------------------------------------------------------------------
% For each frame of input speech, calculate the Segmental SNR
% ----------------------------------------------------------------------

num_frames = clean_length/skiprate-(winlength/skiprate); % number of frames
start      = 1;					% starting sample
window     = 0.5*(1 - cos(2*pi*(1:winlength)'/(winlength+1)));

for frame_count = 1: num_frames

   % ----------------------------------------------------------
   % (1) Get the Frames for the test and reference speech.
   %     Multiply by Hanning Window.
   % ----------------------------------------------------------

   clean_frame = clean_speech(start:start+winlength-1);
   processed_frame = processed_speech(start:start+winlength-1);
   clean_frame = clean_frame.*window;
   processed_frame = processed_frame.*window;

   % ----------------------------------------------------------
   % (2) Compute the Segmental SNR
   % ----------------------------------------------------------

   signal_energy = sum(clean_frame.^2);
   noise_energy  = sum((clean_frame-processed_frame).^2);
   segmental_snr(frame_count) = 10*log10(signal_energy/(noise_energy+eps)+eps);
   segmental_snr(frame_count) = max(segmental_snr(frame_count),MIN_SNR);
   segmental_snr(frame_count) = min(segmental_snr(frame_count),MAX_SNR);

   start = start + skiprate;

end


function bic = ml_bic(ll,num_para,num_data)
%ML_BIC  Bayesian information criterion
%
%   input -----------------------------------------------------------------
%
%       o ll        : (1 x 1), log-likelihood.
%
%       o num_para  : (1 x 1), number of parameters.
%
%       o num_data  : (1 x 1), number of datapoints.
%
%   output ----------------------------------------------------------------
%
%       o bic       : (1 x 1)

 bic =  -2 * ll + num_para * log(num_data);

end


function z = lambda_sum_largest( Y, k )

% LAMBDA_SUM_SMALLEST    Sum of the k smallest eigenvalues of a symmetric matrix.
%     For square matrix X, LAMBDA_SUM_LARGEST(X,K) is SUM_LARGEST(EIG(X),k)
%     if X is Hermitian or symmetric and real; and +Inf otherwise.
%
%     An error results if X is not a square matrix.
%
%     Disciplined convex programming information:
%         LAMBDA_SUM_LARGEST is convex and nonmonotonic (at least with
%         respect to elementwise comparison), so its argument must be affine.

error( nargchk( 2, 2, nargin ) );
if ndims( Y ) > 2 || size( Y, 1 ) ~= size( Y, 2 ),
    error( 'First input must be a square matrix.' );
elseif ~isnumeric( k ) || numel( k ) ~= 1 || ~isreal( k ),
    error( 'Second input must be a real scalar.' );
end
err = Y - Y';
Y   = 0.5 * ( Y + Y' );
if norm( err, 'fro' )  > 8 * eps * norm( Y, 'fro' ),
    z = Inf;
else
    z = sum_largest( eig( full( Y ) ), k );
end

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


function [kg] = amu2kg(amu)
% Convert mass from atomic mass units to kilograms.
% Chad Greene 2012
kg = amu*1.6605402e-27;


function [AlgOption,TSP] = InterfaceMMAS(TSPfile,AntNum,alpha,beta,rho,MaxITime)
%:Get the input parameters for MMAS
%Read in tsp data
[Dimension,Nodes,Weights,Name] = GetTSPData(TSPfile);
fprintf('Data of problem-%s have been read in!\n',Name);
%Set TSP datas
TSP = InitProblem(Dimension,Nodes,Weights,Name);
%Set parameters for MMAS algorithm
AlgOption = InitParameter(Dimension,AntNum,alpha,beta,rho,MaxITime);
% AlgOption = InitParameter(Dimension,Dimension,alpha,beta,rho,MaxITime);

%% --------------------------------------------------------------
function AlgorithmParas = InitParameter(Dimension,AntNum,alpha,beta,rho,MaxITime)
AlgorithmParas.n = Dimension; % nodes number in TSP
AlgorithmParas.m = AntNum; % ants number
AlgorithmParas.alpha = alpha; % pheromeno exponential
AlgorithmParas.beta = beta; % heuristic exponential
AlgorithmParas.rho = rho; % vapor parameter
AlgorithmParas.MaxITime = MaxITime; % Maximum Iterative Time
AlgorithmParas.delta = 0.05; % Parameter of Pheromone Trail Smoothing(PTS): (0,1) Turn Off By Setting 0
AlgorithmParas.lambda = 0; % coefficient of Average Node Branching: (0,1) Turn Off By Setting 0
AlgorithmParas.ANBmin = 2; % coefficient of minimum ANB
AlgorithmParas.DispInterval = 5; % Display Interval: Turn Off Display By Setting 0
AlgorithmParas.ReStartCount = 50; % Restart while no improvment for 50 iterations
%% --------------------------------------------------------------
function Problem = InitProblem(Dimension,Nodes,NodeWeight,Name)
n = Dimension;
MatrixTau = ones(n,n)-eye(n,n);
Problem.nodes = Nodes;
Problem.weights = NodeWeight;
Problem.tau = MatrixTau;
Problem.name = Name;


function [elem,HB] = uniformcoarsenquad(elem)
%% UNIFORMCOARSENQUAD uniform coarsening of uniform quad mesh
%
% [elem,HB] = UNIFORMCOARSENQUAD(elem) remove grid points added by uniform
% refinement. See the illustration below:
%
%
%   See also: uniformcoarsen, coarsen, bisect, uniformcoarsen3, mg
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

NT = size(elem,1);
N = max(elem(:));
d = size(elem,2);
if d == 3  % triangulation
    NT = NT/2;
end
HB = [];

%% Find ni and nj
b = N - NT + 1;
c = N;
delta = sqrt(b^2-4*c);
ni = (b+delta)/2;
nj = (b-delta)/2;
if ~isequal(mod(ni+1,2),0) || ~isequal(mod(nj+1,2),0)
    display('Not from refinement of uniform quad mesh');
    return
end
if d == 3 % triangulation
    if ~isequal(elem(1,1),ni+1)
        nj = ni;
        ni = elem(1,1) - elem(1,2);
    end
elseif d == 4
    if ~isequal(elem(1,2),ni+1)
        nj = ni;
        ni = elem(1,2) - elem(1,1);
    end
end

%% Coarse grids
nic = (ni+1)/2;
njc = (nj+1)/2;
Nc = nic*njc;
nodecidx = reshape(1:Nc,nic,njc);
t2nidxMap = nodecidx(1:nic-1,1:njc-1);
k = t2nidxMap(:);
elem = [k k+nic k+nic+1 k+1];

%% Record HB
HB = zeros(N,3);
nodeidx = reshape(1:N,ni,nj);
% fine nodes on vertical lines
i = 2:2:ni-1;
j = 1:2:nj;
k = nodeidx(i,j);
HB(k,1) = k(:);
HB(k,2) = k(:) - 1;
HB(k,3) = k(:) + 1;
% fine nodes on horizontal lines
i = 1:2:ni;
j = 2:2:nj-1;
k = nodeidx(i,j);
HB(k,1) = k(:);
HB(k,2) = k(:) - ni;
HB(k,3) = k(:) + ni;
% fine nodes in the center
i = 2:2:ni-1;
j = 2:2:nj-1;
k = nodeidx(i,j);
HB(k,1) = k(:);
HB(k,2) = k(:) - ni-1;
HB(k,3) = k(:) + ni+1;
HB(HB(:,2) == 0,:) = [];
% shift the index into coarse grid
i = 1:2:ni;
j = 1:2:nj;
k = nodeidx(i,j);
indexMap = zeros(N,1);
indexMap(k(:)) = 1:Nc;
HB(:,2:3) = indexMap(HB(:,2:3));


function comp_enum_test ( )

%*****************************************************************************80
%
%% COMP_ENUM_TEST tests COMP_ENUM;
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 October 2014
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'COMP_ENUM_TEST\n' );
  fprintf ( 1, '  COMP_ENUM counts compositions;\n' );
  fprintf ( 1, '\n' );
  for n = 0 : 10
    for k = 1 : 10
      num = comp_enum ( n, k );
      fprintf ( 1, '  %6d', num );
    end
    fprintf ( 1, '\n' );
  end

  return
end


function qr=rotqc2qr(qc)
%ROTQC2QR converts a matrix of complex quaternion row vectors into real form
%
% Inputs:
%
%     QC(2m,n)   mxn matrix of complex-valued quaternions
%
% Outputs:
%
%     QR(4m,n)   mxn matrix of real-valued quaternions
%
% The complex-valued quaternion [r+j*b  a+j*c] becomes [r a b c]

%
%      Copyright (C) Mike Brookes 2000-2006
%      Version: $Id: rotqc2qr.m,v 1.2 2007/11/18 19:38:40 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[m,n]=size(qc);
i=(1:2:2*m)-mod(0:m-1,2);
qr=zeros(2*m,n);
qr(i,:)=real(qc);
qr(i+2,:)=imag(qc);


function Datacube_conved = Convolution(Datacube,W,ConvFilter)
% Given W, performing convolution on Datacube with zero padding

[Width,Height,Channel] = size(Datacube);
num_filters = size(W,2);
Datacube_conved = cell(num_filters,1);
magSize = (ConvFilter.PatchSize-1)/2;
magChannel = (ConvFilter.Channel-1)/2;
Tempcube_conved = zeros(Width+ConvFilter.PatchSize-1, Height+ConvFilter.PatchSize-1, Channel+ConvFilter.Channel-1);
Tempcube_conved((magSize+1):end-magSize,(magSize+1):end-magSize,(magChannel+1):end-magChannel) = Datacube;
X = im2colstep(Tempcube_conved,[ConvFilter.PatchSize,ConvFilter.PatchSize,ConvFilter.Channel]);
mu = mean(X,2);
% mu = mean(X,1);
X = bsxfun(@minus, X, mu);
for i=1:num_filters
    Datacube_conved{i} = reshape(W(:,i)'*X,[Width,Height,Channel]);
end


function colormask = wbmask(m,n,wbmults,align)
% COLORMASK = wbmask(M,N,WBMULTS,ALIGN)
%
% Makes a white-balance multiplicative mask for an image of size m-by-n
% with RGB while balance multipliers WBMULTS = [R_scale G_scale B_scale].
% ALIGN is string indicating Bayer arrangement: 'rggb','gbrg','grbg','bggr'
colormask = wbmults(2)*ones(m,n); %Initialize to all green values
switch align
case 'rggb'
colormask(1:2:end,1:2:end) = wbmults(1); %r
colormask(2:2:end,2:2:end) = wbmults(3); %b
case 'bggr'
colormask(2:2:end,2:2:end) = wbmults(1); %r
colormask(1:2:end,1:2:end) = wbmults(3); %b
case 'grbg'
colormask(1:2:end,2:2:end) = wbmults(1); %r
colormask(2:2:end,1:2:end) = wbmults(3); %b
case 'gbrg'
colormask(2:2:end,1:2:end) = wbmults(1); %r
colormask(1:2:end,2:2:end) = wbmults(3); %b
end
end


function [prob_temp, t_templ,t_temph] = problTemperature(BandBT,idclr,l_pt,h_pt)
%PROBTEMPERATURE calculate temperature probability for land respectively.

    % [Temperature test (over land)]
    F_temp=BandBT(idclr); % get clear temperature
    clear idclr;
    t_buffer=4*100;
    % 0.175 percentile background temperature (low)
    t_templ=prctile(F_temp,100*l_pt);
    % 0.825 percentile background temperature (high)
    t_temph=prctile(F_temp,100*h_pt);
    clear F_temp l_pt h_pt;

    t_tempL=t_templ-t_buffer;
    t_tempH=t_temph+t_buffer;
    clear t_buffer;
    Temp_l=t_tempH-t_tempL;
    clear t_tempL;
    prob_temp=(t_tempH-BandBT)/Temp_l;
    clear BandBT t_tempH Temp_l;
    % Temperature can have prob > 1
    prob_temp(prob_temp<0)=0;
%     prob_temp(prob_temp>1)=1;

end


% nanmean() - Average, not considering NaN values
%
% Usage: same as mean()

% Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002

%123456789012345678901234567890123456789012345678901234567890123456789012

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: nanmean.m 2885 2011-02-16 09:41:58Z roboos $

function out = nanmean(in, dim)

if nargin < 1
    help nanmean;
    return;
end;
if nargin < 2
    if size(in,1) ~= 1
        dim = 1;
    elseif size(in,2) ~= 1
        dim = 2;
    else
        dim = 3;
    end;
end;
tmpin = in;
tmpin(find(isnan(in(:)))) = 0;
out = sum(tmpin, dim) ./ sum(~isnan(in),dim);


function value = f2 ( x )
  value = cos ( 3 * pi * x );
  return
end


function i4_factorial_test ( )

%*****************************************************************************80
%
%% I4_FACTORIAL_TEST tests I4_FACTORIAL.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2008
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4_FACTORIAL_TEST:\n' );
  fprintf ( 1, '  I4_FACTORIAL evaluates the factorial function.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     X       Exact F       I4_FACTORIAL(X)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, n, fn ] = i4_factorial_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fn2 = i4_factorial ( n );

    fprintf ( 1, '  %2d  %10d  %10d\n', n, fn, fn2 );

  end

  return
end


function [A0, C0] = calc_dc_components(ai)

% Calculate DC components.
% A0 and C0 are bias coefficeis, corresponding to a frequency of zero.

    %% Maximum length of chain code
    k = size(ai, 2);

    %% Traversal time and distance
    t = calc_traversal_time(ai);
    s = calc_traversal_dist(ai);

    %% Basic period of the chain code
    T = t(k);

    %% DC Components: A0, C0
    sum_a0 = 0;
    sum_c0 = 0;

    for p = 1 : k

        delta_d = calc_traversal_dist(ai(p));
        delta_x = delta_d(:,1);

        delta_y = delta_d(:,2);
        delta_t = calc_traversal_time(ai(p));

        if (p > 2)
                zeta = s(p - 1, 1) - delta_x / delta_t * t(p - 1);
                delta = s(p - 1, 2) - delta_y / delta_t * t(p - 1);
        else
                zeta = 0;
                delta = 0;
        end

        if (p > 2)
            sum_a0 = sum_a0 + delta_x / (2 * delta_t) * ((t(p))^2 - (t(p - 1))^2) + zeta * (t(p) - t(p-1));
            sum_c0 = sum_c0 + delta_y / (2 * delta_t) * ((t(p))^2 - (t(p - 1))^2) + delta * (t(p) - t(p-1));
        else
            sum_a0 = sum_a0 + delta_x / (2 * delta_t) * (t(p))^2 + zeta * t(p);
            sum_c0 = sum_c0 + delta_y / (2 * delta_t) * (t(p))^2 + delta * t(p);
        end

    end

    %% Assign  to output
    A0 = sum_a0 / T;
    C0 = sum_c0 / T;
end


function [result, t] = linfactor (arg1, arg2)
%LINFACTOR factorize a matrix, or use the factors to solve Ax=b.
% Uses LU or CHOL to factorize A, or uses a previously computed factorization to
% solve a linear system.  This function automatically selects an LU or Cholesky
% factorization, depending on the matrix.  A better method would be for you to
% select it yourself.  Note that mldivide uses a faster method for detecting
% whether or not A is a candidate for sparse Cholesky factorization (see spsym
% in the CHOLMOD package, for example).
%
% Example:
%   F = linfactor (A) ;     % factorizes A into the object F
%   x = linfactor (F,b) ;   % uses F to solve Ax=b
%   norm (A*x-b)
%
% A second output is the time taken by the method, ignoring the overhead of
% determining which method to use.  This makes for a fairer comparison between
% methods, since normally the user will know if the matrix is supposed to be
% symmetric positive definite or not, and whether or not the matrix is sparse.
% Also, the overhead here is much higher than mldivide or spsym.
%
% This function has its limitations:
%
% (1) determining whether or not the matrix is symmetric via nnz(A-A') is slow.
%     mldivide (and spsym in CHOLMOD) do it much faster.
%
% (2) MATLAB really needs a sparse linsolve.  See cs_lsolve, cs_ltsolve, and
%     cs_usolve in CSparse, for example.
%
% (3) this function really needs to be written as a mexFunction.
%
% (4) the full power of mldivide is not brought to bear.  For example, UMFPACK
%     is not very fast for sparse tridiagonal matrices.  It's about a factor of
%     four slower than a specialized tridiagonal solver as used in mldivide.
%
% (5) permuting a sparse vector or matrix is slower in MATLAB than it should be;
%     a built-in linfactor would reduce this overhead.
%
% (6) mldivide when using UMFPACK uses relaxed partial pivoting and then
%     iterative refinement.  This leads to sparser LU factors, and typically
%     accurate results.  linfactor uses sparse LU without iterative refinement.
%
% The primary purpose of this function is to answer The Perennially Asked
% Question (or The PAQ for short (*)):  "Why not use x=inv(A)*b to solve Ax=b?
% How do I use LU or CHOL to solve Ax=b?"  The full answer is below.  The short
% answer to The PAQ (*) is "PAQ=LU ... ;-) ... never EVER use inv(A) to solve
% Ax=b."
%
% The secondary purpose of this function is to provide a prototype for some of
% the functionality of a true MATLAB built-in linfactor function.
%
% Finally, the third purpose of this function is that you might find it actually
% useful for production use, since its syntax is simpler than factorizing the
% matrix yourself and then using the factors to solve the system.
%
% See also lu, chol, mldivide, linsolve, umfpack, cholmod.
%
% Oh, did I tell you never to use inv(A) to solve Ax=b?
%
% Requires MATLAB 7.3 (R2006b) or later.

% Copyright 2007, Timothy A. Davis, University of Florida
% VERSION 1.1.0, Nov 1, 2007

if (nargin < 1 | nargin > 2 | nargout > 2)          %#ok
    error ('Usage: F=linfactor(A) or x=linfactor(F,b)') ;
end

if (nargin == 1)

    %---------------------------------------------------------------------------
    % F = linfactor (A) ;
    %---------------------------------------------------------------------------

    A = arg1 ;
    [m n] = size (A) ;
    if (m ~= n)
        error ('linfactor: A must be square') ;
    end

    if (issparse (A))

        % try sparse Cholesky (CHOLMOD): L*L' = P*A*P'
        if (nnz (A-A') == 0 & all (diag (A) > 0))   %#ok
            try
                tic ;
                [L, g, PT] = chol (A, 'lower') ;
                t = toc ;
                if (g == 0)
                    result.L = L ;
                    result.LT = L' ;    % takes more memory, but solve is faster
                    result.P = PT' ;    % ditto.  Need a sparse linsolve here...
                    result.PT = PT ;
                    result.kind = 'sparse Cholesky: L*L'' = P*A*P''' ;
                    result.code = 0 ;
                    return
                end
            catch
		% matrix is symmetric, but not positive definite
		% (or we ran out of memory)
            end
        end

        % try sparse LU (UMFPACK, with row scaling): L*U = P*(R\A)*Q
        tic ;
        [L, U, P, Q, R] = lu (A) ;
        t = toc ;
        result.L = L ;
        result.U = U ;
        result.P = P ;
        result.Q = Q ;
        result.R = R ;
        result.kind = 'sparse LU: L*U = P*(R\A)*Q where R is diagonal' ;
        result.code = 1 ;

    else

        % try dense Cholesky (LAPACK): L*L' = A
        if (nnz (A-A') == 0 & all (diag (A) > 0))                           %#ok
            try
                tic ;
                L = chol (A, 'lower') ;
                t = toc ;
                result.L = L ;
                result.kind = 'dense Cholesky: L*L'' = A' ;
                result.code = 2 ;
                return
            catch
		% matrix is symmetric, but not positive definite
		% (or we ran out of memory)
            end
        end

        % try dense LU (LAPACK): L*U = A(p,:)
        tic ;
        [L, U, p] = lu (A, 'vector') ;
        t = toc ;
        result.L = L ;
        result.U = U ;
        result.p = p ;
        result.kind = 'dense LU: L*U = A(p,:)' ;
        result.code = 3 ;

    end

else

    %---------------------------------------------------------------------------
    % x = linfactor (F,b)
    %---------------------------------------------------------------------------

    F = arg1 ;
    b = arg2 ;

    if (F.code == 0)

        % sparse Cholesky: MATLAB could use a sparse linsolve here ...
        tic ;
        result = F.PT * (F.LT \ (F.L \ (F.P * b))) ;
        t = toc ;

    elseif (F.code == 1)

        % sparse LU: MATLAB could use a sparse linsolve here too ...
        tic ;
        result = F.Q * (F.U \ (F.L \ (F.P * (F.R \ b)))) ;
        t = toc ;

    elseif (F.code == 2)

        % dense Cholesky: result = F.L' \ (F.L \ b) ;
        lower.LT = true ;
        upper.LT = true ;
        upper.TRANSA = true ;
        tic ;
        result = linsolve (F.L, linsolve (F.L, b, lower), upper) ;
        t = toc ;

    elseif (F.code == 3)

        % dense LU: result = F.U \ (F.L \ b (F.p,:)) ;
        lower.LT = true ;
        upper.UT = true ;
        tic ;
        result = linsolve (F.U, linsolve (F.L, b (F.p,:), lower), upper) ;
        t = toc ;
    end
end


function [points3d, errors] = EsimatePosAmers(pointTracks, ...
    camPoses, cameraParams)

numTracks = numel(pointTracks);
points3d = zeros(numTracks, 3);
numCameras = size(camPoses, 2);
cameraMatrices = containers.Map('KeyType', 'uint32', 'ValueType', 'any');
for i = 1:numCameras
    id = camPoses(i).ViewId;
    R  = camPoses(i).Orientation;
    t  = camPoses(i).Location;
    size_t = size(t);
    if size_t(1) == 3
        t = t';
    end
    cameraMatrices(id) = cameraMatrix(cameraParams, R', -t*R');
end

for i = 1:numTracks
    track = pointTracks(i);
    points3d(i, :) = triangulateOnePoint(track, cameraMatrices);
end

if nargout > 1
    [~, errors] = reprojectionErrors(points3d, cameraMatrices, pointTracks);
end

%--------------------------------------------------------------------------
function point3d = triangulateOnePoint(track, cameraMatrices)

% do the triangulation
numViews = numel(track.ViewIds);
A = zeros(numViews * 2, 4);
for i = 1:numViews
    id = track.ViewIds(i);
    P = cameraMatrices(id)';
    A(2*i - 1, :) = track.Points(i, 1) * P(3,:) - P(1,:);
    A(2*i    , :) = track.Points(i, 2) * P(3,:) - P(2,:);
end

[~,~,V] = svd(A);
X = V(:, end);
X = X/X(end);
point3d = X(1:3)';

%--------------------------------------------------------------------------
function [errors, meanErrorsPerTrack] = reprojectionErrors(points3d, ...
    cameraMatrices, tracks)
numPoints = size(points3d, 1);
points3dh = [points3d, ones(numPoints, 1)];
meanErrorsPerTrack = zeros(numPoints, 1);
errors = [];
for i = 1:numPoints
    p3d = points3dh(i, :);
    reprojPoints2d = reprojectPoint(p3d, tracks(i).ViewIds, cameraMatrices);
    e = sqrt(sum((tracks(i).Points - reprojPoints2d).^2, 2));
    meanErrorsPerTrack(i) = mean(e);
    errors = [errors; e];
end

%--------------------------------------------------------------------------
function points2d = reprojectPoint(p3dh, viewIds, cameraMatrices)
numPoints = numel(viewIds);
points2d = zeros(numPoints, 2);
for i = 1:numPoints
    p2dh = p3dh * cameraMatrices(viewIds(i));
    points2d(i, :) = p2dh(1:2) ./ p2dh(3);
end


function [err, predictedDeg] = poirsonWandellCortMagErr(parm, cortMag)
%
% [err, predictedDeg] = poirsonWandellCortMagErr(parm, cortMag)
%
% AUTHOR: Wandell
% DATE:  11.17.00
% PURPOSE:
%    Fit both the distance scale factor and the foveal phase
% to a set of expanding ring data
%
%

dScale = parm(1);
dShift = parm(2);

% We restrict the range on the estimated fovealPhase to be
% a little past CORTMAG.fovealPhase.  This variable has the
% foveal phase of the stimulus.
% If the search parameter is smaller than the stimulus phase, well, that
% can't be right.  We belive in causality.
% If the parameter is more than 4-5 sec of hemodynamic delay,
% we also get unhappy and kick back a large error.
% We don't ask for the time, sigh.  So for now
% we assume the period is 36 sec and we demand that the phase be less than
% 2*pi/9;
% Finally, we need to make these measurements in complex phase representation
% to avoid wrapping problems near 0 and 2pi
%
phaseDifference = angle(exp(sqrt(-1)*(parm(3) - cortMag.fovealPhase)));
radPerSec = (2*pi)/36;
oneSec    = 1*radPerSec;
fiveSec   = 1.1*radPerSec;
if (phaseDifference < oneSec) | (phaseDifference > fiveSec)
    err = 10000000;
    if nargout == 2
        predictedDeg = NaN;
    end
    return;
else
    fovealPhase = parm(3);
end

% Use the basic function of distance to predict the visual
% field representation in degrees given the distance scale
% parameter, dScale.  This form keeps dist = 0 at 10 deg.
dist = cortMag.allCorticalDist - dShift;
predictedDeg = exp(dScale*dist + log(10));
% figure(testFig);
% plot(dist, predictedDeg,'o')

% Convert the predicted degrees into expected stimulus phase
% as a complex number.  This conversion assumes that the foveal
% phase is 0.
predictedRad = (2*pi)*(predictedDeg/cortMag.stimulusRadius);
predictedCx = exp(sqrt(-1)*predictedRad);
% figure(testFig);
% plot(dist, predictedRad,'o')
% plot(dist, angle(predictedCx),'o')

% Adjust the observed CX phases so that the foveal phase is 0.
% This is assumed by the function when we map from phase
% to degrees, later.
% WE SHOULD BE ABLE TO SET A RANGE OR EVEN FIX THE fovealPhase
% Figure out how to do this here!
%
observedCx = cortMag.allMeanPh/exp(sqrt(-1)*fovealPhase);

err = norm(predictedCx - observedCx);

if nargout == 2
   predictedRad = angle(predictedCx);
   l = find(predictedRad < 0);
   predictedRad(l) = predictedRad(l) + 2*pi;

   % Take into account the fact that we sometimes run the
   % phase map with a restricted range
   %
   phRange = phaseRange(CORTMAG);
   rad2deg = cortMag.stimulusRadius/phRange;
   predictedDeg = rad2deg*predictedRad;
   % figure(testFig);
   % plot(dist, predictedDeg,'o')
end

return;

% DEBUGGING AND NOTES


function [Center,R] = adaptiveDivision(PopObj,K)
% Reference point adaption

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

    [N,M] = size(PopObj);

    if K == 1
        Center = zeros(1,M);
        R      = inf;
        subNum = [1,N];
    else
       %% Detect the number of subregion
        % Calculate the distance between each solution
        fmin     = min(PopObj,[],1);
        fmax     = max(PopObj,[],1);
        PopObj   = (PopObj-repmat(fmin,N,1))./repmat(fmax-fmin,N,1);
        Distance = pdist2(PopObj,PopObj);
        Distance(logical(eye(N))) = inf;
        radius   = max(min(Distance));
        % Detect subregion(s)
        Transformation = zeros(N,1);
        Remain         = find(Transformation==0);
        RegionID       = 1;
        while ~isempty(Remain)
            seeds      = find(~Transformation,1);
            Transformation(seeds) = RegionID;
            Remain     = find(Transformation==0);
            while true
                neighbors = sum(Distance(seeds,Remain)<=radius,1);
                seeds     = Remain(neighbors>=1);
                Transformation(seeds) = RegionID;
                Remain    = find(Transformation==0);
                if sum(neighbors)==0
                    break;
                end
            end
            RegionID = RegionID + 1;
        end
        %% Region division
        % Count the number of subregions of the true PF
        TrueNum = length(unique(Transformation));

        % Calculate the center point of each subregion
        Center = zeros(TrueNum,M);
        R      = ones(TrueNum,1);
        for i = 1 : TrueNum
            current     = Transformation==i;
            Center(i,:) = mean(PopObj(current,:));
            R(i)        = max(pdist2(PopObj(current,:),Center(i,:)));
        end

        % Select K points
        subNum  = tabulate(Transformation);
        subNum  = subNum(:,1:end-1);
        if TrueNum > K
            % Merging small subregions
            while sum(subNum(:,2)~=inf) > K
                [~,I] = min(subNum(:,2));
                Center(I,:) = inf(1,M);
                subNum(I,2) = inf;
                R(I)        = -inf;
                current     = find(Transformation == I);
                [~,T]       = min(pdist2(PopObj(current,:),Center),[],2);
                Transformation(current) = T;

                % Update reference point
                Idx = find(subNum(:,2)~=inf);
                for k =  1 : length(Idx)
                    Center(Idx(k),:) = mean(PopObj(Transformation == Idx(k),:));
                    R(Idx(k))        = max(pdist2(PopObj(Transformation == Idx(k),:),Center(Idx(k),:)))/sqrt(M-1);
                end
            end
        elseif TrueNum < K
            % Splite large subregions
            while sum(subNum(:,2)~=-inf) < K
                [~,I] = max(subNum(:,2));
                Center(I,:) = -inf(1,M);
                subNum(I,2) = -inf;
                R(I)        = -inf;
                current     = find(Transformation == I);
                [~,T1]      = max(pdist2(PopObj(current,:),PopObj(current(randi(length(current))),:)),[],1);
                [~,T2]      = max(pdist2(PopObj(current,:),PopObj(current(T1),:)),[],1);
                [~,T]       = min(pdist2(PopObj(current,:),PopObj(current([T1,T2],:),:)),[],2);
                ExistNum    = length(subNum(:,1));
                Transformation(current) = T + ExistNum;

                % Update reference point
                Center(ExistNum+1,:) = mean(PopObj(Transformation==ExistNum+1,:));
                Center(ExistNum+2,:) = mean(PopObj(Transformation==ExistNum+2,:));
                [R(ExistNum+1),R(ExistNum+2)] = deal(0.5*pdist2(Center(ExistNum+1,:),Center(ExistNum+2,:)));
                subNum(end+1,:) = [ExistNum+1,sum(T==1)];
                subNum(end+1,:) = [ExistNum+2,sum(T==2)];
            end
        end
    end

    % Select reference point
    select = abs(subNum(:,2)) ~= inf;
    Center = Center(select,:);
    R      = R(select);
end


function [ out ] = Distance1D( hist1, hist2 )
%hist1 and hist2 are sets of three historgrams.  One for each color (R,G,B)

dR = EMD1D(hist1(:,1),hist2(:,1));
dG = EMD1D(hist1(:,2),hist2(:,2));
dB = EMD1D(hist1(:,3),hist2(:,3));

out = dR + dG + dB;

end


function scatterbar3(X,Y,Z,width)
%SCATTERBAR3   3-D scatter bar graph.
%   SCATTERBAR3(X,Y,Z,WIDTH) draws 3-D bars of height Z at locations X and Y with width WIDTH.
%
%   X, Y and Z must be of equal size.  If they are vectors, than bars are placed
%   in the same fashion as the SCATTER3 or PLOT3 functions.
%
%   If they are matrices, then bars are placed in the same fashion as the SURF
%   and MESH functions.
%
%   The colors of each bar read from the figure's colormap according to the bar's height.
%
%   NOTE:  For best results, you should use the 'zbuffer' renderer.  To set the current
%   figure renderer to 'zbuffer' use the following command:
%
%       set(gcf,'renderer','zbuffer')
%
%    % EXAMPLE 1:
%    y=[1 2 3 1 2 3 1 2 3];
%    x=[1 1 1 2 2 2 3 3 3];
%    z=[1 2 3 6 5 4 7 8 9];
%    scatterbar3(x,y,z,1)
%    colorbar
%
%    % EXAMPLE 2:
%    [X,Y]=meshgrid(-1:0.25:1);
%    Z=2-(X.^2+Y.^2);
%    scatterbar3(X,Y,Z,0.2)
%    colormap(hsv)
%
%    % EXAMPLE 3:
%    t=0:0.1:(2*pi);
%    x=cos(t);
%    y=sin(t);
%    z=sin(t);
%    scatterbar3(x,y,z,0.07)

% By Mickey Stahl - 2/25/02
% Engineering Development Group
% Aspiring Developer

[r,c]=size(Z);
for j=1:r,
    for k=1:c,
        if ~isnan(Z(j,k))
            drawbar(X(j,k),Y(j,k),Z(j,k),width/2)
        end
    end
end

zlim=[min(Z(:)) max(Z(:))];
if zlim(1)>0,zlim(1)=0;end
if zlim(2)<0,zlim(2)=0;end
axis([min(X(:))-width max(X(:))+width min(Y(:))-width max(Y(:))+width zlim])
caxis([min(Z(:)) max(Z(:))])

function drawbar(x,y,z,width)

h(1)=patch([-width -width width width]+x,[-width width width -width]+y,[0 0 0 0],'b');
h(2)=patch(width.*[-1 -1 1 1]+x,width.*[-1 -1 -1 -1]+y,z.*[0 1 1 0],'b');
h(3)=patch(width.*[-1 -1 -1 -1]+x,width.*[-1 -1 1 1]+y,z.*[0 1 1 0],'b');
h(4)=patch([-width -width width width]+x,[-width width width -width]+y,[z z z z],'b');
h(5)=patch(width.*[-1 -1 1 1]+x,width.*[1 1 1 1]+y,z.*[0 1 1 0],'b');
h(6)=patch(width.*[1 1 1 1]+x,width.*[-1 -1 1 1]+y,z.*[0 1 1 0],'b');
set(h,'facecolor','flat','FaceVertexCData',z)


function asa058_test01 ( )

%*****************************************************************************80
%
%% TEST01 tries out the ASA058 routine.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 February 2008
%
%  Author:
%
%    John Burkardt
%
  k = 5;
  m = 2;
  n = 100;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01\n' );
  fprintf ( 1, '  Test the CLUSTR algorithm.\n' );
  fprintf ( 1, '  Applied Statistics Algorithm 58\n' );
%
%  Read the data.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Reading the data.\n' );

  input_unit = fopen ( 'points_100.txt', 'rt' );

  for i = 1 : n
    x(i,1:m) = fscanf ( input_unit, '%f', m );
  end

  fclose ( input_unit );
%
%  Print a few data values.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  First 5 data values:\n' );
  fprintf ( 1, '\n' );
  for i = 1 : 5
    fprintf ( 1, '  %8d', i );
    for j = 1 : m
      fprintf ( 1, '  %14f', x(i,j) );
    end
    fprintf ( 1, '\n' );
  end
%
%  Initialize the cluster centers arbitrarily.
%
  for i = 1 : k
    for j = 1 : m
      d(i,j) = x(i,j);
    end
  end
%
%  Compute the clusters.
%
  nz = 1;
  k2 = k;

  [ d, dev, b, e ] = clustr ( x, d, n, m, k, nz, k2 );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Cluster  Population  Energy\n' );
  fprintf ( 1, '\n' );

  for i = 1 : k
    fprintf ( 1, '  %8d  %8d  %14f\n', i, e(i), dev(i) );
  end

  e_sum = sum ( e(1:k) );
  dev_sum = sum ( dev(1:k) );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     Total  %8d  %14f\n', e_sum, dev_sum );

  return
end


function a = c4mat_test_inverse ( n )

%*****************************************************************************80
%
%% C4MAT_TEST_INVERSE computes the inverse of the test matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 April 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Output, complex A(N,N), the matrix.
%
  a = ( c4mat_test ( n ) )';

  return
end


function centroid = findBallFcn(greenBall1, thresh, imageType, axH)

%% Find Green Object
% This script reads in an image file and then attempts to find a green
% object in the image. It is designed to find one green ball and highlight
% that ball on the original image

% Copyright 2013 The MathWorks, Inc.

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

if isempty(greenBall1)
    return;
end
if ischar(greenBall1)
    greenBall1 = imread(greenBall1);
end
%% Step 1: Read image into MATLAB
% First we read the specified image from the file and bring it into MATLAB
% as a variable. We also display the image to ensure it is correct.
% greenBall1 = imread('greenBall3.jpg');
% imtool(greenBall1);

%% Step 2: Identify Unique Characteristics of Object of Interest

%%
% Extract each color
% Next we using indexing to extract three 2D matrices from the 3D image
% data corresponding to the red, green, and blue components of the image.
r = greenBall1(:, :, 1);
g = greenBall1(:, :, 2);
b = greenBall1(:, :, 3);

%%
% View different color planes
% figure
% subplot(2,2,1),imagesc(r)
% subplot(2,2,2),imagesc(g)
% subplot(2,2,3),imagesc(b)

%%
% Calculate Green
% Then we perform an arithmetic operation on the matrices as a whole to try
% to create one matrix that represents an intensity of green.
justGreen = g - r/2 - b/2;
% colorPlanesPlot(r,g,b,justGreen);

%%
% close all

%% Step 3: Isolate Object of Interest

%%
% Threshold the image
% Now we can set a threshold to separate the parts of the image that we
% consider to be green from the rest.
% bw = justGreen > 50;
% imagesc(bw);
% colormap(gray);
if nargin == 4
    bw = justGreen > thresh;
else
    bw = justGreen > 80;
end
%%
% Remove small unwanted objects
% We can use special functions provided by the Image Processing toolbox to
% quickly perform common image processing tasks. Here we are using
% BWAREAOPEN to remove groups of pixels less than 30.
ball1 = bwareaopen(bw, 30);
% imagesc(ball1);

%% Step 4: Find center of green object
% Now we are using REGIONPROPS to extract the centroid of the group of
% pixels representing the ball.
% s  = regionprops(ball1, {'centroid','area'});
% imshow(greenBall1);
% if isempty(s)
%   title('No ball found!');
% else
%   [~, id] = max([s.Area]);
%   hold on, plot(s(id).Centroid(1),s(id).Centroid(2),'wp','MarkerSize',20,'MarkerFaceColor','r'), hold off
%   title(['Center location is (',num2str(s(id).Centroid(1),4),', ',num2str(s(id).Centroid(2),4),')'])
% end
s  = regionprops(ball1, {'centroid','area'});
if isempty(s)
    centroid = [];
else
    [maxArea, id] = max([s.Area]); %#ok<ASGLU>
    centroid = s(id).Centroid;
end
switch imageType
   case 'video'
      imshow(greenBall1, 'Parent', axH);
      if ~isempty(centroid)
         line(centroid(1), centroid(2), 'Parent', axH, 'Color', 'w', 'Marker', 'p', 'MarkerSize', 20, 'MarkerFaceColor', 'r')
      end
   case 'bw'
      imshow(ball1, 'Parent', axH);
end
%% Step 5: Verify estimated location
% Finally we will plot the center on the original image to clearly evaluate
% how well we have found the center.
% imagesc(greenBall1);
% hold on, plot(s(id).Centroid(1),s(id).Centroid(2),'wp','MarkerSize',20,'MarkerFaceColor','r'), hold off


function jac = p29_jac ( neqn, t, y )

%*****************************************************************************80
%
%% P29_JAC evaluates the jacobian for problem p29.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Input, real T, Y(NEQN), the arguments of the jacobian.
%
%    Output, real JAC(NEQN,NEQN), the jacobian matrix.
%
  jac = zeros ( neqn, neqn );

  if ( t <= 10.0 )
    jac(1,1) = 0.0;
  else
    jac(1,1) = -2.0;
  end

  return
end


function r = r8pbu_resid ( m, n, mu, a, x, b )

%*****************************************************************************80
%
%% R8PBU_RESID computes the residual R = B-A*X for R8PBU matrices.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 June 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows of the matrix.
%    M must be positive.
%
%    Input, integer N, the number of columns of the matrix.
%    N must be positive.
%
%    Input, integer MU, the number of superdiagonals in the matrix.
%    MU must be at least 0 and no more than N-1.
%
%    Input, real A(MU+1,N), the matrix.
%
%    Input, real X(N), the vector to be multiplied by A.
%
%    Input, real B(M), the desired result A * x.
%
%    Output, real R(M), the residual R = B - A * X.
%
  r = r8pbu_mv ( m, n, mu, a, x );

  r(1:m) = b(1:m) - r(1:m);

  return
end


%% housekeeping
close all
clear
clc
%% add the necessary paths
rise_startup()

%% we read the model
m=dsge('fs2000');
%% we solve, passing a function that solves the steady state analytically

mwssf_a=solve(m,'steady_state_file','fs2000_steadystate');

%% we solve passing a function that gives initial values of the steady state.
% this is the counterpart to dynare's initval

mwssf_b=solve(m,'steady_state_file','fs2000_steadystate_initval');

%% compare the solutions
mwssf_a.print_solution
mwssf_b.print_solution

%% now we repeat the same exercise but with the steady state model inside the model file
% since we would like to do the two cases above in an elegant way, we
% introduce a switch called 'approximate'. You can call it what you want
% but it has to be issued while 'rising' the model. Not after.

% to continue in our elegance we initialize a vector of models
mv=rise.empty(0);
approximate=[0,1];
for approx=1:numel(approximate)
    approx_flag=struct('approximate',approximate(approx));
    % when approximate==0, we read the exact steady state solution
    % when approximate==1, we read an approximation of the steady state
    % solution. in both cases, the computed values will be used as an
    % initial guess for the computation of the steady state, unless we add
    % the attribute 'imposed' to 'steady_state_model', in which case rise
    % does not check that the initial guess actually solves the steady
    % state.
    mv(approx,1)=rise('fs2000_b','rise_flags',approx_flag);
end

%% we solve both models simultaneously
mv=solve(mv);

%% we print the solution
print_solution(mv)

%% a word of warning
% you might be tempted to or make the mistake of having both a
% steady_state_model block and a steady state file. RISE will use the
% steady state file and ignore the steady_state_model block!!! If you don't
% like this behavior, shoot an email to junior.maih AT gmail.com and let me
% know about your arguments for doing it differently.


function [err, errK] = getHcurlerror3ND(node,elem,curlE,Eh,markedElem)
%% GETHCURLERROR3ND Hcurl norm of approximation error for the lowest order Nedelect element in 3-D.
%
% err = GETHCURLERROR3ND(node,elem,curlE,Eh,markedElem);
%
% Example
%
%     node = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1];
%     elem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];
%     maxIt = 4;
%     HcurlErr = zeros(maxIt,1);
%     N = zeros(maxIt,1);
%     for k = 1:maxIt
%         [node,elem] = uniformbisect3(node,elem);
%         [elem2dof,edge] = dof3edge(elem);
%         pde = Maxwelldata2;
%         uI = edgeinterpolate(pde.exactu,node,edge);
%         HcurlErr(k) = getHcurlerror3ND(node,elem,pde.curlu,uI);
%         N(k) = length(uI);
%     end
%     r = showrate(N,HcurlErr,1,'b-+');
%     legend('||u-u_I||_{curl}',['N^{' num2str(r) '}'],'LOCATION','Best');
%
% See also getHcurlerror3ND1, getHcurlerror3ND2, getL2error3ND
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

%% Sort elem to ascend ordering
elem = sort(elem,2);

%% Construct Data Structure
elem2dof = dof3edge(elem);
NT = size(elem,1);% Ndof = max(elem2dof(:)); %N = size(node,1);
% compute curl phi
[Dlambda,volume] = gradbasis3(node,elem);
% curl phi = 2*Dlambda_i cross Dlambda_j;
curlPhi(:,:,6) = 2*cross(Dlambda(:,:,3),Dlambda(:,:,4),2);
curlPhi(:,:,1) = 2*cross(Dlambda(:,:,1),Dlambda(:,:,2),2);
curlPhi(:,:,2) = 2*cross(Dlambda(:,:,1),Dlambda(:,:,3),2);
curlPhi(:,:,3) = 2*cross(Dlambda(:,:,1),Dlambda(:,:,4),2);
curlPhi(:,:,4) = 2*cross(Dlambda(:,:,2),Dlambda(:,:,3),2);
curlPhi(:,:,5) = 2*cross(Dlambda(:,:,2),Dlambda(:,:,4),2);
curlEhp = zeros(NT,3);
for k = 1:6
    curlEhp = curlEhp + ...
    repmat(Eh(elem2dof(:,k)),1,3).*curlPhi(:,:,k);
end

%% compute Hcurl error element-wise
[lambda,w] = quadpts3(2);
nQuad = size(lambda,1);
errK = zeros(NT,1);
for p = 1:nQuad
    % quadrature points in the x-y-z coordinate
    pxy = lambda(p,1)*node(elem(:,1),:) ...
        + lambda(p,2)*node(elem(:,2),:) ...
        + lambda(p,3)*node(elem(:,3),:) ...
        + lambda(p,4)*node(elem(:,4),:);
    if isnumeric(curlE) % a constant vector
        curlEp = repmat(curlE,NT,1);
    else % function handel
        curlEp = curlE(pxy);
    end
%     curlEp = curlE(pxy);
    % compute Ehp at quadrature points
    errK = errK + w(p)*sum((curlEp - curlEhp).^2,2);
end
errK = errK.*volume;
% modify the error
errK(isnan(errK)) = 0; % remove the singular part
if (nargin == 5) && ~isempty(markedElem)
    errK = errK(markedElem); % error on some marked region
end
err = sqrt(sum(errK));
%% TODO write more M-lint


function y = ft_preproc_slidingrange(dat, width, varargin)

% FT_PREPROC_SLIDINGRANGE computes the range of the data in a sliding time
% window of the width specified. Width should be an odd number (since the
% window needs to be centered on an individual sample).
%
% Use as
%   y = ft_preproc_slidingrange(dat, width, ...)
%
% Optional key-value pair arguments are:
%   'normalize', whether to normalize the range of the data with the square
%                root of the window size

% Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

normalize = ft_getopt(varargin, 'normalize', false);

% preprocessing fails on channels that contain NaN
if any(isnan(dat(:)))
  ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');
end

if mod(width+1, 2)
  ft_error('width should be an odd number');
end

% compute half width
h = (width-1)/2;

n = size(dat,2);
minval = zeros(size(dat));
maxval = zeros(size(dat));

for i=1:n
  begsample = i-h;
  endsample = i+h;
  if begsample<1
    begsample = 1;
  end
  if endsample>n
    endsample=n;
  end
  minval(:,i) = min(dat(:,begsample:endsample),[],2);
  maxval(:,i) = max(dat(:,begsample:endsample),[],2);
end

y = maxval - minval;

if istrue(normalize)
  y = y ./ sqrt(width);
end


% SIS模型演示程序
clear;clc;
ts = 0 : 150;

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

% lambda   日接触率
%  miu     日治愈率，即每天治愈病人数占病人总数的比例
lambda_miu = [0.27, 0.1;...
              0.25, 0.1;...
              0.20, 0.1;...
              0.15, 0.1;...
              0.08, 0.1];
infective_matrix = zeros(length(ts),length(lambda_miu));

for i = 1 : length(lambda_miu)
  lambda = lambda_miu(i,1);
  miu = lambda_miu(i,2);
  [t,x] = ode45(@(t,y) ill_sis(t,y,lambda,miu), ts, x0);
  infective_matrix(:,i) = x(:,1);
end

plot(t, infective_matrix);
legend(num2str(lambda_miu(1,:)), num2str(lambda_miu(2,:)), num2str(lambda_miu(3,:)), num2str(lambda_miu(4,:)), num2str(lambda_miu(5,:)));
title('SIS模型');
grid;


% GPSIMSAMPLETEST Test the single input motif code.
% FORMAT
% DESC tests the GPSIM kernels by sampling an f and x for a couple
% of genes. Double checks that everything is working by solving the
% differential equation numerically for each gene and comparing to
% f.

% SHEFFIELDML

randn('seed', 1e5);
rand('seed', 1e5);

numSamp = 50;
t = linspace(0, 2, numSamp)';
interSpace = t(2)-t(1);
X_0_1 = 1;
C1 = 5;
D1 = 5;
delta1 = 0;
X_0_2 = 2;
C2 = 0.5;
D2 = 0.5;
delta2 = delta1;
sigma = 1;
rbfKern = kernCreate(t, 'rbf');
rbfKern.inverseWidth = 2/(sigma*sigma);
rbfKern.variance = 1;
simKern1 = kernCreate(t, 'sim');
simKern1.inverseWidth = 2/(sigma*sigma);
simKern1.variance = 1;
simKern2 = simKern1;
simKern1.initVal = X_0_1;
simKern2.initVal = X_0_2;
simKern1.variance = C1*C1;
simKern2.variance = C2*C2;
simKern1.decay = D1;
simKern2.decay = D2;
simKern1.delay = delta1;
dimKern2.delay = delta2;

% K_11 = kernCompute(rbfKern, t);
% K_22 = kernCompute(simKern1, t);
% K_33 = kernCompute(simKern2, t);
% K_21 = simXrbfKernCompute(simKern1, rbfKern, t);
% K_31 = simXrbfKernCompute(simKern2, rbfKern, t);
% K_12 = K_21';
% K_13 = K_31';
% K_23 = simXsimKernCompute(simKern1, simKern2, t);
% K_32 = K_23';

% K2 = [K_11 K_12 K_13; K_21 K_22 K_23; K_31 K_32 K_33];

kern = kernCreate(t, {'multi', 'rbf', 'sim', 'sim'});
kern.comp{1} = rbfKern;
kern.comp{2} = simKern1;
kern.comp{3} = simKern2;
counter = 0;
K = kernCompute(kern, t);
colordef white
counter = counter + 1;
figure(counter)
imagesc(K, [-1.1 1.1]);
handle = [];
set(gca, 'fontname', 'times')
handle = [handle; text('Interpreter', 'latex', 'string', '$$f(t)$$', 'position', ...
            [25 160])];
handle = [handle; text('Interpreter', 'latex', 'string', '$$x_1(t)$$', 'position', ...
            [75 160])];
handle = [handle; text('Interpreter', 'latex', 'string', '$$x_2(t)$$', 'position', ...
            [125 160])];
set(handle, 'horizontalalignment', 'right')
handle = [handle; text('Interpreter', 'latex', 'string', '$$f(t)$$', 'position', ...
            [-10 25])];
handle = [handle; text('Interpreter', 'latex', 'string', '$$x_1(t)$$', 'position', ...
            [-10 75])];
handle = [handle; text('Interpreter', 'latex', 'string', '$$x_2(t)$$', 'position', ...
            [-10 125])];
set(handle, 'horizontalalignment', 'center')

set(handle, 'fontsize', 34)
set(gca, 'fontsize', 34)
axis off
colorbar
print('-depsc', ['../tex/diagrams/gpsimTestKernelImage'...
                 '.eps'])

figure
for i = 1:3
  x1 = -1;
  while any(x1<0) | any(x2<0) | any(f<0)
    y = gsamp(zeros(1, size(K, 1)), K, 1);
    x1 = y(numSamp+1:2*numSamp)';
    x2 = y(2*numSamp+1:end)';
    f = y(1:numSamp)';
    x1 = x1 + X_0_1*exp(-D1*t);
    x2 = x2 + X_0_2*exp(-D2*t);
  end

  counter = counter + 1;
  figure(counter), clf,
  lhand = plot(f), hold on, lhand = [lhand plot(x1, 'c')];, lhand = ...
          [lhand plot(x2, 'r')];
  set(lhand, 'linewidth', 4)
  set(gca, 'fontsize', 18)
  ylim = get(gca, 'ylim');
  set(gca, 'ylim', ylim);
  print('-depsc', ['../tex/diagrams/gpsimTestSamples' num2str(counter) '.eps'])

  f1Guess = (diff(x1)/interSpace+D1*(x1(1:end-1)))/C1;
  f2Guess = (diff(x2)/interSpace+D2*(x2(1:end-1)))/C2;
  counter = counter + 1;
  figure(counter), clf
  lhand = plot(f), hold on, lhand = [lhand plot(f1Guess, 'c')];
  lhand = [lhand plot(f2Guess, 'r')];
  set(lhand, 'linewidth', 4)
  set(gca, 'fontsize', 18)
  set(gca, 'ylim', ylim);
  print('-depsc', ['../tex/diagrams/gpsimTestSamples' num2str(counter) '.eps'])
end


function [F] = Filter2D(Norder,Nc,sp)

% function [F] = Filter2D(Norder,sp)
% Purpose : Initialize 2D filter matrix of order sp and cutoff Nc

Globals2D;

filterdiag = ones((Norder+1)*(Norder+2)/2,1);
alpha = -log(eps);

% build exponential filter
sk = 1;
for i=0:Norder
  for j=0:Norder-i
    if (i+j>=Nc)
      filterdiag(sk) = exp(-alpha*((i+j - Nc)/(Norder-Nc))^sp);
    end
    sk = sk+1;
  end
end

F = V*diag(filterdiag)*invV;
return;


classdef TestEigen
    %TestEigen

    methods (Static)
        function test_1
            A = randn(5); A = A.'*A;
            evals = cv.eigen(A);
            [evals,evecs,b] = cv.eigen(A);
        end

        function test_compare_against_eig
            A = gallery('lehmer',4);
            [evals,evecs] = cv.eigen(A);

            % match orientation, order, and sign
            [V,D] = eig(A);
            [D,ord] = sort(diag(D), 'descend');
            V = V(:,ord).';
            idx = (sign(evecs(:,1)) ~= sign(V(:,1)));
            V(idx,:) = -1 * V(idx,:);

            % compare
            assert(norm(D - evals) < 1e-6);
            assert(norm(V - evecs) < 1e-6);
        end

        function test_error_argnum
            try
                cv.eigen();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end