function halton_test11 ( )

%*****************************************************************************80
%
%% TEST11 tests U2_TO_SPHERE_UNIT_3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 January 2009
%
%  Author:
%
%    John Burkardt
%
  dim_num2 = 3;

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

  dim_num = 2;
  halton_dim_num_set ( dim_num );
  n = 5;
  step = 123456789;
  halton_step_set ( step );
  seed(1:dim_num) = 0;
  halton_seed_set ( seed );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  DIM_NUM = %12d\n', dim_num );
  fprintf ( 1, '  N =    %12d\n', n );
  fprintf ( 1, '  STEP = %12d\n', step );

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

  for j = 1 : n
    u = halton ( );
    x = u2_to_sphere_unit_3d ( u );
    fprintf ( 1, '  ' );
    for i = 1 : dim_num2
      fprintf ( 1, '  %6f', x(i) );
    end
    fprintf ( 1, '\n' );
  end

  n = 1000;
  step = 0;
  halton_step_set ( step );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  N =    %12d\n', n );
  fprintf ( 1, '  STEP = %12d\n', step );

  average(1:dim_num2) = 0.0;

  for i = 1 : n
    u = halton ( );
    x = u2_to_sphere_unit_3d ( u );
    average(1:dim_num2) = average(1:dim_num2) + x(1:dim_num2);
  end

  average(1:dim_num2) = average(1:dim_num2) / n;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average the points, which should get a value\n' );
  fprintf ( 1, '  close to zero, and closer as N increases.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average:        ' );
  for i = 1 : dim_num2
    fprintf ( 1, '  %8e', average(i) );
  end
  fprintf ( 1, '\n' );

  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 j2 = 1 : 5

    seed_val = get_seed ( );
    step = seed_val + 111 * j2;
    halton_step_set ( step );

    u = halton ( );
    v = u2_to_sphere_unit_3d ( u );

    step = 0;
    halton_step_set ( step );

    dot_average = 0.0;

    for j = 1 : n
      u = halton ( );
      x = u2_to_sphere_unit_3d ( u );
      dot_average = dot_average + abs ( x(1:dim_num2) * v(1:dim_num2)' );
    end

    dot_average = dot_average / n;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Random V:         ' );
    for j = 1 : dim_num2
      fprintf ( 1, '  %8f', v(j) );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Average |(XdotV)| %f\n', dot_average );

  end

  return
end


function [C, sigma] = dataset3Params(X, y, Xval, yval)
%EX6PARAMS returns your choice of C and sigma for Part 3 of the exercise
%where you select the optimal (C, sigma) learning parameters to use for SVM
%with RBF kernel
%   [C, sigma] = EX6PARAMS(X, y, Xval, yval) returns your choice of C and
%   sigma. You should complete this function to return the optimal C and
%   sigma based on a cross-validation set.
%

% You need to return the following variables correctly.
C = 1;
sigma = 0.3;

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return the optimal C and sigma
%               learning parameters found using the cross validation set.
%               You can use svmPredict to predict the labels on the cross
%               validation set. For example,
%                   predictions = svmPredict(model, Xval);
%               will return the predictions on the cross validation set.
%
%  Note: You can compute the prediction error using
%        mean(double(predictions ~= yval))
%

% C = best C
% sigma = best Sigma
values = [0.01 0.03 0.1 0.3 1, 3, 10 30]';

% all predictions
predictions = zeros(size(values));

for i=1:size(values,1), % C
    for j=1:size(values,1), % sigma

        model = svmTrain(X, y, values(i), @(x1, x2) gaussianKernel(x1, x2, values(j)));
        predict = svmPredict(model, Xval);
        predictions(i,j) = mean(double(predict ~= yval));

    end
end

[colmin, rowindex] = min(predictions);
[minerror, index] = min(colmin);

C = values(rowindex(index))
sigma = values(index)

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

end


function[x,y]=ellcurves(varargin)
%ELLCURVES  Returns curves corresponding to specified ellipse properties.
%
%   For direct plotting of ellipses, see ELLPLOT, which calls ELLCURVES.
%
%   ZC=ELLCURVES(KAPPA,LAMBDA,THETA,ZRES) returns complex-valued curves ZC
%   tracing out the periphery of ellipses with amplitude KAPPA, linearity
%   LAMBDA, and orientation THETA, located at complex positions ZRES.
%
%   All input arguments are arrays of the same length, say N.  By default,
%   ZC is calculated at 32 locations around the periphery.  Thus ZC will be
%   a complex-valued matrix with 32 rows and N columns.
%
%   [XC,YC]=ELLCURVES(...) alternately returns the real and imaginary parts
%   of ZC, corresponding to the X- and Y- components of the ellipses.
%
%   ELLCURVES(KAPPA,LAMBDA,THETA,PHI,ZRES) with five input arguments begins
%   each ellipse at phase PHI.  For most applications, the starting phase
%   does not matter.  The default value is to begin with a phase of zero.
%
%   ELLCURVES(... ,'npoints',M) uses M points around the ellipse periphery.
%
%   ELLCURVES(... ,'aspect',AR) with AR=[XAR YAR] multiplies the X-signal
%   and Y-signal by XAR and YAR, respectively, for plotting purposes.
%
%   ELLCURVES is called by ELLPLOT, and is also useful in applications,
%   e.g. analysis of model fields within elliptical contours.
%
%   The curves can be plotted with PLOT(ZC).
%
%   See also ELLIPSEPLOT, ELLSIG, INELLIPSE.
%
%   Usage: zc=ellcurves(kappa,lambda,theta,zres);
%          zc=ellcurves(kappa,lambda,theta,phi,zres);
%          zc=ellcurves(kappa,lambda,theta,phi,zres,'npoints',64);
%          [xc,yc]=ellcurves(kappa,lambda,theta,phi,zres,'npoints',64);
%          zc=ellcurves(kappa,lambda,theta,phi,zres,'aspect',ar,'npoints',64);
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2014--2018 J.M. Lilly --- type 'help jlab_license' for details

na=length(varargin);

k=varargin{1};
l=varargin{2};
theta=varargin{3};

ar=[1 1];
npoints=32;

if na>4
    for i=1:3
        if ischar(varargin{end-1})
            if strcmpi(varargin{end-1}(1:3),'npo')
                npoints=varargin{end};
            elseif strcmpi(varargin{end-1}(1:3),'asp')
                ar=varargin{end};
            end
            na=na-2;
            varargin=varargin(1:end-2);
        end
    end
end

if length(varargin)==5
    phi=varargin{4};
    x=varargin{5};
else
    x=varargin{4};
    if iscell(k)
        for i=1:length(k)
             phi{i}=zeros(size(k{i}));
        end
    else
        phi=zeros(size(k));
    end
end

if ~iscell(k)
    z=ellcurves_one(k,l,theta,phi,x,ar,npoints);
else
    for i=1:length(k)
        z{i,1}=ellcurves_one(k{i},l{i},theta{i},phi{i},x{i},ar,npoints);
    end
end

if nargout==2
    if iscell(z)
        x=cellreal(z);
        y=cellimag(z);
    else
        x=real(z);
        y=imag(z);
    end
else
    x=z;
end

function[z]=ellcurves_one(kappa,lambda,theta,phi,x,ar,npoints)
phio=linspace(0,2*pi,npoints);
%x=conj(x');

z=zeros(length(phio),length(kappa));
for i=1:length(phio)  %Loop over phio, very fast
    [xc,yc]=ellsig(kappa,lambda,theta,phi+phio(i),'real');
    %vsize(xc,yc,x)
    z(i,:)=ar(1)*xc+sqrt(-1)*ar(2)*yc+x;
end
%vsize(xc,yc,x)

%if ~isempty(strfind(str,'not'))
%    z=permute(z,[2 1]);  %This is like 6 times faster than conjugate transpose
%end


%% RangeFrame Demo
%
%  James Houghton
%  James.P.Houghton@gmail.com
%  December 4 2009
%
% Requires rangeframe.m
%
% In this demo we use the range frame to display the range of the first and last quartile,
% and the mean of a bivariate scatter plot. The same range frame could display other information,
% such as median, standard deviation, etc. with appropriate explanation.
%

%% Generate data to plot
x = exp(0 + .5*randn(1,100));                 % the log-normal is an interesting distribution
y = x + .15*randn(1,100);

%% determine relevant range frame points
x_sort = sort(x);
x_Q1 = x_sort(round(length(x_sort)/4));       %approximate 1st quartile
x_Q3 = x_sort(round(length(x_sort)*3/4));     %approximate 3rd quartile

y_sort = sort(y);
y_Q1 = y_sort(round(length(y_sort)/4));       %approximate 1st quartile
y_Q3 = y_sort(round(length(y_sort)*3/4));     %approximate 3rd quartile

x_frame = [min(x), x_Q1, mean(x), x_Q3, max(x)];
y_frame = [min(y), y_Q1, mean(y), y_Q3, max(y)];

%% plot the data
% we can use a simple plot command, as the changes are made at the axis level
% instead of at the figure level.
plot(x, y, '.');

% apply a range frame to the data we are interested in
ax1 = rangeframe(gca, x_frame, y_frame);

% we can make changes to the axis after it is returned from the rangeframe function
set(ax1, 'DefaultTextInterpreter', 'Latex');    %use the latex font interpreter
set(ax1, 'XTick', [0, 1, 2, 3, 4], ...          %set the axis values to display
         'Ytick', [0, 1, 2, 3, 4]);

xlabel(ax1, 'X data');                          %label everything
ylabel(ax1, 'Y data');
title(ax1, 'Statistical data with quartiles and mean');


function boundary = p03_boundary_nearest ( m, n, point )

%*****************************************************************************80
%
%% P03_BOUNDARY_NEAREST returns a nearest boundary point in problem 03.
%
%  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.
%
%    31 August 2005: Thanks to Hua Fei for pointing out that a previous
%    version of this routine gave inaccurate results for points that were
%    significantly far from the box.
%
%  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 points.
%
%    Output, real BOUNDARY(M,N), points on the boundary
%    that are nearest to each point.
%
  center = [ 0.0, 0.0 ];
  r1 = 1.0;
  r2 = 0.4;
  x1 = -1.0;
  x2 = +1.0;
  y1 = -1.0;
  y2 = +1.0;

  for j = 1 : n

    x = point(1,j);
    y = point(2,j);
%
%  Special case: a point at the center of the box.
%  The closest point is ANY point on the circle.
%
    if ( point(1,j) == center(1) & point(2,j) == center(2) )
      boundary(1,j) = center(1) + r2;
      boundary(2,j) = center(2);
      continue
    end
%
%  Is the point to the left of the box?
%
    if ( x <= x1 )

      boundary(1,j) = x1;

      if ( y <= y1 )
        boundary(2,j) = y1;
      elseif ( y <= y2 )
        boundary(2,j) = y;
      elseif ( y2 <= y )
        boundary(2,j) = y2;
      end
%
%  To the right of the box?
%
    elseif ( x2 <= x )

      boundary(1,j) = x2;

      if ( y <= y1 )
        boundary(2,j) = y1;
      elseif ( y <= y2 )
        boundary(2,j) = y;
      elseif ( y2 <= y )
        boundary(2,j) = y2;
      end
%
%  Below the middle of the box?
%
    elseif ( y <= y1 )

      boundary(1,j) = x;
      boundary(2,j) = y1;
%
%  Above the middle of the box?
%
    elseif ( y2 <= y )

      boundary(1,j) = x;
      boundary(2,j) = y2;
%
%  Inside the box.
%  Figure out which side is closest by drawing the diagonal lines.
%
    else
%
%  Y is small.
%
      if (     y <= x &  y <= -x )
        boundary(1,j) = x;
        boundary(2,j) = y1;
%
%  X is big.
%
      elseif ( y <= x & -y <=  x )
        boundary(1,j) = x2;
        boundary(2,j) = y;
%
%  Y is big.
%
      elseif ( x <= y & -x <=  y )
        boundary(1,j) = x;
        boundary(2,j) = y2;
%
%  X is small.
%
      elseif ( x <= y &  x <= -y )
        boundary(1,j) = x1;
        boundary(2,j) = y;
      end
%
%  For points inside the box, the boundary of the circle might be closer than
%  the boundary of the box.
%
      r = sqrt ( sum ( ( point(1:m,j) - center(1:m)' ).^2 ) );

      dist_circle = abs ( r - r2 );
      dist_box = sqrt ( sum ( ( point(1:m,j) - boundary(1:m,j) ).^2 ) );

      if ( dist_circle <  dist_box )
        boundary(1:m,j) = center(1:m)' + r2 / r * ( point(1:m,j) - center(1:m)' );
      end

    end

  end

  return
end


function [mu,vecs,vals] = onlineImagePCA_radon(files,batchSize,scale,pixels,thetas,numPerFile)
%onlineImagePCA_radon finds postural eigenmodes based upon a set of
%aligned images (called by findPosturalEigenmodes.m).
%
%   Input variables:
%
%       files -> cell array of VideoReader objects
%       batchSize -> # of images to process at once
%       scale -> image scaling factor
%       pixels -> radon-transform space pixels to use (Lx1 or 1xL array)
%       thetas -> angles used in Radon transform
%       numPerFile -> # of images to use per file
%
%
%   Output variables:
%
%       mu -> mean value for each of the pixels
%       vecs -> postural eignmodes (LxL array).  Each column (vecs(:,i)) is
%                   an eigenmode corresponding to the eigenvalue vals(i)
%       vals -> eigenvalues of the covariance matrix
%
%
% (C) Gordon J. Berman, 2014
%     Princeton University

    if nargin < 3 || isempty(scale);
        scale = 10/7;
    end

    if nargin < 6 || isempty(numPerFile)
        numPerFile = -1;
    end

    Nf = length(files);
    lengths = zeros(Nf,1);
    for i=1:Nf
        lengths(i) = files{i}.NumberOfFrames;
    end

    L = length(pixels);

    testImage = read(files{1},1);
    testImage = testImage(:,:,1);
    s = size(testImage);
    nX = round(s(1)/scale);
    nY = round(s(2)/scale);
    s = [nX nY];

    firstBatch = true;
    tempMu = zeros(1,L);
    totalImages = 0;
    for t=1:Nf

        fprintf(1,'Processing File #%5i out of %5i\n',t,Nf);

        M = lengths(t);
        if numPerFile == -1
            currentNumPerFile = M;
        else
            currentNumPerFile = numPerFile;
        end

        if M < currentNumPerFile
            currentIdx = 1:M;
        else
            currentIdx = randperm(M,currentNumPerFile);
        end
        M = min([lengths(t) currentNumPerFile]);

        if M < batchSize
            currentBatchSize = M;
        else
            currentBatchSize = batchSize;
        end
        num = ceil(M/currentBatchSize);

        currentVideoReader = files{t};

        currentImage = 0;
        X = zeros(currentBatchSize,L);
        for j=1:num

            fprintf(1,'\t Batch #%5i out of %5i\n',j,num);

            if firstBatch

                firstBatch = false;

                parfor i=1:currentBatchSize

                    a = read(currentVideoReader,currentIdx(i));
                    a = double(imresize(a(:,:,1),s));
                    lowVal = min(a(a>0));
                    highVal = max(a(a>0));
                    a = (a - lowVal) / (highVal - lowVal);

                    R = radon(a,thetas);
                    X(i,:) = R(pixels);

                end
                currentImage = currentBatchSize;

                mu = sum(X);
                C = cov(X).*currentBatchSize + (mu'*mu)./ currentBatchSize;

            else

                if j == num
                    maxJ = M - currentImage;
                else
                    maxJ = currentBatchSize;
                end

                tempMu(:) = 0;
                iterationIdx = currentIdx((1:maxJ) + currentImage);
                parfor i=1:maxJ

                    a = read(currentVideoReader,iterationIdx(i));
                    a = double(imresize(a(:,:,1),s));

                    lowVal = min(a(a>0));
                    highVal = max(a(a>0));
                    a = (a - lowVal) / (highVal - lowVal);

                    R = radon(a,thetas);
                    y = R(pixels);
                    X(i,:) = y';
                    tempMu = tempMu + y';

                end

                mu = mu + tempMu;
                C = C + cov(X(1:maxJ,:)).*maxJ + (tempMu'*tempMu)./maxJ;
                currentImage = currentImage + maxJ;

            end

        end

        totalImages = totalImages + currentImage;

    end

    mu = mu ./ totalImages;
    C = C ./ totalImages - mu'*mu;

    fprintf(1,'Finding Principal Components\n');
    [vecs,vals] = eig(C);

    vals = flipud(diag(vals));
    vecs = fliplr(vecs);


%============================================================================
% Copyright (C) 2014, Heikki Hyyti
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files (the "Software"),
% to deal in the Software without restriction, including without limitation
% the rights to use, copy, modify, merge, publish, distribute, sublicense,
% and/or sell copies of the Software, and to permit persons to whom the
% Software is furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
% DEALINGS IN THE SOFTWARE.
%============================================================================

function [a,b] = fitRegressionLine(x, y)
    A11 = x' * x;
    A12 = sum(x);
    A21 = A12;
    A22 = size(x,1);

    B11 = y(:,1)' * x;
    B21 = sum(y(:,1));

    a = (A12*B21 - A22*B11) / (A12*A21 - A11*A22);
    b = (A11*B21 - A21*B11) / (A11*A22 - A12*A21);
end


clear all
addpath('../ParNMPC/')
%% Formulate an OCP using Class OptimalControlProblem

% Create an OptimalControlProblem object
OCP = OptimalControlProblem(1,... % dim of inputs
                            2,... % dim of states
                            0,... % dim of parameters
                            12);  % N: num of discritization grids

% Set the prediction horizon T
OCP.setT(1);

% Set the dynamic function f
a = -1;
b = -1;
f = [OCP.x(2); a * OCP.x(1) + b * OCP.x(2) * OCP.u(1)];
OCP.setf(f);
OCP.setDiscretizationMethod('Euler');

% Set the cost function L
Q    = diag([10, 10]);
R    = 0.01;
xRef = [0;0];
uRef = 0.5;
L    =  0.5*(OCP.x-xRef).'*Q*(OCP.x-xRef)...
       +0.5*(OCP.u-uRef).'*R*(OCP.u-uRef);
OCP.setL(L);

% Set the linear constraints G(u,x,p)>=0
G = [OCP.u(1);...
     1 - OCP.u(1)];
OCP.setG(G);

% Generate necessary files
OCP.codeGen();
%% Configrate the solver using Class NMPCSolver

% Create a NMPCSolver object
nmpcSolver = NMPCSolver(OCP);

% Configurate the Hessian approximation method
nmpcSolver.setHessianApproximation('Newton');

% Generate necessary files
nmpcSolver.codeGen();
%% Solve the very first OCP for a given initial state and given parameters using Class OCPSolver

% Set the initial state
x0 =   [1;0];

% Set the parameters
dim = OCP.dim;
N   = OCP.N;
p   = zeros(dim.p,N);

% Solve the very first OCP
solutionInitGuess.lambda = [randn(dim.lambda,1),zeros(dim.lambda,1)];
solutionInitGuess.mu     = randn(dim.mu,1);
solutionInitGuess.u      = uRef;
solutionInitGuess.x      = [x0,xRef];
solutionInitGuess.z      = ones(dim.z,N);
solution = NMPC_SolveOffline(x0,p,solutionInitGuess,1e-4,1000);

plot(solution.x(1,:).');

% Save to file
save GEN_initData.mat dim x0 p N

% Set initial guess
global ParNMPCGlobalVariable
ParNMPCGlobalVariable.solutionInitGuess = solution;
%% Define the controlled plant using Class DynamicSystem

% M(u,x,p) \dot(x) = f(u,x,p)
% Create a DynamicSystem object
plant = DynamicSystem(1,2,0);

g = 9.81;
a = -1;
b = -1;
fPlant = [plant.x(2); a * plant.x(1) + b * plant.x(2) * plant.u(1)];

% Set the dynamic function f
plant.setf(fPlant); % same model

% Generate necessary files
plant.codeGen();


%SVMR SVM regression
%
%      W = SVMR(X,NU,KTYPE,KPAR,EP)
%      W = X*SVMR([],NU,KTYPE,KPAR,EP)
%      W = X*SVMR(NU,KTYPE,KPAR,EP)
%
% INPUT
%   X      Regression dataset
%   NU     Fraction of objects outside the 'data tube'
%   KTYPE  Kernel type (default KTYPE='p', for polynomial)
%   KPAR   Extra parameter for the kernel
%   EP     Epsilon, with of the 'data tube'
%
% OUTPUT
%   W      Support vector regression
%
% DESCRIPTION
% Train an nu-Support Vector Regression on dataset X with parameter NU.
% The kernel is defined by kernel type KTYPE and kernel parameter KPAR.
% For the definitions of these kernels, have a look at proxm.m.
%
% SEE ALSO (PRTools Guide)
%  LINEARR, PROXM, GPR, SVC

% Copyright: D.M.J. Tax, D.M.J.Tax@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function y = svmr(varargin)

	argin = shiftargin(varargin,{'scalar','char'},1);
	argin = shiftargin(argin,'char',2);
  argin = setdefaults(argin,[],0.01,'p',1,0.2);

  if mapping_task(argin,'definition')
    y = define_mapping(argin,'untrained');
    y = setname(y,'SVM regression');

  elseif mapping_task(argin,'training')			% Train a mapping.

    [x,nu,ktype,kpar,ep] = deal(argin{:});
    [n,d] = size(x);
    y = gettargets(x);
    % kernel mapping:
    wk = proxm(+x,ktype,kpar);
    K = +(x*wk);
    % setup optimization:
    tol = 1e-6;
    C = 1/(n*nu);
    H = [K -K; -K K];
    f = repmat(ep,2*n,1) - [y; -y];
    A = [];
    b = [];
    Aeq = [ones(1,n) -ones(1,n)];
    beq = 0;
    lb = zeros(2*n,1);
    ub = repmat(C,2*n,1);
    %do the optimization:
    if exist('qld')
      alf = qld(H,f,Aeq,beq,lb,ub,[],1);
    else
      alf = quadprog(H,f,A,b,Aeq,beq,lb,ub);
    end
    % find SV's
    w = alf(1:n)-alf((n+1):end);  % the real weights
    Isv = find(abs(w)>tol);
    Ibnd = find(abs(w(Isv))<C-tol);
    % for the 'real' sv's, we want the classifier output to compute the
    % offset:
    I = Isv(Ibnd);
    out1 = sum(repmat(w',length(Ibnd),1).*K(I,:),2);
    sw = sign(w);
    out = y(I) - out1 - sw(I).*ep;

    % store the useful parameters:
    W.b = mean(out);
    W.wk = proxm(+x(Isv,:),ktype,kpar);
    W.w = w(Isv);

    y = prmapping(mfilename,'trained',W,1,d,1);
    y = setname(y,'Linear regression');
  else
    % evaluation
    [x,v] = deal(argin{1:2});
    W = getdata(v);
    [n,d] = size(x);
    Kz = +(x*W.wk);
    out = sum(repmat(W.w',n,1).*Kz,2) + repmat(W.b,n,1);
    y = setdat(x,out);

  end

return


function a = rutis3 ( )

%*****************************************************************************80
%
%% RUTIS3 returns the RUTIS3 matrix.
%
%  Example:
%
%    4 -5  0  3
%    0  4 -3 -5
%    5 -3  4  0
%    3  0  5  4
%
%  Properties:
%
%    A is not symmetric: A' /= A.
%
%    A is integral, therefore det ( A ) is integral, and
%    det ( A ) * inverse ( A ) is integral.
%
%    A has distinct eigenvalues.
%
%    A has a pair of complex eigenvalues.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Joan Westlake,
%    A Handbook of Numerical Matrix Inversion and Solution of
%    Linear Equations,
%    John Wiley, 1968,
%    ISBN13: 978-0471936756,
%    LC: QA263.W47.
%
%  Parameters:
%
%    Output, real A(4,4), the matrix.
%

%
%  Note that the matrix entries are listed by row.
%
  a(1:4,1:4) = [ ...
    4.0, -5.0,  0.0,  3.0; ...
    0.0,  4.0, -3.0, -5.0; ...
    5.0, -3.0,  4.0,  0.0; ...
    3.0,  0.0,  5.0,  4.0 ];

  return
end


function bessel_j0_int_values_test ( )

%*****************************************************************************80
%
%% BESSEL_J0_INT_VALUES_TEST demonstrates the use of BESSEL_JO_INT_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BESSEL_J0_INT_VALUES_TEST:\n' );
  fprintf ( 1, '  BESSEL_J0_INT_VALUES stores values of \n' );
  fprintf ( 1, '  the integral of the Bessel function J0.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      X           FX\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

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

    if ( n_data == 0 )
      break
    end

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

  end

  return
end


function jd=mjd2jd(mjd)
% MJD2JD  Converts Modified Julian Date to Julian Date.
%   Non-vectorized version. See also CAL2JD, DOY2JD, GPS2JD,
%   JD2CAL, JD2DOW, JD2DOY, JD2GPS, JD2MJD, JD2YR, YR2JD.
% Version: 2010-03-25
% Usage:   jd=mjd2jd(mjd)
% Input:   mjd - Modified Julian date
% Output:  jd  - Julian date

% Copyright (c) 2011, Michael R. Craymer
% All rights reserved.
% Email: mike@craymer.com

if nargin ~= 1
  warning('Incorrect number of arguments');
  return;
end

jd=mjd+2400000.5;


function [ f1, f2, f3 ] = feature_all( img )

if(ndims(img)==3)
    img=rgb2gray(img);
end

im1=im2double(img);

% Scale factor is 3
h=fspecial('gaussian',3);
im_f=double(imfilter(im1,h));
im2 = im_f(2:2:end,2:2:end);

h=fspecial('gaussian',3);
im_f=double(imfilter(im2,h));
im3 = im_f(2:2:end,2:2:end);

t1=block_dct(im1);
t2=block_dct(im2);
t3=block_dct(im3);

f1=[t1 t2 t3];

f2=global_gsm(img);

col=im2col(im1,[5 5],'distinct');
t1=svd(col);
col=im2col(im2,[5 5],'distinct');
t2=svd(col);
col=im2col(im3,[5 5],'distinct');
t3=svd(col);
f3=[t1 t2 t3];

end


%{

This code is to render a Mesh given a 3x4 camera matrix with an image resolution widthxheight. The rendering result is an ID map for facets, edges and vertices. This can usually used for occlusion testing in texture mapping a model from an image, such as the texture mapping in the following two papers.

--Jianxiong Xiao http://mit.edu/jxiao/

Citation:

[1] J. Xiao, T. Fang, P. Zhao, M. Lhuillier, and L. Quan
Image-based Street-side City Modeling
ACM Transaction on Graphics (TOG), Volume 28, Number 5
Proceedings of ACM SIGGRAPH Asia 2009

[2] J. Xiao, T. Fang, P. Tan, P. Zhao, E. Ofek, and L. Quan
Image-based Facade Modeling
ACM Transaction on Graphics (TOG), Volume 27, Number 5
Proceedings of ACM SIGGRAPH Asia 2008

%}

clear
clc

syms P00 P01 P02 P03 P10 P11 P12 P13 P20 P21 P22 P23
syms m_far m_near m_width m_height scale

projection = [P00 P01 P02 P03; P10 P11 P12 P13; P20 P21 P22 P23; 0 0 0 1];

% handle the near and far clip plane in OpenGL
protr = [1.0, 0.0, 0.0, 0.0;
    0.0, 1.0, 0.0, 0.0;
    0.0, 0.0, m_far / (m_far - m_near), - m_near * m_far /(m_far - m_near);
    0.0, 0.0, 1.0, 0.0];

% handle half pixel inconsistency
offset = [1.0, 0.0, 0.5, 0.0;
    0.0, 1.0, 0.5, 0.0;
    0.0, 0.0, 1.0, 0.0;
    0.0, 0.0, 0.0, 1.0];

% undo image aspect ratio and size
m0 = [m_width / 2, 0.0,         0.0, 0 + m_width / 2.0;
    0.0,        m_height / 2, 0.0, 0 + m_height / 2.0;
    0.0,        0.0,         0.5, 0.5;
    0.0,        0.0,         0.0, 1.0];

% handle scaling
m1=[1 / scale,   0.0,         0.0,                0.0;
    0.0,        1 / scale,    0.0,                0.0;
    0.0,        0.0,         1.0,                0.0;
    0.0,        0.0,         0.0,                1.0];

% handle upside down in vertical direction in image
m2=[1,           0.0,         0.0,                0.0;
    0.0,        -1.0,        m_height,            0.0;
    0.0,        0.0,         1.0,                0.0;
    0.0,        0.0,         0.0,                1.0];

M = (m0 \ protr * m2 * m1 * offset * projection);

M =

[     P20*(1/(m_width*scale) - 1) + (2*P00)/(m_width*scale),     P21*(1/(m_width*scale) - 1) + (2*P01)/(m_width*scale),     P22*(1/(m_width*scale) - 1) + (2*P02)/(m_width*scale),                       P23*(1/(m_width*scale) - 1) + (2*P03)/(m_width*scale)]
[ - P20*(1/(m_height*scale) - 1) - (2*P10)/(m_height*scale), - P21*(1/(m_height*scale) - 1) - (2*P11)/(m_height*scale), - P22*(1/(m_height*scale) - 1) - (2*P12)/(m_height*scale),                   - P23*(1/(m_height*scale) - 1) - (2*P13)/(m_height*scale)]
[                   (P20*(m_far + m_near))/(m_far - m_near),                   (P21*(m_far + m_near))/(m_far - m_near),                   (P22*(m_far + m_near))/(m_far - m_near), (P23*(m_far + m_near))/(m_far - m_near) - (2*m_far*m_near)/(m_far - m_near)]
[                                                       P20,                                                       P21,                                                       P22,                                                                         P23]

inv_width_scale  = 1/(m_width*scale);
inv_height_scale = 1/(m_height*scale);
inv_width_scale_1 =inv_width_scale - 1;
inv_height_scale_1_s = -(inv_height_scale - 1);
inv_width_scale_2 = inv_width_scale*2;
inv_height_scale_2_s = -inv_height_scale*2;
m_far_a_m_near = m_far + m_near;
m_far_s_m_near = m_far - m_near;
m_far_d_m_near = m_far_a_m_near/m_far_s_m_near;

M =
[     P20*(inv_width_scale - 1) + (2*P00)*inv_width_scale,   P21*(inv_width_scale - 1) + (2*P01)*inv_width_scale  , P22*(inv_width_scale - 1) + (2*P02)*inv_width_scale    ,                       P23*(inv_width_scale - 1) + (2*P03)*inv_width_scale]
[ - P20*(inv_height_scale - 1) - (2*P10)*inv_height_scale, - P21*(inv_height_scale - 1) - (2*P11)*inv_height_scale, - P22*(inv_height_scale - 1) - (2*P12)*inv_height_scale,                   - P23*(inv_height_scale - 1) - (2*P13)*inv_height_scale]
[                   (P20*m_far_a_m_near)/m_far_s_m_near,                   (P21*m_far_a_m_near)/m_far_s_m_near,                   (P22*m_far_a_m_near)/m_far_s_m_near, (P23*m_far_a_m_near)/m_far_s_m_near - (2*m_far*m_near)/m_far_s_m_near]
[                                                       P20,                                                       P21,                                                       P22,                                                                         P23]

% final OpenGL matrix = M'
% column 1
P20*inv_width_scale_1 + P00*inv_width_scale_2,
P21*inv_width_scale_1 + P01*inv_width_scale_2,
P22*inv_width_scale_1 + P02*inv_width_scale_2,
P23*inv_width_scale_1 + P03*inv_width_scale_2,

% column 2
P20*inv_height_scale_1_s + P10*inv_height_scale_2_s,
P21*inv_height_scale_1_s + P11*inv_height_scale_2_s,
P22*inv_height_scale_1_s + P12*inv_height_scale_2_s,
P23*inv_height_scale_1_s + P13*inv_height_scale_2_s,

% column 3
P20*m_far_d_m_near,
P21*m_far_d_m_near,
P22*m_far_d_m_near,
P23*m_far_d_m_near - (2*m_far*m_near)/m_far_s_m_near,
% column 4
 P20
 P21
 P22
 P23

% final matrix to opengl

P20*inv_width_scale_1 + P00*inv_width_scale_2,  P20*inv_height_scale_1_s + P10*inv_height_scale_2_s,    P20*m_far_d_m_near,     P20,
P21*inv_width_scale_1 + P01*inv_width_scale_2,  P21*inv_height_scale_1_s + P11*inv_height_scale_2_s,    P21*m_far_d_m_near,     P21,
P22*inv_width_scale_1 + P02*inv_width_scale_2,  P22*inv_height_scale_1_s + P12*inv_height_scale_2_s,    P22*m_far_d_m_near,     P22,
P23*inv_width_scale_1 + P03*inv_width_scale_2,  P23*inv_height_scale_1_s + P13*inv_height_scale_2_s,    P23*m_far_d_m_near - (2*m_far*m_near)/m_far_s_m_near,   P23

inv_width_scale  = 1/(m_width*scale);
inv_height_scale = 1/(m_height*scale);
inv_width_scale_1 =inv_width_scale - 1;
inv_height_scale_1_s = -(inv_height_scale - 1);
inv_width_scale_2 = inv_width_scale*2;
inv_height_scale_2_s = -inv_height_scale*2;
m_far_a_m_near = m_far + m_near;
m_far_s_m_near = m_far - m_near;
m_far_d_m_near = m_far_a_m_near/m_far_s_m_near;


function lambda = gear_eigenvalues ( ii, jj, n )

%*****************************************************************************80
%
%% GEAR_EIGENVALUES returns the eigenvalues of the GEAR matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer II, JJ, define the two special entries.
%
%    Input, integer N, the order of A.
%
%    Output, real LAMBDA(N,1), the eigenvalues.
%
  lambda = zeros ( n, 1 );
%
%  Separate the sign and value.
%
  alpha = zeros ( n, 1 );

  j = abs ( ii );
  js = i4_sign ( ii );

  k = abs ( jj );
  ks = i4_sign ( jj );

  if ( 0 < js & 0 < ks )

    w = 0;

    phi = n - floor ( ( j + k ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = 2 * p * pi / ( 2 * n + 2 - j - k );
    end

    phi = floor ( ( j - 1 ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = 2 * p * pi / j;
    end

    phi = floor ( ( k - 1 ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = 2 * p * pi / k;
    end

    w = w + 1;
    alpha(w) = 0.0;

    if ( i4_is_even ( j ) & i4_is_even ( k ) )
      w = w + 1;
      alpha(w) = pi;
    end

  elseif ( 0 < js & ks < 0 )

    w = 0;

    phi = n + 1 - floor ( (j+k+1) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = ( 2 * p - 1 ) * pi / ( 2 * n + 2 - j - k );
    end

    phi = floor ( ( j - 1 ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = 2 * p * pi / j;
    end

    phi = floor ( k / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = ( 2 * p - 1 ) * pi / k;
    end

    if ( i4_is_even ( j ) & i4_is_odd ( k ) )
      w = w + 1;
      alpha(w) = pi;
    end

  elseif ( js < 0 & 0 < ks )

    w = 0;

    phi = n + 1 - floor ( ( j + k + 1 ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = ( 2 * p - 1 ) * pi / ( 2 * n + 2 - j - k );
    end

    phi = floor ( j / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = ( 2 * p - 1 ) * pi / j;
    end

    phi = floor ( ( k - 1 ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = 2 * p * pi / k;
    end

    if ( i4_is_odd ( j ) & i4_is_even ( k ) )
      w = w + 1;
      alpha(w) = pi;
    end

  elseif ( js < 0 & ks < 0 )

    w = 0;

    phi = n - floor ( ( j + k ) / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = 2 * p * pi / ( 2 * n + 2 - j - k );
    end

    phi = floor ( j / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = ( 2 * p - 1 ) * pi / j;
    end

    phi = floor ( k / 2 );
    for p = 1 : phi
      w = w + 1;
      alpha(w) = ( 2 * p - 1 ) * pi / k;
    end

    if ( i4_is_odd ( j ) & i4_is_odd ( k ) )
      w = w + 1;
      alpha(w) = pi;
    end

  end

  for w = 1 : n
    lambda(w,1) = 2.0 * cos ( alpha(w) );
  end

  return
end


function [varargout]=patchEdgeAngles(F,V)

% function [A,Ad]=patchEdgeAngles(F,V)
% -----------------------------------------------------------------------
% Computes the edge angles (A) for the patch data specified by the faces
% (F) and vertices (V) arrays.
%
%
% See also:
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2015/08/18
%------------------------------------------------------------------------

%%

numNodes=size(F,2);

A=zeros(size(F));
for q=1:1:numNodes

    q1=q;
    q0=q-1;
    if q0<1
        q0=numNodes;
    end
    q2=q+1;
    if q2>numNodes
        q2=1;
    end

    P0=V(F(:,q0),:)-V(F(:,q1),:);
    P0=vecnormalize(P0);
    P2=V(F(:,q2),:)-V(F(:,q1),:);
    P2=vecnormalize(P2);
    A(:,q)=acos(dot(P0,P2,2));

end

varargout{1}=A;

if nargout>1
    varargout{2}=180*(A./pi);
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function [policy, iter, cpu_time] = mdp_value_iteration(P, R, discount, epsilon, max_iter, V0)

% mdp_value_iteration   Resolution of discounted MDP with value iteration algorithm
% Arguments --------------------------------------------------------------
% Let S = number of states, A = number of actions
%   P(SxSxA)  = transition matrix
%              P could be an array with 3 dimensions or
%              a cell array (1xA), each cell containing a matrix (SxS) possibly sparse
%   R(SxSxA) or (SxA) = reward matrix
%              R could be an array with 3 dimensions (SxSxA) or
%              a cell array (1xA), each cell containing a sparse matrix (SxS) or
%              a 2D array(SxA) possibly sparse
%   discount  = discount rate in ]0; 1]
%               beware to check conditions of convergence for discount = 1.
%   epsilon   = epsilon-optimal policy search, upper than 0,
%               optional (default : 0.01)
%   max_iter  = maximum number of iteration to be done, upper than 0,
%               optional (default : computed)
%   V0(S)     = starting value function, optional (default : zeros(S,1))
% Evaluation -------------------------------------------------------------
%   policy(S) = epsilon-optimal policy
%   iter      = number of done iterations
%   cpu_time  = used CPU time
%--------------------------------------------------------------------------
% In verbose mode, at each iteration, displays the variation of V
% and the condition which stopped iterations: epsilon-optimum policy found
% or maximum number of iterations reached.

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

cpu_time = cputime;

global mdp_VERBOSE;

% check of arguments
if iscell(P); S = size(P{1},1); else S = size(P,1); end;
if discount <= 0 || discount > 1
    disp('--------------------------------------------------------')
    disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1]')
    disp('--------------------------------------------------------')
elseif nargin > 3 && (epsilon <= 0)
    disp('--------------------------------------------------------')
    disp('MDP Toolbox ERROR: epsilon must be upper than 0')
    disp('--------------------------------------------------------')
elseif nargin > 4 && max_iter <= 0
    disp('--------------------------------------------------------')
    disp('MDP Toolbox ERROR: The maximum number of iteration must be upper than 0')
    disp('--------------------------------------------------------')
elseif nargin > 5 && size(V0,1) ~= S
    disp('--------------------------------------------------------')
    disp('MDP Toolbox ERROR: V0 must have the same dimension as P')
    disp('--------------------------------------------------------')
else

    if discount == 1
        disp('--------------------------------------------------------')
        disp('MDP Toolbox WARNING: check conditions of convergence.')
        disp('With no discount, convergence is not always assumed.')
        disp('--------------------------------------------------------')
    end;

    PR = mdp_computePR(P,R);

    % initialization of optional arguments
    if nargin < 6; V0 = zeros(S,1); end;
    if nargin < 4; epsilon = 0.01; end;
    % compute a bound for the number of iterations
    if discount ~= 1
       computed_max_iter = mdp_value_iteration_bound_iter(P, R, discount, epsilon, V0);
    end;
    if nargin < 5
        if discount ~= 1
            max_iter = computed_max_iter;
        else
            max_iter = 1000;
        end;
    else
        if discount ~= 1 && max_iter > computed_max_iter
            disp(['MDP Toolbox WARNING: max_iter is bounded by ' num2str(computed_max_iter,'%12.1f') ])
            max_iter = computed_max_iter;
        end;
    end;

    % computation of threshold of variation for V for an epsilon-optimal policy
    if discount ~= 1
        thresh = epsilon * (1-discount)/discount;
    else
        thresh = epsilon;
    end;

    if mdp_VERBOSE; disp('  Iteration    V_variation'); end;

    iter = 0;
    V = V0;
    is_done = false;
    while ~is_done
        iter = iter + 1;
        Vprev = V;

        [V, policy] = mdp_bellman_operator(P,PR,discount,V);

        variation = mdp_span(V - Vprev);
        if mdp_VERBOSE;
            disp(['      ' num2str(iter,'%5i') '         ' num2str(variation)]);
        end;
        if variation < thresh
            is_done = true;
            if mdp_VERBOSE
                disp('MDP Toolbox: iterations stopped, epsilon-optimal policy found')
            end;
        elseif iter == max_iter
            is_done = true;
            if mdp_VERBOSE
                disp('MDP Toolbox: iterations stopped by maximum number of iteration condition')
            end;
        end;
    end;

end;

cpu_time = cputime - cpu_time;


function [prob,sol,fmin] = qp_prob(varargin)
%QP_PROB  Return an OPTI QP
%
%   prob = qp_prob(no) return a pre-built optiprob of a saved QP.
%
%   [prob,sol,fmin] = qp_prob(no) returns the optimum solution and
%   function eval at the optimum
%
%   no = qp_prob() returns the number of problems available for testing.

%   (C) 2011 Jonathan Currie (IPL)

%Check if just returning no problems
if(nargin < 1)
    prob = 3; sol = []; fmin = [];
    return;
else
    no = varargin{1};
end

%Big switch yard
switch(no)
    case 1
        H = eye(3);
        f = -[2 3 1]';
        A = [1 1 1;3 -2 -3; 1 -3 2];
        b = [1;1;1];
        prob = optiprob('H',H,'f',f,'ineq',A,b);
        sol = [1/3;4/3;-2/3];
        fmin = -2.83333333301227;

    case 2
        H = [1 -1; -1 2];
        f = -[2 6]';
        A = [1 1; -1 2; 2 1];
        b = [2; 2; 3];
        lb = [0;0];
        prob = optiprob('H',H,'f',f,'ineq',A,b,'lb',lb);
        sol = [1/3;4/3];
        fmin = -8.22222220552525;

    case 3
        H = [1 -1; -1 2];
        f = -[2 6]';
        A = [1 1; -1 2; 2 1];
        b = [2; 2; 3];
        Aeq = [1 1.5];
        beq = 2;
        lb = [0;0];
        ub = [10;10];
        prob = optiprob('H',H,'f',f,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub);
        sol = [0.34482763667623;1.10344824221585];
        fmin = -6.41379310344827;

    otherwise
        error('Problem not available or not implemented yet');
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   R = euler2rot(abc, convention)
%   Returns the Rotation angle for three euler angles abc=[alpha beta gamma].
%
%   The convention specifies the order and axes of the rotations. For
%   example, for the 'XYZ' convention, we have
%   R = Rot(alpha,'x')*Rot(beta,'y')*Rot(gamma,'z')
%
%   Author: Arturo Gil. Universidad Miguel Hernandez de Elche. email:
%   arturo.gil@umh.es date:   11/11/2020
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
function [R] = euler2rot(abc, convention)

if convention =='XYZ'
    ax = abc(1);
    ay = abc(2);
    az = abc(3);

    Rx = Rot(ax, 'x');
    Ry = Rot(ay, 'y');
    Rz = Rot(az, 'z');

    R = Rx*Ry*Rz;
else
    'Unknown convention'
end


% RDIVIDE_LINTEST   Check that correct linearity information is returned for
% various operations with ./

function pass = test_lintest_rdivide()
%% Initialisation
x = chebfun(@(x) x);
u = adchebfun(x) + 2;
v = adchebfun(x) + 3;

%% One variable involved
pass = [];
w = u/2;
pass(length(pass) + 1) = w.linearity == 1;

w = u./(x+2);
pass(length(pass) + 1) = w.linearity == 1;

w = sin(u)./(x+2);
pass(length(pass) + 1) = w.linearity == 0;

w = 2./u;
pass(length(pass) + 1)  = w.linearity == 0;

w = x./u;
pass(length(pass) + 1)  = w.linearity == 0;

w = u./(u+2);
pass(length(pass) + 1)  = w.linearity == 0;

%% Two variables, but still only one in compuations
u = seed(u, 1, 2);
v = seed(v, 2, 2);
w = u/2;
pass(length(pass) + 1)  = all( w.linearity == [1 1]);

w = u./(x+2);
pass(length(pass) + 1)  = all( w.linearity == [1 1]);

w = sin(u)/2;
pass(length(pass) + 1)  = all( w.linearity == [0 1]);

w = 2./u;
pass(length(pass) + 1)  = all( w.linearity == [0 1]);

w = x./u;
pass(length(pass) + 1)  = all( w.linearity == [0 1]);

w = u./(u+2);
pass(length(pass) + 1)  = all( w.linearity == [0 1]);

%% Combination of variables
w = u./v;
pass(length(pass) + 1)  = all( w.linearity == [0 0]);

w = sin(u)./v;
pass(length(pass) + 1)  = all( w.linearity == [0 0]);

w = u./(u.*v);
pass(length(pass) + 1)  = all( w.linearity == [0 0]);

end


function [angle_SAM,map] = SAM(ref,tar)
%--------------------------------------------------------------------------
% Spectral angle mapper (SAM)
%
% USAGE
%   [angle_SAM,map] = SAM(msoriginal,msfused)
%
% INPUT
%   ref : reference HS data (rows,cols,bands)
%   tar : target HS data (rows,cols,bands)
%
% OUTPUT
%   angle_SAM : average SAM in degree (scalar)
%   map       : 2-D map of SAM
%
%--------------------------------------------------------------------------
[rows,cols,bands] = size(tar);
prod_scal = dot(ref,tar,3);
norm_orig = dot(ref,ref,3);
norm_fusa = dot(tar,tar,3);
prod_norm = sqrt(norm_orig.*norm_fusa);
prod_map = prod_norm;
prod_map(prod_map==0)=eps;
map = acos(prod_scal./prod_map);
prod_scal = reshape(prod_scal,rows*cols,1);
prod_norm = reshape(prod_norm, rows*cols,1);
z=find(prod_norm==0);
prod_scal(z)=[];prod_norm(z)=[];
angolo = sum(sum(acos(prod_scal./prod_norm)))/(size(prod_norm,1));
angle_SAM = real(angolo)*180/pi;

end


function [EccA] = vect_solveKepler(meanALL, eccALL)
%solveKepler Summary of this function goes here
%   Detailed explanation goes here.
    EccA = zeros(size(eccALL));
    tol = 1E-12;

    if(any(eccALL < 1))
        ecc = eccALL(eccALL < 1);
        mean = meanALL(eccALL < 1);

        mean = AngleZero2Pi(mean);

        E0 = zeros(size(mean));
        E1 = ones(size(mean)) * Inf;
        if(any(mean > pi))
            E0(mean > pi) = mean(mean > pi) - ecc(mean > pi);
        end
        if(any(mean <= pi))
            E0(mean <= pi) = mean(mean <= pi) + ecc(mean <= pi);
        end

        first = true;
        while(any(abs(E1 - E0) > tol))
            if(~first)
                E0 = E1;
            end
            E1 = E0 + (mean - E0 + ecc.*sin(E0))./(1-ecc.*cos(E0));
            if(first)
                first = false;
            end
        end
        EccA(eccALL < 1) = E1;
    end

    if(any(eccALL >= 1))
        ecc = eccALL(eccALL >= 1);
        mean = meanALL(eccALL >= 1);

        H0 = zeros(size(mean));
        H1 = ones(size(mean)) * Inf;

        if(any(ecc < 1.6))
            bool = (-pi < mean & mean < 0) | mean > pi;
            H0(bool) = mean(bool) - ecc(bool);
            H0(not(bool)) = mean(not(bool)) + ecc(not(bool));
        end
        if(any(ecc >= 1.6))
            bool = ecc<3.6 & abs(mean) > pi;
            H0(bool) = mean(bool) - sign(mean(bool)).*ecc(bool);
            H0(not(bool)) = mean(not(bool))./(ecc(not(bool))-1);
        end

        first = true;
        while(any(abs(H1 - H0) > tol))
            if(~first)
                H0 = H1;
            end
            H1 = H0 + (mean - ecc.*sinh(H0) + H0)./(ecc.*cosh(H0) - 1);

            if(any(isnan(H1))) %this code necessary to prevent Inf/Inf = NaN cases where H0 is very large and the sinh/cosh functions give Inf as an answer
                bool1 = isnan(H1) & -ecc.*sinh(H0) == Inf;
                bool2 = isnan(H1) & -ecc.*sinh(H0) == -Inf;

                H1(bool1) = H0(bool1) + ones(size(H0(bool1)));
                H1(bool2) = H0(bool2) - ones(size(H0(bool2)));
            end

            if(first)
                first = false;
            end
        end
        EccA(eccALL >= 1) = H1;
    end
end


function [ axisAngle ] = Rot2AxisAngle( Rot )
%ROT2AXISANGLE Summary of this function goes here
%   Detailed explanation goes here

    theta = acos((trace(Rot) - 1) / 2);

    vec = 1.0/(2*sin(theta));
    vec = vec * [Rot(3,2) - Rot(2,3), Rot(1,3) - Rot(3,1), Rot(2,1) - Rot(1,2)];
    axisAngle = vec * theta;
end


function pass = test_std2(pref)
% Test the chebfun3/max command.

if ( nargin < 1 )
    pref = chebfunpref;
end
tol = 1e3*pref.cheb3Prefs.chebfun3eps;

% Note that std(chebfun(@(x) x.^2)) = sqrt(4/45).

f1 = chebfun3(@(x,y,z) x.^2 + z); % f1 has (x,y)-std equal to sqrt(4/45).
f2 = chebfun3(@(x,y,z) z.^2 + y); % f2 has (x,z)-std equal to sqrt(4/45).
f3 = chebfun3(@(x,y,z) y.^2 + x); % f3 has (y,z)-std equal to sqrt(4/45).

exact = chebfun(@(x) sqrt(4/45)); % (x,y)-std of z equals 0.

h1 = std2(f1);
h2 = std2(f1,[],[1,2]);
h3 = std2(f2,[],[1,3]);
h4 = std2(f3,[],[3, 2]);

pass(1) = norm(h1 - exact) < tol;
pass(2) = norm(h2 - exact) < tol;
pass(3) = norm(h3 - exact) < tol;
pass(4) = norm(h4 - exact) < tol;

end


function [betaAngle] = patchFaceAngles(F,V)

% function [betaAngle] = patchFaceAngles(F,V)
% ------------------------------------------------------------------------
%
%
% 2018/11/14 Created
%
% ------------------------------------------------------------------------

%%
% Get connectivity matrices
connecticityStruct=patchConnectivity(F,V);
edgeVertexConnectivity=connecticityStruct.edge.vertex;
edgeFaceConnectivity=connecticityStruct.edge.face;
faceEdgeConnectivity=connecticityStruct.face.edge;
% vertexEdgeConnectivity=connecticityStruct.vertex.edge;

logicValid=all(edgeFaceConnectivity>0,2);

% Face normals
N=patchNormal(F,V);

% Create edge vectors
VE = V(edgeVertexConnectivity(:,1),:) - V(edgeVertexConnectivity(:,2),:); %Edge vector
edgeVectorLength = sqrt(sum(VE.^2,2)); %Length of edge vector
VE=VE./edgeVectorLength(:,ones(1,3)); %Normalized edge vector

% Compute the un-signed angle
betaAngle=nan(size(edgeFaceConnectivity,1),1);
betaAngle(logicValid) = real(acos(dot(N(edgeFaceConnectivity(logicValid,1),:),N(edgeFaceConnectivity(logicValid,2),:),2)));

% Fix sign of angle
cp = nan(size(edgeFaceConnectivity,1),3);
cp(logicValid,:) = cross(N(edgeFaceConnectivity(logicValid,1),:),N(edgeFaceConnectivity(logicValid,2),:),2);

si = sign(dot(cp,VE,2));
% si(abs(si)<eps)=1;

betaAngle=pi+(betaAngle.*si);

betaAngle=betaAngle(faceEdgeConnectivity);

end
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function [sg] = g_convSig_approx(x,P,u,in)
% this function evaluates a logistic convolution of the inputs
% function [gx,dgdx,dgdp] = g_convSig(x,P,u,in)
% This function evaluates the following multiple convolution model:
%   p(y(t)=1) = sigm(cst + sum_k sum_tau w(k,tau)*u(k,t-tau))
% where u can be of any dimension (k=1,...,K), and sigm is the standard
% sigmoid mapping. This logistic convolution model is useful for binary
% observations.
% Note that the convolution (Volterra) kernels are constructed from the
% parameters' vector P. The size of the parameters' vector P is determined
% by the maximum lag (tau) considered.
% IN:
%   - x: [useless]
%   - P: (K*maxLag+1)x1 vector of kernel parameters.
%   - u: (K*nt)x1 vectorized input to the system
%   - in: [useless]
% OUT:
%   - sg: the predicted system's output (in terms of p(y(t)=1))
%   - dsdx: [useless]
%   - dsdp: the gradient of the system's output w.r.t. kernel parameters
% SEE ALSO: g_conv0

% [g,~,dgdp] = g_conv_approx(x,P,u,in);
g = g_conv_approx(x,P,u,in);
sg = VBA_sigmoid(g);

% dsdx = [];
% dsdp = dgdp*diag(sg.*(1-sg));


% 股票预测问题 by 曲线拟合
%% 历史数据处理
clear;clc;
x = [2,3,4,5,8,9,10,11,12,15,16,17,18,19,22,23,24,25,26,29,30]; % 时间
y = [7.74,7.84,7.82,7.78,7.91, 7.97,7.9,7.76,7.9,8.04,8.06, 8.11,8.08,8.13,8.03,8.01,8.06,8.0,8.3,8.41,8.28];  % 当天收盘价

p=polyfit(x,y,3);  % 多项式拟合，返回次数为 3 的多项式 p(x) 的系数，该阶数是 y 中数据的最佳拟合（在最小二乘方式中）。p 中的系数按降幂排列，p 的长度为 n+1
plot(x,y,'*',x,polyval(p,x));

%% 开始预测
x1=[31,32,33];   % 待预测时间
xi=[x,x1];
y1=[8.27,8.17,9.54];  %  该股票后三个交易日的收盘价分别为8.27,8.17,9.54
plot(x,y,'*',xi,polyval(p,xi),x1,y1,'rp');
% 结论：预测结果仅供参考


function r8_atanh_test ( )

%*****************************************************************************80
%
%% R8_ATANH_TEST tests R8_ATANH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2008
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8_ATANH_TEST\n' );
  fprintf ( 1, '  R8_ATANH computes the inverse hyperbolic tangent\n' );
  fprintf ( 1, '  of a given value.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '        X        R8_ATANH(X)  TANH(R8_ATANH(X))\n' );
  fprintf ( 1, '\n' );

  for i = -2 : 9
    x = i / 10.0;
    a = r8_atanh ( x );
    x2 = tanh ( a );
    fprintf ( 1, '  %12f  %12f  %12f\n', x, a, x2 );
  end

  return
end


function [xDistSort,yDistSort]=sortPointMinDist(x,y)
%% function [xDistSort,yDistSort]=sortPointMinDist(x,y)
% Sorts arbitrary points into a Clock Wise contour.
%
%% Syntax
% [xDistSort,yDistSort]=sortPointMinDist(x,y)
%
%% Description
% This functions goal is to order points efficintly to allow plotting a contoure with
% them. While this problem can be hard to solve, and even sometimes considered unsolvable,
% it is solved here basing on the assumption that "nearest point" is the nect point. This
% results in a solution of O(N^2) complexity (calculating all distamnces between points),
% but im most cases it will be of significantly lower complexity.
%
%% Input arguments:
% x- x coordinates of the points
%
% y- x coordinates of the points
%
%% Output arguments
% xDistSort- sorted points x coordinates.
%
% yDistSort- sorted points y coordinates.
%
%% Issues & Comments (None)
% The resulting shape will have points connected,accordung to a predfined metric, so it
% will not always result in a shape user wished for. Add additonal points to fix this
% issue, when needed.
% The funciton is pretty damandig computationally (~20 slower than sortPoint2ContourCW),
% so should be used not too frequently.
%
%% Example
% N=11;
% x=10*rand(1,N);
% y=10*rand(1,N);
% [xCW,yCW]=sortPointMinDist(x,y);
% figure;
% plot(x,y,'.-b');
% hold on;
% plot(xCW,yCW,'.-r','LineWidth',2);
% hold off;
% axis equal;
% title('Sorting arbitrary Points to form a Contour','FontSize',14);
% legend('Unsorted points contour', 'Sorted points contour');
%
%% See also
% sortPoint2ContourCW;  % Custom function
% mask2poly;            % Custom function
% poly2mask;            % Matlab function
%
%% Revision history
% First version: Nikolay S. 2011-07-24.
% Last update:   Nikolay S. 2011-07-25.
%
% *List of Changes:*
%

%% convert to column vectors and sort
nPoints=length(x);
iDistSort=zeros(1,nPoints);
distMat=Inf(nPoints,nPoints); % col index- distance from, row index- distance to

for iDistRow=1:nPoints
   ind2=(iDistRow+1):nPoints;
   distMat(iDistRow, ind2)=sqrt((x(ind2)-x(iDistRow)).^2+(y(ind2)-y(iDistRow)).^2);
   % distance between a->b eqauls distance between b->a
   distMat(ind2, iDistRow)=transpose(distMat(iDistRow, ind2));
end

% find pair of closest points- first and second points
[~,pointLinInd] = min(distMat(:));
[iDistSort(1),nextPoint] = ind2sub(size(distMat), pointLinInd);
for iPoint=1:nPoints-1
   currPoint=nextPoint;
   [minDist,nextPoint] = min(distMat(currPoint, :)); % find next point- closest to current
   distMat(currPoint,:)=Inf; % delete distances from current point
   distMat(:,currPoint)=Inf; % delete distances to   current point
   iDistSort(iPoint+1)=nextPoint; % store sorted points indexes

   if isinf(minDist) % this will b true in case of an error
      break;
   end
end
xDistSort=x(iDistSort);
yDistSort=y(iDistSort);


function [u,x]=SFrontTrack(u0,x0,T,u_flux,f_flux);
% Doing front tracking on the initial fronts defined by (u0,x0) in the
% time interval [0 T]. The piecewise linear flux function is in (u_flux,
% f_flux). u0 must take values in the set {u_flux}.
% This version plots the fronts as the Riemann problmes are solved.

[u s t_coll,x]=Sinitialize(u0,x0,T,u_flux,f_flux);
% Initializes the collision times.
t_start=zeros(size(x));
asm=mean(abs(s));
xlower=min([x(1)-asm*T,x(1)]);
xhigher=max([x(length(x))+asm*T,x(length(x))]);
if xlower==xhigher
  xlower=xhigher-0.5;
  xhigher=xlower+1;
end;
axis([xlower xhigher 0 T]);
set(gca,'Box','on');
%axes('XLim',[xlower xhigher],'YLim',[0 T],'Box','on');
hold on;
[t i]=min(t_coll);
while t<T&~isempty(s),  % The main loop until no more collisions ...
  [ncr nu]=size(u);
  nx=length(x);
  if nx~=nu-1,
    [nx nu];
    error('Wrong length of x vs u in FrontTrack');
  end;
  xc=x(i)+s(i)*(t-t_start(i));
  line([x(i) xc],[t_start(i) t]);       % Plotting the lines to the
  line([x(i-1) xc],[t_start(i-1) t]);   % collision about to be solved
  [ur sr]=SRiemannsol(u(:,i-1),u(:,i+1),u_flux,f_flux);  % Solving the RP
  [nc nr]=size(ur);
  ns=length(sr);
  if ns>0,
    if i>2,
      t_coll(i-1)=collision_time([s(i-2) sr(1)],[t_start(i-2),t],...
                                 [x(i-2),xc],T+1);
      if t_coll(i-1)<=t,     % The collision is not after present time.
        [-1 t_coll(i-1) t]   % Fatal error.
        [s(i-2) sr(1) t_start(i-2) t]
        error('not increasing t_coll : a');
      end;
    end;
    if i<nu-1,
      t_coll(i+1)=collision_time([sr(ns),s(i+1)],[t,t_start(i+1)],...
                                 [xc,x(i+1)],T+1);
      if t_coll(i+1)<=t,  % The collision is not after present time.
        [1 t_coll(i+1) t] % Fatal error.
        [sr(ns) s(i+1)]
        error('not increasing t_coll: b ');
      end;
    end;
  else
    if i>2&i<nu-1,
      t_coll(i-1)=collision_time([s(i-2) s(i+1)],...
                                 [t_start(i-2),t_start(i+1)],...
                                 [x(i-2),x(i+1)],T+1);
    end;
  end;
  u=[u(:,1:i-1) ur u(:,i+1:nu)];    % Managing the lists ...
  s=[s(1:i-2) sr s(i+1:nu-1)];
  hone=ones([1,ns]);
  x=[x(1:i-2) xc*hone x(i+1:nu-1)];
  t_start=[t_start(1:i-2) t*hone t_start(i+1:nu-1)];
  t_coll=[t_coll(1:i-1) (T+1)*ones([1,nr]) t_coll(i+1:nu)];
  [t i]=min(t_coll);
end;
n=length(x);
for i=1:n  % Drawing the fronts up to final time T
  line([x(i),x(i)+s(i)*(T-t_start(i))],[t_start(i) T]);
end;
x=x+s.*(T-t_start);
hold off;


function Bd = getBd(phi, h, d)

% getBd: get the B-matrix as in equation (16) and Lemma 2
%
% Usage:    Bd = getBd(phi, h, d)
%
% INPUTS:
%       phi: a cell containing all the systems Phi_i(s)
%       h: the fast sampling interval
%       d: the vector of fractional delays
%
% OUTPUT:
%       Bd: matrix Bd as in equation (16)
%
% SEE ALSO: getAd, getCd

N = length(d);

% Compute for the block not containing Q0 and R0
BB = [];

for i = 1:N
    Ai = phi{i+1}{1};
    Bi = phi{i+1}{2};
    Ci = phi{i+1}{3};

    % Column i of BB
    BBi = [];

    % Concatenate Delta_ij to get row i
    for j = 1:N
        if ( i <= j)
            Aj = phi{j+1}{1};
            Bj = phi{j+1}{2};
            Cj = phi{j+1}{3};

            QQ = MVL(Ai, Bi, Aj, Bj, h);
            QR =   expm(d(j)*Aj) * MVL(Ai, Bi, Aj, Bj, h-d(j)) * Cj' ;
            RQ = ( expm(d(i)*Ai) * MVL(Aj, Bj, Ai, Bi, h-d(i)) * Ci' )' ;   % Transpose of QR above

            if (d(i) < d(j))
                RR = Ci * expm( (d(j)-d(i)) * Ai) * MVL(Ai, Bi, Aj, Bj, h-d(j)) * Cj' ;
            else
                RR = Ci * MVL(Ai, Bi, Aj, Bj, h-d(i)) * expm( (d(i)-d(j)) * Ai') * Cj' ;
            end

            BBij = [QQ, QR;
                    RQ, RR];

            BBi = [BBi BBij];
        else
            Aj = phi{j+1}{1};
            Bj = phi{j+1}{2};
            Cj = phi{j+1}{3};

            % position of this block BBij
            sc = size(BBi, 2) + 1;          % Starting column
            wc = size(Aj,1) + size(Cj,1);   % Number of column in this block
            sr = size(BB, 1) + 1;           % Starting row
            wr = size(Ai,1) + size(Ci,1);   % Number of row in this block

            % To save computation, we use Delta_ji'
            BBi = [BBi BB(sc:(sc+wc-1), sr:(sr+wr-1))'];
        end
    end

    BB = [BB; BBi];
end

% column 0 of BB, except the first block Q0*Q0'
BB0 = [];

A0 = phi{1}{1};
B0 = phi{1}{2};
C0 = phi{1}{3};

for i = 1:N
    Ai = phi{i+1}{1};
    Bi = phi{i+1}{2};
    Ci = phi{i+1}{3};

    QQ = MVL(A0, B0, Ai, Bi, h);
    QR = expm(d(i)*Ai) * MVL(A0, B0, Ai, Bi, h-d(i)) * Ci' ;

    BB0 = [BB0 QQ QR];
end

QQ0 = MVL(A0, B0, A0, B0, h);

BB = [QQ0   BB0;
      BB0'  BB];

Bd = real(sqrtm(BB));


function squareStokesP1P0
%STOKE Summary of this function goes here
%   Detailed explanation goes here

close all; clear all; clc;
%figure(1); set(gcf,'Units','normal'); set(gcf,'Position',[0,0,0.7,0.75]);
%---------------------- Parameters ----------------------------------------
maxIt = 3; N = zeros(maxIt,1);
erru = zeros(maxIt,1);  errp = zeros(maxIt,1);
%---------------------- Generate initial mesh -----------------------------
node = [0,0; 1,0; 1,1; 0,1];    % nodes
elem = [2,3,1; 4,1,3];          % elements
for k = 1:3
    [node,elem] = uniformbisect(node,elem);
end
%% pde
pde.f = @f; pde.g_D = @g_D; pde.p=@exactp;
%---------------------- Finite Element Method -----------------------------
%
for k = 1:maxIt
    [node,elem] = uniformbisect(node,elem);
    [u,p,A,nodeRefine,nodeFine,elemFine] = mgStokesP1P0TwolevelNew(node,elem,pde);
    N(k) = length(u) + length(p);
    uI = exactu(nodeRefine);
    erru(k) = sqrt((u-uI(:))'*A{2}*(u-uI(:)));
    center = (nodeFine(elemFine(:,1),:)+nodeFine(elemFine(:,2),:)+nodeFine(elemFine(:,3),:))/3;
    pI = exactp(center);
    pI = pI-pI(end);
    errp(k)=max(abs(p-pI));
%     errp(k) = norm(p - pI)/sqrt(N);
    fprintf('erru = %6.3g, errp = %6.3g\n', erru(k), errp(k));
end
%% Plot convergence rates
figure(2);
showrate2(N,erru,1,'-*','||Du-Du_h||',N,errp,1,'m-+','||p-p_h||');
end
%---------------------- End of function SQUARE -----------------------------
function z = f(p)
x = p(:,1); y = p(:,2);
z(:,1) = -4*pi^2*(2*cos(2*pi*x)-1).*sin(2*pi*y)+x.^2;
z(:,2) = 4*pi^2*(2*cos(2*pi*y)-1).*sin(2*pi*x);
end
function z = exactu(p)
x = p(:,1); y = p(:,2);
z(:,1) = (1-cos(2*pi*x)).*sin(2*pi*y);
z(:,2) = -(1-cos(2*pi*y)).*sin(2*pi*x);
end
function z=exactp(p)
x = p(:,1);
z = 1/3*x.^3;
end

% %---------------------- Sub functions called by CUBE ----------------------
% function z = f(p) % load data (right hand side function)
% x = p(:,1); y = p(:,2);
% z(:,1) = 2^10*( (1-6*x+6*x.^2).*(y-3*y.^2+2*y.^3) ...
%        + (x.^2-2*x.^3+x.^4).*(-3+6*y)...
%        - (-3+6*x).*(y.^2-2*y.^3+y.^4) );
% z(:,2) = -(2^10)*( (-3+6*x).*(y.^2-2*y.^3 ...
%        + y.^4)+(x-3*x.^2+2*x.^3).*(1-6*y+6*y.^2)...
%        + (1-6*x+6*x.^2).*(y-3*y.^2+2*y.^3) );
% end
% %--------------------------------------------------------------------------
% function z = exactu(p)
% x = p(:,1); y = p(:,2);
% z(:,1) = -(2^8)*(x.^2-2*x.^3+x.^4).*(2*y-6*y.^2+4*y.^3);
% z(:,2) = 2^8*(2*x-6*x.^2+4*x.^3).*(y.^2-2*y.^3+y.^4);
% end
% %--------------------------------------------------------------------------
% function z = exactp(p)
% x = p(:,1); y = p(:,2);
% z = -(2^8)*(2-12*x+12*x.^2).*(y.^2-2*y.^3+y.^4);
% end
%--------------------------------------------------------------------------
function z = g_D(p) % Dirichlet boundary condition
z = exactu(p);
end


function a = polya_fit_m(data, a, weight)
% POLYA_FIT_M   Maximum-likelihood Dirichlet-multinomial (Polya) mean.
%
% POLYA_FIT_M(data,a) returns the MLE (a) for the matrix DATA,
% subject to a constraint on sum(A).
% Each row of DATA is a histogram of counts.
% A is a row vector providing the initial guess for the parameters.
%
% POLYA_FIT_M(data,a,weight) returns the MLE where each histogram is weighted.
% WEIGHT is a column vector of numbers in [0,1] (default all ones).
%
% A is decomposed into S*M, where M is a vector such that sum(M)=1,
% and only M is changed by this function.  In other words, sum(A)
% is unchanged by this function.
%
% The algorithm is a generalized Newton iteration, described in
% "Estimating a Dirichlet distribution" by T. Minka.

% Written by Tom Minka

s = sum(a);
m = a/s;
[N,K] = size(data);

use_weight = (nargin > 2);
row = (rows(a) == 1);

for iter = 1:20
  old_m = m;
  if row
    a = s*m;
    for k = 1:length(m)
      dk = data(:,k);
      vdk = a(k)*di_pochhammer(a(k), dk);
      if use_weight
	vdk = vdk .* weight;
      end
      m(k) = sum(vdk);
    end
  else
    a = repmat(s*m, 1, N);
    vdata = a.*di_pochhammer(a, data);
    if use_weight
      vdata = vdata .* repmat(weight, rows(vdata), 1);
    end
    m = row_sum(vdata);
  end
  m = m ./ sum(m);
  if max(abs(m - old_m)) < 1e-4
    break
  end
end
a = s*m;


classdef test1DLHS < handle

    properties (Access = public)
        tol = 1e-12;
    end

    properties (Access = private)
        mesh
        K, M
        LHS, RHS
        funL2, funH1
    end

    methods (Access = protected, Static)

        function nu = createPoissonValue()
            nu = 0;
        end
    end

    methods (Access = public)

        function obj = test1DLHS()
            obj.init()
            obj.createMesh()
            obj.createLHS();
            obj.createRHS();
            obj.solveSystem();
        end

        function p = hasPassed(obj)
            x = load('test_1DLHS', 'x');
            p = isequal(x.x, obj.funH1.fValues);
        end

    end

    methods (Access = private)

        function init(obj)
        end

        function createMesh(obj)
            n = 50;
            xCoord =  0:1/(n-1):1;
            s.coord(:,1) = xCoord;
            s.coord(:,2) = zeros(n,1);
            s.connec(:,1) = 1:n-1;
            s.connec(:,2) = 2:n;
            s.kFace = -1;
            m = Mesh(s);
%             m.plot();
            obj.mesh = m;
        end

        function createLHS(obj)
            obj.createStifnessMatrix();
            obj.createMassMatrix();
            e = 0.1*obj.mesh.computeMeanCellSize();
            obj.LHS = e*obj.K + obj.M;
        end

        function createStifnessMatrix(obj)
            l.type = 'StiffnessMatrix';
            l.fun  = P1Function.create(obj.mesh,1);
            l.mesh = obj.mesh;
            lhs = LHSintegrator.create(l);
            obj.K = lhs.compute();
        end

        function createMassMatrix(obj)
            s.type = 'MassMatrix';
            s.fun  = P1Function.create(obj.mesh,1);
            s.mesh = obj.mesh;
            lhs    = LHSintegrator.create(s);
            obj.M  = lhs.compute();
        end

        function createRHS(obj)
            xCoord = obj.mesh.coord(:,1)';
            xmean = (max(xCoord)-min(xCoord))/2;
            f = heaviside(xCoord-xmean);

            s.mesh = obj.mesh;
            s.fValues = f;
            fL2 = P1Function(s);
%             fL2.plot;
            obj.RHS = obj.M*(fL2.fValues)';
            obj.funL2 = fL2;
        end

        function solveSystem(obj)
            s.type    =  'DIRECT';
            solver    = Solver.create(s);
            fH1Values = solver.solve(obj.LHS,obj.RHS);

            s.mesh = obj.mesh;
            s.fValues = fH1Values;
            fH1 = P1Function(s);
%             fH1.plot()
            obj.funH1 = fH1;
%             obj.mesh.plot();
%             hold on
%             xCoord = obj.mesh.coord(:,1)';
%             plot(xCoord,obj.funL2.fValues,'-+');
%             plot(xCoord,obj.funH1.fValues,'-+');
        end
    end

end


function [fMeanMag, fBValue, fStdDev, fAValue] = ...
        calc_bmemag(mag, fBinning)
    %CALC_BMEMAG Calculate Maximum Likelihood b-value
    % [fMeanMag, fBValue, fStdDev, fAValue] = ...
    %                   calc_bmemag(mag, fBinning)
    % Calculates the mean magnitute, the b-value based
    % on the maximum likelihood estimation, the a-value and the
    % standard deviation of the b-value
    %
    % Input parameters:
    %   mag             Vector of magnitudes
    %   fBinning        Bin size in magnitude (default 0.1)
    %
    % Output parameters:
    %   fMeanMag        Mean magnitude
    %   fBValue         b-value
    %   fStdDev         Standard deviation of b-value
    %   fAValue         a-value

    % Copyright (C) 2003 by Danijel Schorlemmer
    %
    % 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.
    %
    % Modified by Glenn Thompson 2014/06/14

    % Set the default value if not passed to the function
    if ~exist('fBinning')
        fBinning = 0.1;
    end

    % Calculate the minimum and mean magnitude, length of catalog
    nLen = length(mag);
    fMinMag = min(mag);
    fMeanMag = mean(mag);
    % Calculate the b-value (maximum likelihood)
    fBValue = (1/(fMeanMag-(fMinMag-(fBinning/2))))*log10(exp(1));
    % Calculate the standard deviation
    fStdDev = (sum((mag-fMeanMag).^2))/(nLen*(nLen-1));
    fStdDev = 2.30 * sqrt(fStdDev) * fBValue^2;
    % Calculate the a-value
    fAValue = log10(nLen) + fBValue * fMinMag;
end


% Notes for Laplace scheme and dynamic updating of parameters
%==========================================================================
n  = 128;                       % number of samples (time bins)
P  = 4;                         % true parameter
k  = n;                         % precision on fluctuations
pp = 2;                         % prior on parameter
m  = 8;                         % number of data
iS = eye(m,m)*2;                % error precision
s  = sqrtm(inv(iS));

p  = [0;0];                     % initial parameter estimates
for i = 1:n

    x      = 4 + randn(m,1);          % exogenous input
    z      = s*randn(m,1);            % error
    y      = P*x + z;                 % response
    e      = y - p(1)*x;              % prediction error
    Lp     = -e'*iS*x + pp*p(1);
    Lpp    = x'*iS*x  + pp;
    f      = [p(2); (-Lp -k*p(2))];
    dfdx   = [0 1;   -Lpp -k];
    p      = p + spm_dx(dfdx,f,1);
    X(:,i) = p;
    LP(i)  = Lp;
end

% results
%--------------------------------------------------------------------------
subplot(2,1,1)
plot(1:n,X)
title('generalised parameter estimates','FontSize',16)

subplot(2,1,2)
plot(1:n,LP)
title('energy gradient','FontSize',16)

return

% Notes
%==========================================================================
M.f = inline('[x(2); (u - K(1)*x(2))]','x','u','K','M');
M.m = 1;
M.n = 2;
M.l = 2;
M.x = [0;0];
M.u = 0;

N   = 128;
dt  = 1/64;
K   = 4;
[K0,K1,K2] = spm_kernels(M,K,N,dt);

subplot(2,1,1)
plot([1:N]*dt,K1);
xlabel('time (s)')
title('Kernels','FontSize',16)
legend('drive','trace')
axis square


function [ rel_err, snr ] = get_SNR( X, X0 )

noise = X - X0;
trueNorm = norm(X0);
rel_err = norm( noise ) / trueNorm;
snr = -20*log10( rel_err );

end


% test of shortest path using Dijkstra/A*

name = 'erdos';
name = 'rand_network';
name = 'rand';
name = 'square';
name = 'sanfrancisco';
name = 'northamerica';
name = 'sanjoaquin';
name = 'california';
name = 'oldenburg';
name = 'rand_clusters_triangulation';
name = 'randn_triangulation';
name = 'nefertiti.off';
name = 'rand_triangulation';

options.proba = 0.1;
options.alpha = 0.3;
options.beta = 0.3;

n = Inf;
switch lower(name)
    case 'square'
        n = 50^2;
    case {'rand_triangulation','randn_triangulation', 'rand_clusters_triangulation'}
        n = 5000;
    case 'rand'
        n = 100;
    case 'erdos'
        n = 100;
    case 'rand_network'
        n = 200;

end

disp('Loading file');
[A,vertex] = load_graph(name,n,options);

n = min(n,size(A,1));
A = A(1:n,1:n);
vertex = vertex(:,1:n);
A = max(A,A');

% select two points
clf;
hold on;
gplot(A,vertex');
axis tight;
axis square;
axis off;
start_point = ginput(1)';
plot( start_point(1), start_point(2), 'ro'  );
end_point = ginput(1)';
plot( end_point(1), end_point(2), 'bx'  );
hold off;

% find nearest node
d = compute_distance_to_points(vertex,start_point);
[tmp,start_point] = min(d);
d = compute_distance_to_points(vertex,end_point);
[tmp,end_point] = min(d);

% compute heuristic
v = vertex';
p = v(end_point,:);
H = sqrt( (p(1)-v(:,1)).^2 + (p(2)-v(:,2)).^2 );

% perform front propagation without heuristic
clear options;
options.end_points = end_point;
options.H = [];
disp('Performing classical Dijkstra');
[D,S] = perform_dijkstra(A, start_point, options);

% perform front propagation with euclidean heuristic
clear options;
options.end_points = end_point;
options.H = H;
disp('Performing classical A*');
[D1,S1] = perform_dijkstra(A, start_point, options);

% extract paths
path  = perform_dijkstra_path_extraction(A,D,end_point);
path1 = perform_dijkstra_path_extraction(A,D1,end_point);

% plot the paths
options.point_size = 5;
options.graph_style = 'k';
options.far_point_style = '';
clf;
subplot(1,2,1);
plot_dijkstra(A, vertex, S, path, start_point,end_point, options );
axis square;
title('Classical Dijkstra');
subplot(1,2,2);
plot_dijkstra(A, vertex, S1, path1, start_point,end_point, options );
axis square;
title('Algorihtm A^*');


function plotLinCon(A,b,Aeq,beq,data)
%PLOTLINCON Plot Linear Constraints on the current figure
%   plotLinCon(A,b,Aeq,beq)

%   Copyright (C) 2011 Jonathan Currie (IPL)

if(nargin < 5 || isempty(data))
    xl = xlim; yl = ylim;
else
    xl = data.xl; yl = data.yl;
end

hold on;

%Plot Inequality Constraints
if(~isempty(A))
    A = full(A);
    %Check for 1D, fake second column as zeros
    if(size(A,2) == 1)
        A = [A zeros(size(A,1),1)];
    end

    for i = 1:length(b)
        if(any(A(i,:)))
            if(all(A(i,:)) && b(i)) %normal, full A + b
                %%disp('normal')
                c = b(i) / A(i,2);
                m = -(b(i) / A(i,2)) / (b(i) / A(i,1));
                xi = (yl - c) / m;
            elseif(all(A(i,:)) && ~b(i)) %b is zero, line through origin
                %%disp('b is zero, full A')
                c = 0;
                m = -A(i,1)/A(i,2);
                xi = (yl - c) / m;
            elseif(b(i)) %bounds, b scales
                %%disp('partially empty A, b scales')
                m = inf;
            else %bounds, b is zero
                %%disp('partially empty A, empty b');
                m = inf;
            end

            %Normal Line
            if(~isinf(m) && ~isnan(m))
                %Grab a point (+1,+1) or (-1,+1)
                if(m <= 0)
                    x = [xi(1)+1; yl(1)+1];
                else
                    x = [xi(1)-1; yl(1)+1];
                end
                %Evaluate point to check direction of patch
                in = A(i,:)*x;
                %Patch based on type + gradient
                if(in > b(i)) % <=
                    %%disp('leq')
                    if(m <= 0)
                        %%disp('neg grad')
                        patch([xi(1) xl(2) xl(2) xi(2)],[yl(1) yl(1) yl(2) yl(2)],'y','FaceAlpha',0.3)
                    else
                        %%disp('pos grad')
                        patch([xi(1) xl(1) xl(1) xi(2)],[yl(1) yl(1) yl(2) yl(2)],'y','FaceAlpha',0.3)
                    end
                else % >=
                    %%disp('geq')
                    if(m <= 0)
                        %%disp('neg grad')
                        patch([xi(1) xl(1) xl(1) xi(2)],[yl(1) yl(1) yl(2) yl(2)],'y','FaceAlpha',0.3)
                    else
                        %%disp('pos grad')
                        patch([xi(1) xl(2) xl(2) xi(2)],[yl(1) yl(1) yl(2) yl(2)],'y','FaceAlpha',0.3)
                    end
                end
            %Bounds
            else
                if(A(i,1) == 0)
                    %%disp('A1 empty')
                    a = A(i,2);
%                     if(xl(1) == -1), xxl = 0.1; else xxl = 1; end
%                     in = a*(xl(1)+xxl) > b(i);
                    i1 = a*(yl(1))-b(i); i2 = a*(yl(2))-b(i);
                    if(i1 < i2), in = false; else in = true; end
                    vbnd = b(i)/a;
                    bndtype = 1; %horizontal (y)
                else
                    %%disp('A2 empty')
                    a = A(i,1);
%                     if(yl(1) == -1), yyl = 0.1; else yyl = 1; end
%                     in = a*(yl(1)+yyl) > b(i);
                    i1 = a*(xl(1))-b(i); i2 = a*(xl(2))-b(i);
                    if(i1 < i2), in = false; else in = true; end
                    vbnd = b(i)/a;
                    bndtype = 0; %vertical (x)
                end
                if(bndtype == 0) %vertical
                    %%disp('vertical bound')
                    if(in)
                        %%disp('lb')
                        patch([vbnd vbnd xl(1) xl(1)],[yl(1) yl(2) yl(2) yl(1)],'y','FaceAlpha',0.3)
                    else
                        %%disp('ub')
                        patch([vbnd vbnd xl(2) xl(2)],[yl(1) yl(2) yl(2) yl(1)],'y','FaceAlpha',0.3)
                    end
                else %horizontal
                    %%disp('horizontal bound')
                    if(in)
                        %%disp('lb')
                        patch([xl(1) xl(1) xl(2) xl(2)],[vbnd yl(1) yl(1) vbnd],'y','FaceAlpha',0.3)
                    else
                        %%disp('ub')
                        patch([xl(1) xl(1) xl(2) xl(2)],[vbnd yl(2) yl(2) vbnd],'y','FaceAlpha',0.3)
                    end
                end
            end
        end
    end
end

%Plot Equality Constraints
if(~isempty(Aeq))
    Aeq = full(Aeq);
    %Check for 1D, fake second column as zeros
    if(size(Aeq,2) == 1)
        Aeq = [Aeq zeros(size(Aeq,1),1)];
    end

    for i = 1:length(beq)
        if(any(Aeq(i,:)))
            if(all(Aeq(i,:)) && beq(i)) %normal, full A + b
                %disp('eq normal')
                c = beq(i) / Aeq(i,2);
                m = -(beq(i) / Aeq(i,2)) / (beq(i) / Aeq(i,1));
                xi = (yl - c) / m;
            elseif(all(Aeq(i,:)) && ~beq(i)) %b is zero, line through origin
                %disp('eq b is zero, full A')
                c = 0;
                m = -Aeq(i,1)/Aeq(i,2);
                xi = (yl - c) / m;
            elseif(beq(i)) %bounds, b scales
                %disp('eq partially empty A, b scales')
                m = inf;
            else %bounds, b is zero
                %disp('eq partially empty A, empty b');
                m = inf;
            end

            %Normal Line
            if(~isinf(m) && ~isnan(m))
                line(xi,yl);
            %Straight Line (H or V)
            else
                if(Aeq(i,1) == 0)
                    %disp('eq A1 empty')
                    a = Aeq(i,2);
                    vbnd = beq(i)/a;
                    line(xl,[vbnd vbnd]);
                else
                    %disp('eq A2 empty')
                    a = Aeq(i,1);
                    vbnd = beq(i)/a;
                    line([vbnd vbnd],yl);
                end

            end
        end
    end
end

hold off;

end


% Matlab Script: cluster_win.m
% ----------------------------
%
% Plots the distance window length and the time window length against magnitude
%
%

%% Magntiude areas
vMagnitude = (0:0.1:10);
vMagnitudea = (0:0.1:6.5);
vMagnitudeb = (6.5:0.1:10);

% Gardener and Knopoff, 1974
vSpaceGaKn74 = 10.^(0.1238*vMagnitude+0.983);
vTimeGaKn74 = 10.^(0.5409*vMagnitudea-0.547);
vTimeGaKn74b = 10.^(0.032*vMagnitudeb+2.7389); % M>=6.5

% Uhrhammer 1976
vSpaceUr = exp(-1.024+0.804*vMagnitude);
vTimeUr = exp(-2.87+1.235*vMagnitude);

% Gruenthal, 1985
vSpaceGr85 = 10.^(0.1060*vMagnitude+1.0982);
vTimeGr85 = 10.^(0.5055*vMagnitude-0.1329);
% Gruenthal, pers. communication
vSpaceGr = exp(1.77+sqrt(0.037+1.02*vMagnitude));
vTimeGra = exp(-3.95+sqrt(0.62+17.32*vMagnitudea));
vTimeGrb = 10.^(2.8+0.024*vMagnitudeb); % M >= 6.5

% Youngs, 1987
%% Maximum window limits
%% Space
vMagY1 = (0:0.01:2.43);
vMagY2 = (2.43:0.01:5.87);
vMagY3 = (5.87:0.01:10);
vSpaceY1 = 20+0*vMagY1;
vSpaceY2 = 10.^(0.1159*vMagY2+1.0197);
vSpaceY3 = 10.^(0.5281*vMagY3-1.3937);
%% Time
vMagTY1 = (0:0.01:3.89);
vMagTY2 = (3.89:0.01:10);
vTimeY1 = 30+0*vMagTY1;
vTimeY2 = 10.^(0.4916*vMagTY2-0.4317);

%% Minimum window limits
%% Space
vMinY1 = (0:0.01:4.41);
vMinY2 = (4.41:0.01:4.98);
vMinY3 = (4.98:0.01:6.42);
vMinY4 = (6.42:0.01:10);
vSpaceMinY1 = 10+0*vMinY1;
vSpaceMinY2 = 10.^(0.5281*vMinY2-1.3290);
vSpaceMinY3 = 10.^(0.3313*vMinY3-0.3490);
vSpaceMinY4 = 10.^(0.1154*vMinY4+1.0371);
%% Time
vMinTY1 = (0:0.01:5);
vMinTY2 = (5:0.01:10);
vTimeMinY1 = 5+0*vMinTY1;
vTimeMinY2 = 10.^(1.0526*vMinTY2-4.561);

% Plotting time window
hPlot = figure_w_normalized_uicontrolunits('tag','Timewindow','Numbertitle','off','Name','Time window length','Units','normalized');
hAxe = axes('tag','ax_timewindow','Nextplot','replace','box','on');

set(gca,'tag','ax_timewindow','Nextplot','replace','box','on','Xticklabel', [0 10 100]);
axs1=findobj('tag','ax_timewindow');
axes(axs1(1));
semilogy(vMagnitudea,vTimeGaKn74,'Color',[1 0 0],'Linewidth', 2);
hold on;
semilogy(vMagnitude,vTimeGr85,'Color',[0 0.5 0],'Linewidth', 2);
semilogy(vMagnitudea,vTimeGra,'Color',[0 0.8 0],'Linewidth', 2);
semilogy(vMagnitude,vTimeUr,'Color',[0.5 0 0],'Linewidth', 2);
semilogy(vMagTY1,vTimeY1,vMagTY2,vTimeY2,'Color',[0 0 1],'Linewidth', 2);
semilogy(vMagnitudeb,vTimeGaKn74b,'Color',[1 0 0],'Linewidth', 2);
semilogy(vMinTY1,vTimeMinY1,vMinTY2,vTimeMinY2,'Color',[0 0 1],'Linewidth', 2);
semilogy(vMagnitudeb,vTimeGrb,'Color',[0 0.8 0],'Linewidth', 2);
legend('Gardner & Knopoff (1974)','Gruenthal (1985)','Gruenthal (pers.)','Urhammer (1976)','Mod. Young (1987)');
xlabel('Magnitude');
ylabel('Time / [days]');
set(gca,'Xlim',[0 9]);%,'Ylim',[0.1 3000],'Yticklabel', [0.1 1 10 100 1000]);
grid on;

% Plotting space window
hPlot2 = figure_w_normalized_uicontrolunits('tag','Spacewindow','Numbertitle','off','Name','Spacial window length','Units','normalized');
hAxe2 = axes('tag','ax_spacewindow','Nextplot','replace','box','on');

set(gca,'tag','ax_spacewindow','Nextplot','replace','box','on');
axs1=findobj('tag','ax_spacewindow');
axes(axs1(1));
semilogy(vMagnitude,vSpaceGaKn74,'Color',[1 0 0],'Linewidth', 2);
hold on;
semilogy(vMagnitude,vSpaceGr85,'Color',[0 0.5 0],'Linewidth', 2);
semilogy(vMagnitude,vSpaceGr,'Color',[0 0.8 0],'Linewidth', 2);
semilogy(vMagnitude,vSpaceUr,'Color',[0.5 0 0],'Linewidth', 2);
semilogy(vMagY1,vSpaceY1,vMagY2,vSpaceY2,vMagY3,vSpaceY3,'Color',[0 0 1],'Linewidth', 2);
semilogy(vMinY1,vSpaceMinY1,vMinY2,vSpaceMinY2,vMinY3,vSpaceMinY3,vMinY4,vSpaceMinY4,'Color',[0 0 1],'Linewidth', 2);
legend('Gardner & Knopoff (1974)','Gruenthal (1985)','Gruenthal (pers. comm)','Urhammer (1976)','Mod. Young (1987)');
ylabel('Distance / [km]')
xlabel('Magnitude');
set(gca,'Xlim',[0 9],'Ylim', [5 300],'Yticklabel', [10 100]);
grid on;